Keel by ChimpLabs
Jump to page or section Esc
Primitives

Modulith

Opinionated single-unit composition of bounded-context services with shared database defaults, inferred and explicit event contracts, boundary enforcement, and zero-rewrite extraction to multi-unit Topology.

Modulith is an opinionated Topology for building a modular monolith in Keel. You compose bounded-context Services into one deployable unit with a shared database by default, enforce strict module boundaries at definition time, and extract any service into its own container or Cloudflare Worker later with one call (App.extract(...)).

Modulith enforces five architectural guarantees automatically:

  1. Single unit & shared database by default: All services deploy as one unit (unitName: "app") with isolation: { database: "shared", buckets: "shared", workloadAuth: "off" }.
  2. Inferred + explicit publishes: A service’s published topics are the union of explicit publishes: [OrderPlaced], any Topic declared in resources, and the CDC TableChangeTopic of any owned Table with trackChanges: true.
  3. Class-typed subscribes owned by each service: There are no global event handlers on Modulith. Each service declares subscribes: [PaymentFailed] using the actual Topic class/descriptor and maps every subscription inside its own implementation (compile-time exhaustive).
  4. Strict boundary validation at definition time: Rejects shared mutable tables/buckets/queues/crons across services, rejects cross-service foreign keys by default (allowCrossServiceForeignKeys: false), rejects duplicate topic publishers, rejects dangling subscriptions, and detects dependency cycles.
  5. Zero .live() / .mock() / .client() boilerplate in the SDK: Compose services with k.implement(Service, (ctx, on) => ...) and App.start({ backend, services }), where each service slot accepts an implementation, a plain stub object, or a remote RPC config ({ url | binding | transport }).

Defining a Modulith (Plain TypeScript SDK)

1. Declare Topics, Queues, Tables, and bounded Services

Each service owns its own tables and queues, declares sync RPC dependencies, and declares async publishes and subscribes contracts. Here BillingService and NotificationsService both consume OrderPlaced (fan-out), while NotificationsService owns an EmailQueue (JobQueue) for retryable background delivery:

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 OrderPlaced = k.topic(
  "orders.placed",
  k.object({
    orderId: k.string(),
    userEmail: k.string(),
    amountCents: k.int(),
  })
)

export const PaymentFailed = k.topic(
  "billing.payment_failed",
  k.object({
    orderId: k.string(),
    userEmail: k.string(),
    reason: k.string(),
  })
)

export const StockTable = k.table("stock", {
  sku: k.text().primaryKey(),
  available: k.integer(),
})

export const OrdersTable = k.table("orders", {
  id: k.uuid().primaryKey(),
  userEmail: k.text(),
  sku: k.text(),
  qty: k.integer(),
  status: k.text(),
})

export const InvoicesTable = k.table("invoices", {
  id: k.uuid().primaryKey(),
  orderId: k.text(),
  amountCents: k.integer(),
  status: k.text(),
})

export const EmailQueue = k.queue(
  "notifications.emails",
  k.object({
    to: k.string(),
    orderId: k.string(),
    template: k.string(),
  }),
  {
    maxAttempts: 3,
    visibilityTimeout: "30 seconds",
    dlq: true,
  }
)

export const DeliveriesTable = k.table("email_deliveries", {
  id: k.uuid().primaryKey(),
  to: k.text(),
  orderId: k.text(),
  template: k.text(),
})

export const InventoryService = k.service("inventory", {
  resources: { stock: StockTable },
  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: { orders: OrdersTable },
  dependencies: [InventoryService],
  publishes: [OrderPlaced],
  subscribes: [PaymentFailed],
  operations: {
    place: {
      input: k.object({
        userEmail: k.string(),
        sku: k.string(),
        qty: k.int(),
        amountCents: k.int(),
      }),
      output: k.object({ orderId: k.string() }),
      errors: [OutOfStockError],
    },
    get: {
      input: k.object({ orderId: k.string() }),
      output: k.object({ orderId: k.string(), status: k.string() }),
    },
  },
})

export const BillingService = k.service("billing", {
  resources: { invoices: InvoicesTable },
  publishes: [PaymentFailed],
  subscribes: [OrderPlaced],
  operations: {
    getInvoice: {
      input: k.object({ orderId: k.string() }),
      output: k.object({ status: k.string() }),
    },
  },
})

