Durable Coroutines for TypeScript: Fault-tolerant Agents with millisecond overhead
Pangram verdict · v3.3
We believe that this entire text is human-written.
AI likelihood · overall
HumanArticle text · 1,417 words · 10 segments analyzed
We added durable coroutines to Restate's TypeScript SDK: persistent, concurrent, multi-step routines that provide the same persistence and recovery semantics as workflows, but add only milliseconds of overhead per durable action, instead of the 50-100 milliseconds often experienced in workflow solutions1. In production deployments, a durable step in a coroutine adds a latency overhead of P50=2.5ms, P99=9ms at rates of >10,000 durable_actions/second for a synchronously replicated 3-AZ setup on GCP. We developed Durable Coroutines together with users building durable agents. Modern agent harnesses persist and track their progress in fine-grained steps: chunks of LLM results, multiple steps per tool call (intent, guardrail, result chunks). That granularity gives agents a stronger model when recovering from failures. But this is hard to achieve with a durable execution model that schedules and dispatches activities to workers for each persistent step. We built durable coroutines to fill that gap. An added perk of this approach is that the code can assume a durable process-like model, where durable steps can rely on local variables and make efficient use of cached resources. The coroutines implementation makes heavy use of TypeScript's generator functions to implement a deterministic scheduler controlling the execution. Background: Workflows vs. Durable Functions Durable execution originally came in the shape of workflows and activities: if you want a persistent step, you need to create an activity, which gets scheduled on some worker. In systems like Temporal, that means the workflow task cedes execution (returns to the workflow orchestrator), the activity is sent to a worker to execute and return a result, and the workflow task gets executed again2. Parallel work means setting up multiple activities, and when the workflow task cedes execution, all activities start running. This approach fits a task-queue & worker architecture. Workflow Serverholds the workflow history and task queuesagent()Worker 1idleWorker 2idleWorker 3idleworkflow suspended — nothing is runningbidi streamRestate Serverpushes the invocation · journals every stepjournal0 entriesService processlong-lived · one event loopidle — no invocationprocess idle — waiting for an invocation An alternative approach that Restate and other systems implemented is often described as Durable Functions. The functions can have durable steps (ctx.run(...), plus durable signals, sleeps, promises, ...) and compose via RPC (calling other durable functions). Durable steps are faster than activities (or calling other durable functions) because they need to do less work: Restate maintains a streaming connection to the executing functions, sending steps and acks between the application and Restate Server. Restate's entire architecture is designed to make step commits fast. Durable functions give developers the choice between two models: putting a unit of work (that should be persisted) into separate functions or activities is useful for heavier tasks, or when the work needs to be queued and dispatched to different workers/deployments and run with specific rate or concurrency limits. In contrast, programs written with durable steps & coroutines feel more like writing durable processes. Except in actual failure/recovery cases, the execution is one continuous run in the same process, letting the code reuse local resources like cached files/results or authenticated connections. Restate has always supported durable steps, but the addition of Durable Coroutines fixes the previously limited support for concurrency in that API. Both models complement each other: We often see developers put larger work (like conversation turns or long-running tools) into a separate durable function (whose invocation has queueing and flow control) and use steps/coroutines to capture the durability of substeps. Enter Durable Coroutines Restate's Durable Coroutines library takes the idea of coroutines from programming languages like Go, Rust, or Kotlin and implements a deterministic scheduler to make them compatible with journal-based durable execution. There are only a few important concepts: Everything is a generator function because that allows Restate to tightly control the execution (see How it works). If you've never worked with generator functions, you can squint your eyes and pretend that yield* fulfills a similar purpose here as await does for Promises.
run(...)
is a single durable step, like in Restate's standard API.
spawn(...)
creates a new concurrently executed coroutine (Task), which can have its own sequence of durable actions and can spawn further Tasks. select(), all(), and other combinators combine steps and tasks in the same way as promise/future combinators do. Let's dive into an example: an agent loop that spawns tools as concurrent sub-workflows and listens for steering signals. function* agent(userMessage: string): restate.Operation<string> { const sandbox = yield* connect(); // re-usable connection across tool calls const messages: Message[] = [{role: "user", content: userMessage}]; const tasks = new Map<string, restate.Task<ToolResult>>(); // tasks in-flight let steer = restate.signal<string>("steer"); // to wait for a note from the user // Durable agent loop while (true) { // 1.
Durable LLM call const action = yield* restate.run(async () => llm(messages)); if (action.type === "final") { return action.message; } messages.push({role: "assistant", calls: action.calls}); // 2. Spawn parallel tool calls (each of them possibly a multi-step sequence) for (const call of action.calls) { tasks.set(call.id, restate.spawn(performCall(call, sandbox))); } messages.push({ role: "tool", results: action.calls.map(({id}) => ({id, result: "task created"})), }); // 3.
Race tool calls with new steering input const next = yield* restate.select({...Object.fromEntries(tasks), steer}); if (next.tag === "steer") { // process steering note messages.push({role: "user", content: yield* steer}); steer = restate.signal<string>("steer"); // renew the signal } else { // process completed tool call const result = yield* tasks.get(next.tag)!; tasks.delete(next.tag); messages.push({role: "tool", results: [result]}); } } } To see how far you can go with Durable Coroutines, have a look at Restate's agent reference architecture, which uses them to compose steering, interruption, sync/async tools, programmatic tool calling, and more. Your browser does not support the video tag.A coding agent concurrently executes LLM calls, subagents, tools, approvals, and steering commands in a single durable concurrent process. Every step is durable, replay-stable, and recoverable. How it works The library uses TypeScript generators instead of Promises (async/await) to give the SDK control over coroutine execution. With async/await, the event loop decides how the execution of different concurrent code paths interleaves. Generators instead pause at each yield until the caller explicitly resumes them.
This lets the SDK decide which coroutine continues next and what result it receives.
By recording the order of completion in the journal, the SDK can replay execution deterministically. Take a tool with two durable steps: a guardrail and the actual tool execution. For each step, yield* pauses the coroutine until the result is there: function* runTool(tool, params) { const allowed = yield* run(() => guardrail(tool, params)); // true/false if (!allowed) { return "Tool call rejected by guardrail"; } return yield* run(() => callTool(tool, params)); } // SDK drives execution via: const task = runTool(tool, params); // runs nothing yet task.next(); // starts guardrail step and pauses task.next(true); // guardrail passed: starts tool call step and pauses task.next(toolResult); // returns run() doesn't return its result directly. Like all actions (a call to another service, a timer, or a signal), it returns a Future. yield* hands that Future to the SDK (the scheduler) and pauses the coroutine. The scheduler waits for the Future to complete, then calls next() with the result, which becomes the value of the yield* expression. Concurrency The code may start additional concurrent coroutines (Tasks) via spawn(...). The scheduler advances all coroutines (repeatedly calls next(...) across yield points) until each coroutine has yielded a future to a Restate action (e.g., a run(...) step, a signal, RPC, ...), meaning everyone is currently waiting. This is the critical point where we need to ensure that we record the order in which these actions complete, so we can deterministically replay them on recovery. The scheduler does that by running RestatePromise.race(pendingActions), which automatically records the winning completion in the durable execution journal. It then resumes the waiting coroutine and starts advancing coroutines again. Exactly one coroutine executes at a time, but the I/O in their durable steps overlaps. To illustrate this, here is the execution of an agent running two concurrent tools, each consisting of a guardrail step and a tool call step. Note how the SDK runs race(...) each time all coroutines are waiting on a durable step (run(...)). Service processRestate SDKinvokeagent(ticket)function* agent(ticket) { const plan = yield* run(() => llm(ticket)); const crm = spawn(crmTool(plan.user)); const billing = spawn(billingTool(plan.user)); const [a, b] = yield* all([crm, billing]); return summarize(a, b);}The SDK controls which fiber can make progress by calling next(). The order of completion is recorded in the journal, for deterministic recovery. Inside the scheduler The scheduler wraps every coroutine in a fiber: the generator plus a state that is ready, waiting, or done.
Ready fibers sit in a FIFO queue.