What happens when your workflow process crashes mid-sleep? How durable execution recovers
Your order service accepts a checkout, pauses for a confirmation window, and plans to charge the card next. Halfway through that sleep, a rolling deploy or OOM kill terminates the container and wipes the in-memory timer. Without durable execution, waiting inside ordinary code turns routine restarts into silently lost work.
Why cron, queues, and hand-rolled retries break
An in-process sleep is quick to write and quick to break. Every setTimeout or async delay lives only in RAM and disappears when the process exits. Long waits also pin memory and open connections when your service should sit idle.
Most teams reach for a database table and a cron job next. You add a status column, a wake_at timestamp, and a poller that scans due rows on an interval. Soon you add row locks so two pollers cannot claim the same order. You end up maintaining migrations, retry counters, dead-letter states, and a database cluster just to wait safely.
Delayed message queues move the complexity instead of removing it. One business flow fragments across queue topics, dead-letter queues, and disconnected consumer handlers. Local variables disappear between hops, forcing you to serialize state onto messages or save it in a database. Visibility timeouts and delay caps also break down once waits stretch into hours or days.
Hand-rolled retry loops fail right after the wake-up. Suppose a worker charges the card and crashes before recording the updated order status. A basic retry runs the handler from line one and repeats earlier steps. Preventing duplicate work forces you to write manual checkpoint logic around every side effect.
None of these tools is wrong by itself. The friction comes from assembling a workflow engine out of stateless pieces and ad-hoc glue. You want sequential code where every wait and completed step survives a process crash.
How durable execution and the journal survive a crash
Durable execution separates where code runs from where its progress lives. A runtime records every step in an append-only journal instead of keeping state in process memory. When a process crashes, another process replays that journal to rebuild local state.
A durable sleep shows how the journal handles crashes. When your handler calls ctx.sleep(1_000), the protocol records SleepCommandMessage (0x040C) with an absolute wake_up_time in UNIX epoch milliseconds. Because the journal stores an absolute instant rather than a relative duration, replaying after a crash never resets the deadline. If that deadline sits in the future, the SDK sends SuspensionMessage naming the pending wait and ends the turn.
Ending the turn releases your application process right away. The timer lives in the store, holding neither process memory nor an open HTTP connection. Because ctx.sleep ends the turn, it never triggers Cairnflow's 60-second inactivity timeout (--inactivity-timeout-ms); only silent ctx.run closures count.
Once wake_up_time arrives, the runtime records SleepCompletionNotificationMessage (0x800C) and invokes your handler again. The SDK executes the function from the top and matches each command against the journal. Completed state reads and the finished sleep return their recorded values immediately. Control resumes on the line right after await ctx.sleep(...).
Replay relies on deterministic logic between journaled steps. Cairnflow's protocol routes every non-deterministic input through an explicit primitive. Randomness draws from StartMessage.random_seed, sleep journals an absolute timestamp, and time or external I/O goes through ctx.run. Replay checks both command kind and ctx.run name; renaming an in-flight step pauses the invocation with code 570.
Working code: a workflow that survives kill -9 mid-sleep
This TypeScript virtual object uses @cairnflow/sdk v0.1.0-beta.0 (Apache-2.0, zero runtime dependencies). Node.js 22.18+ runs .ts files directly without flags; Node 22.6–22.17 requires --experimental-strip-types. Running it locally requires neither Rust nor a separate database.
// order-service.ts (@cairnflow/sdk v0.1.0-beta.0) import { type Context, serve, service } from "@cairnflow/sdk"; const orders = service("OrderService", { async submit(ctx: Context, input: { amount: number }) { const soFar = (await ctx.get<number>("total")) ?? 0; await ctx.sleep(1_000, "await confirmation"); // durable: wakes up in the right place after a crash const receipt = await ctx.run("charge", () => chargeCard(input.amount)); // result is journaled once durable; pass an idempotency key to real APIs await ctx.set("total", soFar + input.amount); return { receipt, total: soFar + input.amount }; }, }, { type: "VIRTUAL_OBJECT" }); // state needs an object — call with a key async function chargeCard(amount: number): Promise<string> { // placeholder for a real payment call return `receipt-${amount}`; } serve({ services: [orders], port: 9080 }); Declaring VIRTUAL_OBJECT gives each key (such as order-42) isolated durable state. submit reads total, sleeps for one second, runs chargeCard inside ctx.run("charge", ...), and persists the updated total. The sleep ends the turn as soon as the runtime commits the timer. After a mid-sleep crash, a restarted node replays GetState and Sleep, then runs chargeCard.
Start a local v0.1.0-beta.0 node, create order-app, and save order-service.ts inside that directory before starting it. Then register the service and send an invocation for order-42.
# Terminal 1: run a local node (dev state lives under ./cairnflow-data) cairnflow --no-auth # Terminal 2: initialize order-app, save order-service.ts here, and start on :9080 mkdir order-app && cd order-app npm init -y && npm pkg set type=module && npm install @cairnflow/sdk # save order-service.ts in order-app/ before running: node order-service.ts # Terminal 3: register and call OrderService cairn register http://127.0.0.1:9080 cairn invoke OrderService submit --key order-42 --input '{"amount": 100}' # completed 4c6a89854f58… # {"receipt":"receipt-100","total":100} While an invocation waits in ctx.sleep, cairn invocations --status suspended lists it as parked. Running cairn journal <id> mid-sleep prints four recorded entries: 0 Input, 1 GetState, 2 GetStateCompletion, and 3 Sleep. After wake-up completes the run, the journal appends 4 SleepCompletion, 5 Run, 6 RunCompletion, 7 SetState, and 8 Output. Each entry reaches durable storage before the turn progresses.
Failures follow three explicit paths. Throwing an ordinary Error aborts the turn without journaling so Cairnflow retries with backoff. TerminalError fails the invocation permanently (and lets you catch it for compensation), while PauseError halts until cairn resume <id>. For human approvals with deadlines, combine a signal and a sleep via ctx.race([ctx.signal("approve"), ctx.sleep(24 * 3600_000)]).
Under the hood: how Cairnflow survives kill -9 without a database
Most workflow engines depend on a separate database or replicated local disks for timers and journals. Cairnflow stores all state in an S3-compatible bucket — locally under ./cairnflow-data, or with --main-store s3://my-bucket/prefix in production. Read the full design in docs/architecture.md and docs/protocol-v1.md; below is the five-step crash path.
1. Timers live as rows in the range database
Cairnflow splits the u64 partition-key space into contiguous ranges, each with one leader, one SlateDB database, and one single-threaded engine. Inside each range database, zone 0x00 holds hot rows: invocation status, timers, outbox rows, retries, and locks. Zone 0x02 stores bulk journal and state data, while zone 0x01 holds derived indexes rebuilt from owned rows. No pending timer lives only in leader memory.
2. Shared WAL commits finish before any acknowledgement
When a turn proposes a sleep, the engine sends Mutations through PartitionWriter::commit into SlateDB's memtable. Each node multiplexes WAL frames across its ranges into shared streams (nodewal/<node>/<inc>/<stripe>/<seq>, default two --wal-stripes) batched via --wal-window-ms. After the bucket accepts conditional PUT Create, WalFlushed advances durable_seq and issues a Committed ticket. Cairnflow never acknowledges /send or advances a turn until that PUT succeeds in stream order.
3. pkill -9 cairnflow terminates the runtime mid-sleep
Killing cairnflow with SIGKILL drops the process, its memtable, and its in-memory timer queues. Because nodes hold no durable local state, every acknowledged journal entry and timer row stays intact in the store.
4. Leadership transfers via CAS without Raft or etcd
Restarting cairnflow — or letting another node claim the range — transfers leadership through object-store compare-and-swap (CAS), without Raft or etcd. Nodes renew liveness on sessions/<node>/<inc>, claim ranges on owners/range-<id>, and fence stale writers via SlateDB's writer_epoch and conditional PUT. At startup, Cairnflow refuses any object store lacking real conditional PUT (PutMode::Create and PutMode::Update on etag).
Before serving, the new leader seals the previous owner's shared WAL at the first gap above the GC floor. It replays those WAL objects into the range DB, flushes to L0, and rebuilds every in-memory timer and queue from storage. You run no manual recovery step because the bucket holds the entire state.
5. Wake-up triggers replay and completes the handler
Once wake_up_time passes, the engine records SleepCompletionNotificationMessage (0x800C) and opens a new HTTP turn to your service. Cairnflow drives handlers over BIDI_STREAM (HTTP/2) or REQUEST_RESPONSE (HTTP/1.1 and serverless adapters via @cairnflow/sdk/fetch). The SDK replays GetState and Sleep, runs ctx.run("charge", ...), commits total, and finishes the invocation.
Trade-offs and when not to use Cairnflow
Putting all state on object storage trades commit latency for operational simplicity. Every acknowledged step waits for an object-store PUT, which takes tens of milliseconds on S3 Standard (lower on low-latency object stores). If your workload needs single-digit-millisecond commits on every step, Cairnflow is the wrong fit.
Cairnflow guarantees that acknowledged steps survive crashes, kill -9, partitions, and leadership changes without reapplying them. It does not guarantee single execution of external side effects. If a node dies after ctx.run calls an external API and before that result commits, the runtime runs the closure again. Pass an idempotency key on every external call so retries stay safe.
Availability also tracks your object store. During a store outage, ranges pause and step down instead of serving stale or unacknowledged data, and durability matches the bucket's own durability.
Cairnflow is in beta (v0.1.0-beta.0) with a shorter track record than mature workflow engines. The on-bucket format is frozen (DATA_FORMAT 10) and upgrades migrate data in place, while APIs may change between minor versions. Three SDKs exist today — TypeScript, Python, and Go — so pick another tool if you need a different language. Before exposing a cluster to untrusted tenants, review docs/self-hosting-security.md.
Cairnflow ships a source-available engine and console (not open source as a whole) with permissively licensed SDKs. The engine and console use BUSL-1.1 with an Additional Use Grant, allowing commercial self-hosting and converting to Apache-2.0 four years after each release. The SDKs and conformance suite use Apache-2.0, and protocol.proto uses MIT. Its programming model is close to Restate's and protocol.proto derives from Restate's MIT protocol, but the two are not interoperable.
Try the Kill and Resume demo
The v0.1.0-beta.0 release publishes binaries for Linux x86_64, Linux arm64, and macOS arm64, plus a Docker image. Install the Linux x86_64 binaries below, keep order-service.ts running and registered, then kill cairnflow mid-sleep.
# Install v0.1.0-beta.0 binaries (Linux x86_64) A=cairnflow-v0.1.0-beta.0-x86_64-unknown-linux-musl mkdir -p ~/.local/bin curl -L "https://github.com/cairnflowdev/cairnflow/releases/download/v0.1.0-beta.0/$A.tar.gz" \ | tar -xz -C ~/.local/bin --strip-components=1 "$A/cairnflow" "$A/cairn" "$A/cairn-ctl" "$A/cairn-query-worker" # Trigger /send and kill cairnflow during the 1-second sleep curl -s -X POST 'http://127.0.0.1:8080/invoke/OrderService/submit/send?key=order-43' \ -H 'content-type: application/json' -d '{"amount": 7}' && pkill -9 cairnflow # Restart from the same directory cairnflow --no-auth # Wait for the sleep to elapse, then inspect the status sleep 2 && cairn status <id> /send replies with {"status":"waiting","id":"6363870492b8…"} once durable, and after restart cairn status <id> returns completed with {"receipt":"receipt-7","total":7}. Run the full two-minute Kill and Resume demo — including the Docker setup — in the Cairnflow README quickstart.