export const NotificationsService = k.service("notifications", {
  resources: { emails: EmailQueue, deliveries: DeliveriesTable },
  subscribes: [OrderPlaced, PaymentFailed],
  operations: {
    enqueueEmail: {
      input: k.object({ to: k.string(), orderId: k.string(), template: k.string() }),
      output: k.object({ jobId: k.string() }),
    },
    listDeliveries: {
      input: k.object({}),
      output: k.array(
        k.object({ to: k.string(), orderId: k.string(), template: k.string() })
      ),
    },
  },
})

2. Compose the Modulith

export const App = k.modulith("commerce", {
  services: [
    InventoryService,
    OrdersService,
    BillingService,
    NotificationsService,
  ],
  entrypoint: "./src/index.ts",
  public: { domain: "api.acme.com" },
})

App is a full TopologyDef (isTopology(App) === true) with an additional App.modulithPlan containing serviceOrder, publishes, subscribes, serviceEdges, and fan-out eventEdges (here orders -> billing and orders -> notifications on orders.placed, plus billing -> orders and billing -> notifications on billing.payment_failed).

3. Implement each service with k.implement

Each implementation receives a boundary-scoped ctx and a class-typed on binder:

  • ctx.<resource> / ctx.bind(Resource) — accesses only resources owned by that service (tables, queues, buckets, etc.) or explicitly listed in App.shared.
  • ctx.<dep> — calls only services declared in dependencies (for example ctx.inventory.reserve(...)).
  • ctx.publish(Topic, payload) — only allows topics in that service’s effectivePublishes (publishes directly on the event bus).
  • ctx.transaction(async (tx) => { ... await tx.publish(Topic, payload) }) — tx.publish(...) automatically enqueues into the transactional outbox, so DB writes and emitted events commit or roll back atomically.
  • subscriptions: [on(Topic, async (ev) => ..., { onError? })] — consumes each subscribed topic with full payload inference; TypeScript checks exhaustively that every topic in subscribes is handled.
  • daemons: [k.daemon(...)] — declares service-owned background daemons that boot on App.start(...) and shut down cleanly on app.close(): k.daemon(Queue, handler, opts?), k.daemon(Cron, handler, opts?), k.daemon(Table, handler, opts?) (mode: "watch" | "cdc"), k.daemon(Topic, handler, opts?) (mode: "live" | "durable"), k.daemon(async (signal) => ..., opts?), or a custom () => DisposableHandle thunk. Owned queue, cron, table, and topic daemons are checked against Service boundaries at compile time and runtime.
export const inventoryImpl = k.implement(InventoryService, (ctx) => ({
  reserve: async ({ sku, qty }) => {
    const row = await ctx.stock.getById(sku)
    if (row.available < qty) {
      throw new OutOfStockError({ sku, available: row.available })
    }
    await ctx.stock.updateById(sku, { available: row.available - qty })
    return { reservationId: `res_${crypto.randomUUID()}` }
  },
}))

export const ordersImpl = k.implement(OrdersService, (ctx, on) => ({
  place: async ({ userEmail, sku, qty, amountCents }) => {
    await ctx.inventory.reserve({ sku, qty })
    return ctx.transaction(async (tx) => {
      const order = await tx.orders.insert({
        userEmail,
        sku,
        qty,
        status: "placed",
      })
      // Automatically routed through the transactional outbox!
      await tx.publish(OrderPlaced, {
        orderId: order.id,
        userEmail,
        amountCents,
      })
      return { orderId: order.id }
    })
  },
  get: async ({ orderId }) => {
    const row = await ctx.orders.getById(orderId)
    return { orderId: row.id, status: row.status }
  },
  subscriptions: [
    on(PaymentFailed, async (ev) => {
      await ctx.orders.updateById(ev.payload.orderId, {
        status: "payment_failed",
      })
    }),
  ],
}))

