Keel by ChimpLabs
Jump to page or section Esc
Core Concepts

Architecture

Three-layer separation of pure descriptors, capability services, and swappable Effect Layers.

@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).

Keel 3-Layer Architecture


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.Stream values. They are backpressured, lazy, and close when Stream.take(n) finishes or a Scope closes.
  • Background fibers and distributed locks bind to a Scope via Effect.forkScoped and Effect.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).

Workflow Durable Replay and LIFO Saga Compensation

  • 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 in E.
  • Step retries. ctx.step accepts { retries } as an attempt count (Schedule.recurs).
  • Race-free signals. ctx.waitForSignal subscribes to store.subscribeSignalsReady (or store.subscribeSignals via Stream.toQueue) before checking buffered rows in store.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:

Push-Driven Transactional Outbox Flow

  • QueueStore.subscribe(queue) wakes workers on new jobs. In QueuePostgresLive, workers claim jobs atomically with FOR UPDATE SKIP LOCKED and wait on PostgreSQL LISTEN/NOTIFY wakeups. In QueueSurrealLive, workers attach a LIVE SELECT on keel_jobs. In both backends, startWorker(..., { mode: "push" }) drains on startup and wakes only when new ready jobs arrive.
  • OutboxNotifier delivers post-commit notifications. In OutboxNotifierPostgresLive, transactional pg_notify fires only when an ACID transaction commits, with zero notifications on rollback. In OutboxNotifierSurrealLive, LIVE SELECT on keel_outbox gives the same post-commit guarantee.
  • Table reactivity offers two modes.
    • Durable atomic CDC. Set trackChanges: true on a Table and consume TableChangeTopic(MyTable) via durableStream or liveStream. 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.

4. Bounded-context services (Service vs ExternalSystem)

Keel models system boundaries with two Context.Service primitives:

  • ExternalSystem wraps third-party vendors you do not own (such as Stripe, Resend, or shipping APIs) behind an anti-corruption layer with resilience policies and declared secrets.
  • Service (@chimp-labs/keel/service) wraps your own domain bounded contexts (such as Inventory, Billing, or Fulfillment) with owned resources, declared dependencies, 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 as TestClock, validate inputs and outputs with Effect Schema, run verifySecrets(resources) at startup, and bind daemons to the layer Scope.
  • Extracted remote microservice. Replace InventoryService.live(...) with InventoryService.client(transport, { timeout, retries }) on the caller side. Expose the implementation on the server side via makeServiceDispatcher(InventoryService) or makeServiceDispatcher(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 ServiceHandlers restricts its error channel to ServiceOperationErrorOf<Spec>, which is the union of errors schemas and defaults to never when omitted. Returning an unhandled insertRow or ExternalSystem call fails to compile until you map it to a declared domain error or escalate it with Effect.orDie.
  • Runtime fail-fast. In .live, .mock, .client, and makeServiceDispatcher, if a handler or remote server fails with a typed error outside spec.errors (for example, through as any or wire drift), Keel escalates it to a defect via Effect.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 inside observeOperation({ component: "service", resource: serviceName, operation: opName }). This records keel.service.<op> tracing spans and KeelMetrics.

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. KeelError and KEEL_ERROR_CLASSIFICATIONS map every Keel TaggedError, PostgresClientError, SurrealClientError, and Effect SchemaError to a category, httpStatus, and retryable flag via classifyKeelError and reportCause.
  • Interrupt-safe boundaries. withErrorBoundary and tapErrorBoundary catch 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, and startCron) accepts onError, and continuous stream daemons also accept restartSchedule. Faults increment KeelMetrics.daemonErrorsTotal, invoke structured hooks, and resume cleanly.

Native Effect observability (@chimp-labs/keel/observability)

  • observeOperation instruments operations with an Effect tracing span (keel.<component>.<operation>), structured log annotations, and low-cardinality KeelMetrics (keel_operations_total, keel_operation_duration_ms, keel_errors_total, keel_daemon_errors_total, and keel_cache_requests_total).
  • High-cardinality identifiers (jobId, runId, and sequence) go into spanAttributes only, 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.