Keel by ChimpLabs
Jump to page or section Esc
Primitives

Workflow

Crash-resilient durable execution with step journaling, automatic replay, reverse LIFO saga compensation, durable sleep, and event waits via @chimp-labs/keel-workflow.

Workflow (@chimp-labs/keel-workflow) runs multi-step, long-running processes as plain async/await functions or Effect v4 programs with durable step journaling, crash replay, and reverse LIFO saga compensation. Common uses include order fulfillment, onboarding, payment sagas, and multi-agent pipelines.

@chimp-labs/keel-workflow plugs directly into createKeel({ resources }) through Keel’s Open Plugin Protocol — pass workflow(...) and signal(...) descriptors alongside your core Keel tables, queues, and topics with zero extra glue.

When a process crashes and restarts with the same runId, Keel replays completed ctx.step(...) results from the journal without re-running side effects. If a later step fails permanently, Keel runs each earlier step’s compensate hook in reverse order.

pnpm add @chimp-labs/keel @chimp-labs/keel-workflow effect

Declaring a workflow

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

import { createKeel, k } from "@chimp-labs/keel/sdk"
import { workflow, signal } from "@chimp-labs/keel-workflow"

export const FulfillmentWorkflow = workflow("order.fulfillment", {
  input: k.object({
    orderId: k.string(),
    sku: k.string(),
    qty: k.int(),
    totalCents: k.int(),
  }),
  output: k.object({
    reservationId: k.string(),
    trackingCode: k.string(),
  }),
})

export const ApprovalSignal = signal(
  "order.approved",
  k.object({ approvedBy: k.string() })
)

// Plugs straight into createKeel({ resources }) via the Open Plugin Protocol!
const keel = await createKeel({
  backend: "memory", // or "sqlite" | "postgres" | "surreal"
  resources: {
    fulfillment: FulfillmentWorkflow,
    approval: ApprovalSignal,
  },
})

Configuration options

Option Type Description
input SchemaLike Schema validating workflow input on start.
output SchemaLike Schema validating the final workflow return value.

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

import { Effect, Schema } from "effect"
import {
  Workflow,
  WorkflowStoreMemory,
  defineWorkflow,
  runWorkflow,
} from "@chimp-labs/keel-workflow"

export class FulfillmentWorkflow extends Workflow("order.fulfillment", {
  input: Schema.Struct({
    orderId: Schema.String,
    sku: Schema.String,
    qty: Schema.Int,
    totalCents: Schema.Int,
  }),
  output: Schema.Struct({
    reservationId: Schema.String,
    trackingCode: Schema.String,
  }),
}) {}

const def = defineWorkflow(FulfillmentWorkflow, (input, ctx) =>
  Effect.gen(function* () {
    const res = yield* ctx.step(
      "reserve-inventory",
      Effect.succeed({ id: `res_${input.orderId}` }),
      {
        retries: 3,
        compensate: (_reserved) => Effect.log("releasing inventory"),
      }
    )
    return { reservationId: res.id, trackingCode: `TRK-${res.id}` }
  })
)

const result = await Effect.runPromise(
  runWorkflow(def, {
    runId: "order-1",
    input: { orderId: "1", sku: "KEEL-M", qty: 2, totalCents: 4500 },
  }).pipe(Effect.provide(WorkflowStoreMemory))
)

Attaching to a service

export const OrdersService = k.service("orders", {
  resources: [OrdersTable, FulfillmentWorkflow, ApprovalSignal],
  dependencies: [InventoryService],
  operations: { /* ... */ },
})

Operations reference

Running a workflow with steps, retries, and saga compensation

const output = await keel.fulfillment.run(
  {
    runId: `order-${order.id}`,
    input: { orderId: order.id, sku: "KEEL-M", qty: 2, totalCents: 4500 },
  },
  async (inp, ctx) => {
    // 1. Journaled step with retries and reverse saga compensation
    const stock = await ctx.step(
      "reserve-inventory",
      () => inventoryApi.reserve({ sku: inp.sku, qty: inp.qty }),
      {
        retries: 3,
        compensate: (reserved) => inventoryApi.release({ id: reserved.id }),
      }
    )

    // 2. Durable sleep (persisted across restarts)
    await ctx.sleep("cooling-period", "5 seconds")

    // 3. Wait for an external signal or domain topic event
    const approval = await ctx.waitForSignal("manager-approval", ApprovalSignal, {
      timeout: "24 hours",
    })

    // 4. Charge payment — if this throws, "reserve-inventory" compensation runs automatically!
    const charge = await ctx.step(
      "charge-card",
      () => stripe.charge({ amountCents: inp.totalCents, approvedBy: approval.approvedBy }),
      {
        compensate: (c) => stripe.refund({ chargeId: c.id }),
      }
    )

    return {
      reservationId: stock.id,
      trackingCode: `TRK-${charge.id}`,
    }
  }
)