export const billingImpl = k.implement(BillingService, (ctx, on) => ({
  getInvoice: async ({ orderId }) => {
    const rows = await ctx.invoices.select({ orderId })
    return { status: rows[0]?.status ?? "missing" }
  },
  subscriptions: [
    on(OrderPlaced, async (ev) => {
      const charged = await chargeCard(ev.payload.orderId, ev.payload.amountCents)
      if (!charged.ok) {
        await ctx.invoices.insert({
          orderId: ev.payload.orderId,
          amountCents: ev.payload.amountCents,
          status: "failed",
        })
        // Chained event: consumed by both OrdersService and NotificationsService
        await ctx.publish(PaymentFailed, {
          orderId: ev.payload.orderId,
          userEmail: ev.payload.userEmail,
          reason: charged.reason,
        })
        return
      }
      await ctx.invoices.insert({
        orderId: ev.payload.orderId,
        amountCents: ev.payload.amountCents,
        status: "paid",
      })
    }),
  ],
}))

4. Consuming events and running a Queue / Worker inside a service

A common pattern in a modular monolith is event fan-out into a service-owned JobQueue: event consumers (on(Topic, ...)) stay fast by enqueueing work onto a typed JobQueue, and a scoped background worker in daemons processes jobs with retries, concurrency, and a dead-letter queue (DLQ).

Because EmailQueue is declared in NotificationsService.resources, only NotificationsService can enqueue to or consume from it — any other service trying to claim or ctx.bind(EmailQueue) is rejected by Modulith boundary checks:

export const notificationsImpl = k.implement(NotificationsService, (ctx, on) => ({
  enqueueEmail: async (input) => {
    const jobId = await ctx.emails.enqueue(input)
    return { jobId }
  },
  listDeliveries: async () => {
    const rows = await ctx.deliveries.select()
    return rows.map((r) => ({
      to: r.to,
      orderId: r.orderId,
      template: r.template,
    }))
  },
  // Fan-out event consumers: react to events from multiple services
  subscriptions: [
    on(
      OrderPlaced,
      async (ev) => {
        await ctx.emails.enqueue({
          to: ev.payload.userEmail,
          orderId: ev.payload.orderId,
          template: "order_confirmation",
        })
      },
      {
        onError: (report) =>
          console.error("OrderPlaced consumer failed:", report.tag, report.message),
      }
    ),
    on(PaymentFailed, async (ev) => {
      await ctx.emails.enqueue({
        to: ev.payload.userEmail,
        orderId: ev.payload.orderId,
        template: "payment_failed",
      })
    }),
  ],
  // Scoped queue worker: boots on App.start(), stops cleanly on app.close()
  daemons: [
    k.daemon(
      EmailQueue,
      async (job) => {
        await sendTransactionalEmail(
          job.payload.to,
          job.payload.template,
          job.payload.orderId
        )
        await ctx.deliveries.insert({
          to: job.payload.to,
          orderId: job.payload.orderId,
          template: job.payload.template,
        })
        // Automatically acked on return; throwing retries up to maxAttempts, then moves to DLQ
      },
      {
        mode: "push",
        concurrency: 4,
        onError: (report) =>
          console.error("Email worker failed:", report.tag, report.message),
      }
    ),
  ],
}))

k.daemon(...) also supports scheduled crons, live or durable CDC table listeners (mode: "watch" default, or mode: "cdc" for tables with trackChanges: true), live or durable catch-up-and-tail topic listeners (mode: "live" | "durable"), and custom AbortSignal-managed background loops (plain () => ctx.emails.startWorker(...) thunks work too).

Pass checkpoint: "<id>" on a Topic (implies mode: "durable") or Table CDC daemon to automatically persist the last processed sequence in keel_checkpoints after each successful handler call — so deployments resume where they left off without reprocessing old events or missing events published during rollout (inspect or clear cursors via app.keel.checkpoints.get(id) / reset(id)):

daemons: [
  // Scheduled cron owned by this service
  k.daemon(CleanupCron, async (scheduledAt) => {
    await pruneExpiredRows(scheduledAt)
  }),

  // Live watch on an owned table (Insert / Update / Delete)
  k.daemon(DeliveriesTable, async (ev) => {
    console.log("Delivery changed:", ev._tag, ev.key)
  }),

  // Durable CDC on an owned table with trackChanges: true + built-in checkpoint
  k.daemon(
    OrdersTable,
    async (ev) => {
      console.log(ev.sequence, ev.payload._tag)
    },
    { mode: "cdc", checkpoint: "orders-cdc-projection" }
  ),

  // Durable catch-up-and-tail topic listener (checkpoint implies mode: "durable")
  k.daemon(
    OrderPlaced,
    async (ev) => {
      await rebuildProjection(ev.sequence, ev.payload)
    },
    { checkpoint: "orders-projection" }
  ),

  // Custom AbortSignal-managed background loop
  k.daemon(async (signal) => {
    while (!signal.aborted) {
      await pollExternalHealth(signal)
    }
  }),
]

