@chimp-labs/keel separates domain contracts, runtime capabilities, and infrastructure wiring into three independent layers. Domain services never import database drivers, cloud SDKs, or IaC libraries. Core @chimp-labs/keel has zero optional peer dependencies—only effect@^4.0.0. Optional database adapters live in standalone packages: @chimp-labs/keel-postgres for PostgreSQL 17 (pg) and @chimp-labs/keel-surreal for SurrealDB 4 (surrealdb).

1. The 3-layer pattern
Layer 1. Pure descriptor classes with zero I/O
A class factory creates each of the 17 core primitives in @chimp-labs/keel (Table, Collection, Bucket, KV, Cache, Lock, RateLimit, Topic, JobQueue, Cron, IAM, Service, ExternalSystem, Secret, Flag, Idempotency, and Topology), plus DurableStream in @chimp-labs/keel-streams and Workflow/Signal in @chimp-labs/keel-workflow via the Open Plugin Protocol. Each class holds only static metadata, Effect Schema codecs, and two symbols:
KeelKindSym(Symbol.for("@chimp-labs/keel/Kind"))KeelMetaSym(Symbol.for("@chimp-labs/keel/Meta"))
Descriptors perform no I/O on import, so both application code and IaC stacks such as Alchemy can import them.
Layer 2. Split capabilities in Effect’s R channel
Each subsystem splits its baseline capability from optional capabilities:
Core capability (R) |
Optional capability (R) |
Why they are split |
|---|---|---|
EventBus (live pub/sub) |
EventStore (durable log) |
Apps without durable event storage fail at compile time if code calls durableStream. |
RelationalStore (SQL + JSONB tables, joins, ACID tx) |
PgCapabilities |
PostgreSQL 17 adds native JSONB GIN/expression indexes, FOR UPDATE SKIP LOCKED, and LISTEN/NOTIFY watches. |
ObjectStore (put, get, list) |
ObjectPresigner (presignGet, presignPut) |
Local filesystem and Memory stores cannot issue S3 signed URLs. |
RelationalStore (portable SQL) |
PgCapabilities (FOR UPDATE SKIP LOCKED) |
Portable code runs identically on SQLite, PostgreSQL 17, and SurrealDB 4, while PostgreSQL-only features stay explicit in R. |
QueueStore (ack, nack, DLQ) |
DelayedQueue (enqueueDelayed) |
Not every queue backend supports arbitrary delayed delivery. |
KeyValueStore (get, set) |
AtomicKV (setIfNotExists, incr, CAS) |
Simple caches do not always guarantee atomic compare-and-swap. |
Layer 3. Swappable layers and native Stream and Scope
- Cursors, listings, byte bodies, and subscriptions return native
Stream.Streamvalues. They are backpressured, lazy, and close whenStream.take(n)finishes or aScopecloses. - Background fibers and distributed locks bind to a
ScopeviaEffect.forkScopedandEffect.acquireRelease. On shutdown or interruption, subscriptions unsubscribe, locks release, and workers drain.
2. Durable workflows and LIFO sagas (@chimp-labs/keel-workflow)
Workflow and Signal live in the official @chimp-labs/keel-workflow plugin package and plug directly into createKeel({ resources }) via Keel’s Open Plugin Protocol. Workflow journals every completed ctx.step, ctx.sleep, ctx.waitForEvent, and ctx.waitForSignal into WorkflowStore. Supported stores include WorkflowStoreMemory, SQLite/SQL via WorkflowStoreFromTable, multi-replica PostgreSQL 17 via @chimp-labs/keel-workflow/postgres (WorkflowStorePostgresLive with LISTEN/NOTIFY signals), and SurrealDB 4 via @chimp-labs/keel-workflow/surreal (WorkflowStoreSurrealLive).

