Keel by ChimpLabs
Jump to page or section Esc
Primitives

Service

Bounded-context service contracts declaring owned resources, dependencies, closed error boundaries, and monolith-to-microservice extraction without caller rewrites.

Service is the entry point of a Keel application. A service declares:

  1. resources, the tables, buckets, topics, queues, crons, workflows, and secrets it owns.
  2. dependencies, the other Keel services or ExternalSystems it calls.
  3. operations, its typed inputs, outputs, and closed error contracts.

From that declaration, Keel infers the scoped infrastructure graph without YAML configuration and computes topological deployment order. It enforces closed error boundaries at compile time and runtime. You can run all services in-process as a modular monolith, then extract any service into its own Cloudflare Worker or Docker container without changing caller code.


Declaring a Service

Plain TypeScript SDK (@chimp-labs/keel/sdk)

import { Schema } from "effect"
import { k } from "@chimp-labs/keel/sdk"

export class OutOfStockError extends Schema.TaggedError<OutOfStockError>()(
  "OutOfStockError",
  { sku: Schema.String, available: Schema.Int }
) {}

export const InventoryService = k.service("inventory", {
  resources: [StockTable, StockReservedTopic],
  operations: {
    reserve: {
      input: k.object({ sku: k.string(), qty: k.int() }),
      output: k.object({ reservationId: k.string() }),
      errors: [OutOfStockError],
    },
  },
})

export const OrdersService = k.service("orders", {
  resources: [OrdersTable, ReceiptsBucket, OrderPlacedTopic, StripeKey],
  dependencies: [InventoryService],
  operations: {
    placeOrder: {
      input: k.object({ userId: k.string(), sku: k.string(), qty: k.int() }),
      output: k.object({ orderId: k.string() }),
      errors: [OutOfStockError],
    },
  },
})

Configuration options

Option Type Required Description
operations Record<string, { input, output, errors? }> Yes Typed operation contracts. Omitting errors restricts handlers to never so undeclared errors cannot leak.
resources readonly KeelResource[] | Record<string, KeelResource> No Owned resources scoped to this service unit on deploy. Owned Topics and trackChanges: true CDC tables are also inferred into effectivePublishes.
dependencies readonly (Service | ExternalSystem)[] No Upstream services and external systems used to generate typed RPC bindings and topological deploy order.
publishes readonly TopicDef[] No Explicit list of Topic classes/descriptors this service publishes. Combined with owned Topic resources and CDC tables into effectivePublishes.
subscribes readonly TopicDef[] No Class-typed Topic descriptors this service consumes. Mapped inside the service implementation via k.implement(Service, (ctx, on) => ({ ..., subscriptions: [on(Topic, handler)] })) or Service.live(..., { subscriptions: (on) => [...] }).

Tip: When composing multiple bounded-context services in one deployable unit, use Modulith (k.modulith + k.implement) to wire in-process implementations, stubs, remote RPC clients, and transactional outbox publishing without calling .live(), .mock(), or .client() directly.

Effect v4 (@chimp-labs/keel/service)

import { Schema } from "effect"
import { Service } from "@chimp-labs/keel/service"

export class InventoryService extends Service<InventoryService>()("inventory", {
  resources: [StockTable, StockReservedTopic],
  operations: {
    reserve: {
      input: Schema.Struct({ sku: Schema.String, qty: Schema.Int }),
      output: Schema.Struct({ reservationId: Schema.String }),
      errors: [OutOfStockError] as const,
    },
  },
}) {}

Operations reference

Wiring in-process (.live)

await using inventoryApi = await keel.inventory.live(
  {
    reserve: async ({ sku, qty }) => {
      const row = await keel.stock.getById(sku)
      if (row.available < qty) {
        throw new OutOfStockError({ sku, available: row.available })
      }
      await keel.stock.updateById(sku, { available: row.available - qty })
      return { reservationId: `res_${crypto.randomUUID()}` }
    },
  },
  {
    verifySecrets: true,
    daemons: [() => keel.stockView.start()],
  }
)

const res = await inventoryApi.reserve({ sku: "KEEL-M", qty: 2 })

Extracting to a remote microservice (.dispatcher and .client)

When you move InventoryService into its own Worker or Docker container, expose it with .dispatcher(handlers) and connect callers with .client(transport, resilienceOpts). Caller code stays identical:

// Server side (mounts onto HTTP / Hono / Cloudflare fetch handler)
await using dispatch = await keel.inventory.dispatcher(handlers)
const response = await dispatch({ operation: "reserve", input: reqBody })

// Caller side (same typed interface as .live(), plus timeout and retries!)
await using remoteInventory = await keel.inventory.client(
  async (req) => {
    const res = await fetch(`${INVENTORY_URL}/_keel/rpc/inventory`, {
      method: "POST",
      body: JSON.stringify(req),
    })
    return res.json()
  },
  {
    timeout: "3 seconds",
    retries: 2,
  }
)

Mocking in unit tests (.mock)

await using mockInventory = await keel.inventory.mock({
  reserve: async () => ({ reservationId: "res_test" }),
})

Complete SDK and Effect API mapping

SDK method (keel.<svc>.*) Effect function (@chimp-labs/keel/service) Description
live(handlers, opts?) Service.live(handlers, opts?) Bind an in-process implementation with secret preflight and scoped daemons.
mock(handlers) Service.mock(handlers) Bind a zero-infrastructure test mock that enforces schemas and error contracts.
client(transport, opts?) Service.client(transport, opts?) Create a typed remote RPC client with timeout, retries, and optional workload identity signing.
dispatcher(handlers) makeServiceDispatcher(Service, handlers) Create a transport-agnostic { operation, input } JSON RPC dispatcher.

Closed error contracts and failure modes

In Effect v4, ServiceHandlers restricts each handler’s error channel to the declared errors union, defaulting to never. Unhandled SqlQueryError or ObjectStoreError failures fail tsc --noEmit. At runtime in both the TypeScript SDK and Effect, any undeclared failure produces a ServiceUndeclaredError defect with HTTP status 500.

Error tag Category HTTP status Retryable When it occurs
Declared errors Domain Custom No Expected domain error listed in operation.errors.
ServiceTransportError unavailable 503 Yes Network or wire failure occurs while calling a remote .client().
ServiceUndeclaredError internal 500 No Handler or remote server emits an error not declared on the contract.
SchemaError invalid 400 No Operation input or output fails schema validation.

Backends and infrastructure

Passing services to inferKeelInfra([OrdersService, InventoryService]) or @chimp-labs/keel-alchemy generates four outputs:

  • Topological deploy order, deploying inventory before orders.
  • Least-privilege bindings that attach R2 or Garage buckets, crons, and secrets only to their owning units.
  • RPC wiring using Cloudflare SERVICE_INVENTORY Service Bindings or Docker internal URLs.
  • HTTP endpoints at /_keel/rpc/:service and /readyz for health checks.

Testing in memory

await using keel = await createKeel({
  backend: "memory",
  resources: { stock: StockTable, inventory: InventoryService },
  ensureAll: true,
})

await keel.stock.insert({ sku: "KEEL-M", available: 1 })
await using api = await keel.inventory.live(handlers)

const failed = await tryKeel(() => api.reserve({ sku: "KEEL-M", qty: 5 }))
// failed.ok === false, failed.error.tag === "OutOfStockError"