Tip: You can also schedule delayed jobs inside a service with await ctx.emails.enqueueDelayed(payload, "15 minutes") and inspect exhausted jobs with await ctx.emails.deadLetters(). See JobQueue for all worker options.

5. Start the Modulith (In-Process, Stubbed, or Remote)

Call App.start(...) once at the composition root. It wires every service in topological serviceOrder, starts all service subscriptions and daemons (including queue workers), and runs the transactional outbox relay automatically (waking immediately on commit via OutboxNotifier):

await using app = await App.start({
  backend: "sqlite", // "memory" | "sqlite" | "postgres" | "surreal"
  sqlite: { filename: ":memory:" },
  ensureAll: true,
  services: {
    inventory: inventoryImpl,
    orders: ordersImpl,
    billing: billingImpl,
    notifications: notificationsImpl,
  },
})

// 1. Reserves stock, commits order + OrderPlaced outbox event atomically
// 2. Outbox relay fans out OrderPlaced to BillingService and NotificationsService
// 3. NotificationsService enqueues an EmailQueue job processed by its daemon worker
const { orderId } = await app.orders.place({
  userEmail: "[email protected]",
  sku: "KEEL-1",
  qty: 1,
  amountCents: 2500,
})

Each entry in services accepts one of three shapes — with zero .live(), .mock(), or .client() calls:

Slot value Behavior Replaces
k.implement(Svc, ...) Runs the real implementation in-process with scoped ctx, class-typed subscriptions, and daemons .live()
Plain { opName: async (input) => ... } Runs a contract-validated test stub (checks input/output schemas & closed errors) .mock()
{ url | binding | transport, timeout?, retries?, workload? } Connects to an extracted remote service over HTTP RPC or Cloudflare Service Binding .client()
// Slice-testing OrdersService with a stubbed InventoryService and remote BillingService:
await using testApp = await App.start({
  backend: "memory",
  ensureAll: true,
  services: {
    inventory: {
      reserve: async () => ({ reservationId: "res_stub" }),
    },
    orders: ordersImpl,
    billing: {
      url: "http://billing:8085",
      timeout: "3 seconds",
      retries: 2,
    },
  },
})

Configuration options

Option Type Default Description
services readonly Service[] Required Bounded-context services that compose the modulith.
unitName string "app" Name of the single deployable unit in the underlying Topology.
isolation.database "shared" | "schema" | "database" | "instance" "shared" Database isolation strategy.
isolation.buckets "shared" | "unit-scoped" "shared" Object storage isolation strategy.
isolation.workloadAuth "off" | "auto" | "required" "off" Workload signing between units (automatically flips to "auto" on extract()).
allowCrossServiceForeignKeys boolean false When false, throws TopologyBoundaryError if a service’s table declares a foreign key referencing another service’s table.
shared { topics?, tenant?, resources? } — Explicitly shared resources exempt from single-owner boundary checks.
entrypoint string — Entrypoint path for Alchemy Docker / Cloudflare deployment.
port number — HTTP port for Docker deployment.
public { domain?, pathPrefix? } — Public edge routing metadata for Caddy / Cloudflare.
migrationsDir string — Migrations directory for the modulith unit.

Extracting a service into a microservice (App.extract)

When one service (or a queue-heavy worker service like notifications) needs independent scaling, isolation, or deployment, call App.extract(...). It returns a standard multi-unit Topology with the extracted service(s) in their own unit(s), the remaining services still grouped in the monolith unit, and workloadAuth automatically enabled:

import { keelDockerStack } from "@chimp-labs/keel-alchemy/docker"
import { App } from "./src/app.js"