- Crash and resume. Re-running
runWorkflow(wf, { runId, input })replays completed steps from the journal without re-executing side effects. - LIFO saga rollback. Every step with
{ compensate }pushes onto a reverse stack, including steps replayed from a prior attempt. When a later step fails, compensations run in reverse order and are marked"compensated"so they never run twice. The original typed error returns inE. - Step retries.
ctx.stepaccepts{ retries }as an attempt count (Schedule.recurs). - Race-free signals.
ctx.waitForSignalsubscribes tostore.subscribeSignalsReady(orstore.subscribeSignalsviaStream.toQueue) before checking buffered rows instore.takeSignal, so concurrent signals cannot slip through.
3. Push-driven workers, Table CDC, and zero-polling outbox
Tight while (true) sleep(25ms) polling loops waste database CPU and prevent serverless databases like SurrealDB Earth or scale-to-zero managed PostgreSQL 17 from idling down.
Keel avoids idle polling in both JobQueue and TransactionalOutbox:

QueueStore.subscribe(queue)wakes workers on new jobs. InQueuePostgresLive, workers claim jobs atomically withFOR UPDATE SKIP LOCKEDand wait on PostgreSQLLISTEN/NOTIFYwakeups. InQueueSurrealLive, workers attach aLIVE SELECTonkeel_jobs. In both backends,startWorker(..., { mode: "push" })drains on startup and wakes only when new ready jobs arrive.OutboxNotifierdelivers post-commit notifications. InOutboxNotifierPostgresLive, transactionalpg_notifyfires only when an ACID transaction commits, with zero notifications on rollback. InOutboxNotifierSurrealLive,LIVE SELECTonkeel_outboxgives the same post-commit guarantee.- Table reactivity offers two modes.
- Durable atomic CDC. Set
trackChanges: trueon aTableand consumeTableChangeTopic(MyTable)viadurableStreamorliveStream. Row mutations write outbox entries in the same ACID transaction. - Ephemeral live watch. Use
watchTable(MyTable)for best-effort, post-commit UI updates or local cache invalidation without outbox persistence.
- Durable atomic CDC. Set
4. Bounded-context services (Service vs ExternalSystem)
Keel models system boundaries with two Context.Service primitives:
ExternalSystemwraps third-party vendors you do not own (such as Stripe, Resend, or shipping APIs) behind an anti-corruption layer with resilience policies and declaredsecrets.Service(@chimp-labs/keel/service) wraps your own domain bounded contexts (such as Inventory, Billing, or Fulfillment) with ownedresources, declareddependencies, closed domain error contracts, telemetry, and lifecycle hooks.
Modular monolith to microservices with zero caller changes
Callers always depend on the Service tag (yield* InventoryService) and see the same ServiceShape under every deployment topology:
- In-process modular monolith. Provide
InventoryService.live(handlers, { verifySecrets: true, daemons: [startWorker(...)] }). Handlers execute in-process, preserve caller fiber context such asTestClock, validate inputs and outputs with EffectSchema, runverifySecrets(resources)at startup, and binddaemonsto the layerScope. - Extracted remote microservice. Replace
InventoryService.live(...)withInventoryService.client(transport, { timeout, retries })on the caller side. Expose the implementation on the server side viamakeServiceDispatcher(InventoryService)ormakeServiceDispatcher(InventoryService, handlers). Caller code does not change.
import { Schema } from "effect"
import { Service, makeServiceDispatcher } from "@chimp-labs/keel"
class InsufficientStockError extends Schema.TaggedError<InsufficientStockError>()(
"InsufficientStockError",
{ sku: Schema.String, available: Schema.Int },
) {}
class InventoryService extends Service<InventoryService>()("inventory", {
resources: [StockTable, StockReservedTopic],
dependencies: [],
operations: {
reserve: {
input: Schema.Struct({ sku: Schema.String, qty: Schema.Int }),
output: Schema.Struct({ reservationId: Schema.String }),
errors: [InsufficientStockError] as const,
},
getStock: {
input: Schema.Struct({ sku: Schema.String }),
output: Schema.Struct({ available: Schema.Int }),
// Omitting `errors` locks handler `E` to `never`
},
},
}) {}
// 1. Modular monolith: in-process `.live` with optional `verifySecrets` & scoped `daemons`
const InventoryLive = InventoryService.live(
{
reserve: ({ sku, qty }) => /* E must be InsufficientStockError (never SqlQueryError!) */ ...,
getStock: ({ sku }) => /* E must be never */ ...,
},
{ verifySecrets: true, daemons: [/* scoped startWorker / startOutboxRelay / startCron */] },
)
// 2. Microservice extraction: swap ONLY the Layer — callers stay untouched
const dispatch = makeServiceDispatcher(InventoryService) // serves `{ operation, input }`
const InventoryRemote = InventoryService.client(
(req) => /* HTTP/RPC call returning `{ ok: true, data } | { ok: false, error }` */ ...,
{ timeout: "3 seconds", retries: 2 },
)
Compile-time and runtime fail-fast error contracts
Internal storage and adapter errors such as SqlQueryError, ObjectStoreError, and KvStoreError must never leak across a bounded context:
- Compile-time enforcement. Each handler in
ServiceHandlersrestricts its error channel toServiceOperationErrorOf<Spec>, which is the union oferrorsschemas and defaults toneverwhen omitted. Returning an unhandledinsertRoworExternalSystemcall fails to compile until you map it to a declared domain error or escalate it withEffect.orDie. - Runtime fail-fast. In
.live,.mock,.client, andmakeServiceDispatcher, if a handler or remote server fails with a typed error outsidespec.errors(for example, throughas anyor wire drift), Keel escalates it to a defect viaEffect.die(new ServiceUndeclaredError({ service, operation, errorTag, cause })). Pure fiber interruptions and existing defects propagate unchanged. - Built-in telemetry. Every
.live,.mock,.client, and direct dispatcher call runs insideobserveOperation({ component: "service", resource: serviceName, operation: opName }). This recordskeel.service.<op>tracing spans andKeelMetrics.
5. Production hardening architecture
Keel includes a zero-dependency production layer built on Effect v4:
Error boundaries and daemon supervision (@chimp-labs/keel/error)
- Semantic classification.
KeelErrorandKEEL_ERROR_CLASSIFICATIONSmap every KeelTaggedError,PostgresClientError,SurrealClientError, and EffectSchemaErrorto acategory,httpStatus, andretryableflag viaclassifyKeelErrorandreportCause. - Interrupt-safe boundaries.
withErrorBoundaryandtapErrorBoundarycatch typed failures and unexpected defects (Cause.die) at HTTP, RPC, and CLI entrypoints while letting pure fiber interruptions propagate. - Supervised daemons. Every background runner (
startWorker,startOutboxRelay, andstartCron) acceptsonError, and continuous stream daemons also acceptrestartSchedule. Faults incrementKeelMetrics.daemonErrorsTotal, invoke structured hooks, and resume cleanly.
Native Effect observability (@chimp-labs/keel/observability)
observeOperationinstruments operations with an Effect tracing span (keel.<component>.<operation>), structured log annotations, and low-cardinalityKeelMetrics(keel_operations_total,keel_operation_duration_ms,keel_errors_total,keel_daemon_errors_total, andkeel_cache_requests_total).- High-cardinality identifiers (
jobId,runId, andsequence) go intospanAttributesonly, never metric labels. This keeps Prometheus and OpenTelemetry cardinality bounded.
6. Infrastructure inference (KeelKindSym and inferKeelInfra)
Because @chimp-labs/keel has no IaC dependencies, any deployment tool can inspect your descriptors via inferKeelInfra(descriptors). When you pass Service descriptors, inferKeelInfra traverses service.resources with cycle protection to collect every owned Table, Topic, Bucket, Secret, and ExternalSystem. It also builds the service dependency graph in plan.domain.services:
import { inferKeelInfra } from "@chimp-labs/keel"
const plan = inferKeelInfra([InventoryService, BillingService])
// plan.needsDatabase === true // (also aliased as `plan.needsSurreal`)
// plan.database.tables === ["stock", "invoices"] // recursively extracted from service.resources
// plan.secrets === ["STRIPE_API_KEY"] // extracted from owned Secrets & ExternalSystems
// plan.domain.services === [
// { name: "inventory", operations: ["reserve", "getStock"], secrets: [], dependencies: [] },
// {
// name: "billing",
// operations: ["chargeOrder"],
// secrets: ["STRIPE_API_KEY"],
// dependencies: [
// { kind: "service", name: "inventory" },
// { kind: "external-system", name: "payments" },
// ],
// },
// ]
Pass plan or the raw descriptors into an IaC module so adding a Bucket or Service provisions its infrastructure. Pass the same descriptor list to verifySecrets(descriptors) or enable { verifySecrets: true } on Service.live to catch missing secrets at startup.