Waiting for topic events and inspecting runs

// Wait inside a workflow for a matching event on any Topic
const paid = await ctx.waitForEvent("wait-payment", PaymentCapturedTopic, {
  match: (ev) => ev.orderId === inp.orderId,
  timeout: "10 minutes",
})

// Inspect workflow journal status and outputs
const record = await keel.fulfillment.getRun(`order-${order.id}`)
// record.status: "running" | "completed" | "failed" | "compensating" | "compensated"

SDK and Effect API mapping

SDK method (keel.<wf>.* / ctx.*) Effect function (@chimp-labs/keel-workflow) Description
define(handler) defineWorkflow(wf, handler) Create a reusable typed workflow definition.
run({ runId?, input }, handler) runWorkflow(def, { runId?, input }) Start or resume a durable workflow run.
getRun(runId) getWorkflowRun(runId) Read a durable run record, status, and output.
ctx.step(name, fn, { retries?, compensate? }) ctx.step(name, effect, opts?) Execute once, persist the output to the journal, and register a LIFO rollback hook.
ctx.sleep(name, duration) ctx.sleep(name, duration) Start a durable timer that survives restarts.
ctx.waitForSignal(name, signal, { timeout? }) ctx.waitForSignal(name, signal, opts?) Suspend until a typed Signal arrives.
ctx.waitForEvent(name, topic, { match?, timeout? }) ctx.waitForEvent(name, topic, opts?) Suspend until a matching Topic event arrives.

Errors and failure modes

Error tag Category HTTP status Retryable When it occurs
WorkflowNotFoundError not_found 404 No getRun references an unknown runId.
WorkflowTimeoutError timeout 504 Yes waitForSignal or waitForEvent exceeded its timeout.
WorkflowStoreError internal 500 Yes Workflow journal persistence failed.
SchemaError invalid 400 No Workflow input, output, or a step payload failed schema validation.

Backends and infrastructure

  • Memory (WorkflowStoreMemory): Automatically provided when createKeel({ backend: "memory" }) includes a workflow(...) or signal(...) resource. Runs step journaling, crash-replay simulation, LIFO compensation, and in-process signal wake-ups.
  • SQLite / portable SQL (WorkflowStoreFromTable): Automatically provided on sqlite, postgres, or surreal via Table primitives (keel_workflow_runs, keel_workflow_steps, keel_workflow_signals).
  • Multi-replica PostgreSQL 17 (@chimp-labs/keel-workflow/postgres): Provide WorkflowStorePostgresLive alongside KeelPostgresLive for ACID step persistence plus live multi-replica LISTEN/NOTIFY signal wake-ups without polling.
  • Multi-replica SurrealDB 4 (@chimp-labs/keel-workflow/surreal): Provide WorkflowStoreSurrealLive alongside KeelSurrealLive for durable step journals plus live LIVE SELECT signal wake-ups without polling.
import { Layer } from "effect"
import { KeelPostgresLive } from "@chimp-labs/keel-postgres"
import { WorkflowStorePostgresLive } from "@chimp-labs/keel-workflow/postgres"

const PgLayer = KeelPostgresLive({ url: process.env.DATABASE_URL! })
export const AppWorkflowLayer = WorkflowStorePostgresLive.pipe(Layer.provideMerge(PgLayer))

Testing in memory

import { createKeel, k } from "@chimp-labs/keel/sdk"
import { workflow } from "@chimp-labs/keel-workflow"

const FulfillmentWorkflow = workflow("order.fulfillment", {
  input: k.object({ orderId: k.string(), sku: k.string(), qty: k.int(), totalCents: k.int() }),
  output: k.object({ reservationId: k.string(), trackingCode: k.string() }),
})

await using keel = await createKeel({
  backend: "memory",
  resources: { fulfillment: FulfillmentWorkflow },
})

const compensated: string[] = []

await expect(
  keel.fulfillment.run(
    { runId: "ord-fail", input: { orderId: "1", sku: "A", qty: 1, totalCents: 1000 } },
    async (_inp, ctx) => {
      await ctx.step("reserve", () => ({ id: "res-1" }), {
        compensate: (r) => {
          compensated.push(r.id)
        },
      })
      await ctx.step("charge", () => {
        throw new Error("card declined")
      })
      return { reservationId: "res-1", trackingCode: "n/a" }
    }
  )
).rejects.toThrow("card declined")

// compensated === ["res-1"] (automatic reverse rollback!)