// Split `inventory` and `notifications` into their own containers; keep `orders` + `billing` in `app`
const SplitTopology = App.extract(
  {
    inventory: {
      entrypoint: "./src/inventory-server.ts",
      port: 8085,
    },
    notifications: {
      entrypoint: "./src/notifications-worker.ts",
      port: 8086,
    },
  },
  {
    isolation: { database: "schema" },
  }
)

export default keelDockerStack(SplitTopology, {
  database: "postgres",
})

SplitTopology works seamlessly with planKeelDockerTopology, keelDockerStack, planKeelCloudflareTopology, keelCloudflareStack, and keel db.


Native Effect v4 usage

In Effect v4 (@chimp-labs/keel or @chimp-labs/keel/modulith), declare publishes, subscribes, and owned JobQueue resources on Service<Self>()(...), pass class-typed subscriptions: (on) => [...] and daemons: [startWorker(...)] into Service.live(...), and compose the modulith with App.buildLocalLayer(...):

import { Effect, Ref, Schema } from "effect"
import {
  JobQueue,
  KeelMemoryLive,
  Modulith,
  Service,
  Topic,
  enqueue,
  publish,
  startWorker,
} from "@chimp-labs/keel"

export class OrderPlaced extends Topic(
  "orders.placed",
  Schema.Struct({ orderId: Schema.String, userEmail: Schema.String })
) {}

export class EmailQueue extends JobQueue(
  "notifications.emails",
  Schema.Struct({ to: Schema.String, orderId: Schema.String }),
  { maxAttempts: 3, dlq: true }
) {}

export class OrdersService extends Service<OrdersService>()("orders", {
  publishes: [OrderPlaced] as const,
  operations: {
    place: {
      input: Schema.Struct({ orderId: Schema.String, userEmail: Schema.String }),
      output: Schema.Struct({ ok: Schema.Boolean }),
    },
  },
}) {}

export class NotificationsService extends Service<NotificationsService>()("notifications", {
  resources: [EmailQueue],
  subscribes: [OrderPlaced] as const,
  operations: {
    sent: {
      input: Schema.Struct({}),
      output: Schema.Array(Schema.String),
    },
  },
}) {}

const delivered = Ref.makeUnsafe<ReadonlyArray<string>>([])

const OrdersLive = OrdersService.live({
  place: ({ orderId, userEmail }) =>
    publish(OrderPlaced, { orderId, userEmail }).pipe(
      Effect.as({ ok: true }),
      Effect.orDie
    ),
})

const NotificationsLive = NotificationsService.live(
  {
    sent: () => Ref.get(delivered),
  },
  {
    // Event consumer enqueues onto the service-owned JobQueue
    subscriptions: (on) => [
      on(OrderPlaced, (ev) =>
        enqueue(EmailQueue, {
          to: ev.payload.userEmail,
          orderId: ev.payload.orderId,
        })
      ),
    ],
    // Scoped push-driven queue worker fiber tied to the service Layer scope
    daemons: [
      startWorker(
        EmailQueue,
        (job) => Ref.update(delivered, (list) => [...list, job.payload.orderId]),
        { mode: "push", concurrency: 4 }
      ),
    ],
  }
)

export const App = Modulith("commerce", {
  services: [OrdersService, NotificationsService],
})

const localLayer = App.buildLocalLayer({
  baseLayer: KeelMemoryLive,
  serviceLayers: {
    orders: OrdersLive,
    notifications: NotificationsLive,
  },
})

Static boundary checks

Violation Error How to fix
Two services claim the same Table, Bucket, JobQueue, or Cron TopologyBoundaryError Keep mutable state inside one owning service, or explicitly list read-only shared resources in shared.resources.
A service’s Table has a foreignKey referencing another service’s Table TopologyBoundaryError Store the foreign ID as a plain scalar column and coordinate via RPC or domain events (or opt in with allowCrossServiceForeignKeys: true).
Two services publish the same Topic TopologyBoundaryError Assign a single owning publisher service, or list the shared event topic in shared.topics.
A service subscribes to a Topic nobody publishes TopologyBoundaryError Add the publishing service to services, declare the topic in its publishes / resources, or list it in shared.topics.
Circular Service.dependencies TopologyBoundaryError Break synchronous RPC cycles with asynchronous publishes / subscribes events.