Time and waits
A schedule in four lines, a wait in one, a poll, a batch, a cap, the one duration grammar, and why a run body never reads the clock.
This page is every way a run touches time: schedules, timers, fact waits, approvals, polls, batches and caps. The commands it teaches are durable-sdk doctor --host and durable-sdk explain <id>; the test side is on Testing.
The rule underneath#
A run body may branch only on what it will see again on the next attempt. So the body reads the clock, randomness and the world inside a step and never between steps: new Date(), Date.now(), Math.random(), randomUUID() and process.env sit in a ctx.step, a poll, a batch or a wait, never in the body's own lines. The moment a run is about is the input's (requestId, slot.at) or a step's answer. The doctor's rule step-bodies/clock-outside-step holds it.
No wait holds a function. A parked run is one WorkflowWait row and no invocation; the dispatcher wakes it as the next attempt at its moment, and the minute sweeper is the fallback for a wake that was lost (Concepts). On the hosted platform timers fire at minute precision. A sleep has no cap of the engine's; a workflow's own timeout, when declared, bounds the run across its waits, so a run that sleeps a week under timeout: "1h" fails at the hour. A preview deployment has no cron (tick: request-only): a timer there resumes at the app's next request.
A schedule in four lines#
import { defineWorkflow } from "@durable-sdk/core";
export const digest = defineWorkflow<{ bucket: string }, void>({
name: "digest.send",
describe: "Sends the hourly digest once per slot.",
key: ["bucket"],
schedule: { every: "1h", input: (slot) => ({ bucket: slot.id }) },
example: { bucket: "497000" },
run: async (ctx) => {
void ctx.input.bucket;
},
});every is "<n>m" | "<n>h" | "<n>d" (at least a minute), or cron: "17 4 * * *" (five fields, UTC). The engine computes the slot once per tick (slot.id the period's index for every, the occurrence's ISO instant for cron; slot.at and slot.until its bounds) and runs the workflow with input(slot) under system:schedule:<name>. The key reads the input alone: put slot.id or slot.at.slice(0, 10) in the field the key names. A schedule whose input keeps the slot out of every key field is refused at boot, since two slots would key one run. catchUp: 1 fires one missed slot after an outage. The console lists every schedule with its last slot and next fire.
A wait in one line#
run: async (ctx) => {
await ctx.step("reserve", () => reserve(ctx.input.id), { irreversible: "a hold the provider expires" });
await ctx.sleep("2h", { id: "nap" });
const matched = await ctx.waitFor("shipment.matched", {
id: "matched",
match: { id: ctx.input.id },
deadline: ctx.input.deadline,
});
const decision = await ctx.waitForApproval<{ ok: boolean }>({ id: "approve", token: "approve", deadline: ctx.input.deadline });
const child = await ctx.child(review, { id: ctx.input.id }, { id: "review" });
},ctx.sleep("2h")is a timer: the run parks, wakes at the moment, answers{ fired: "timer" }.ctx.waitFor(name, { match, deadline | forever: true })parks until a local fact of that name matches the fields; it looks back first, so a fact quicker than the body never strands the run. A deadline that passes throwsWaitTimedOut(catch it by name). A wait names a deadline or saysforever: true; neither is a type error, and both is. The deadline comes from the input, a prior output or the bound clock, never a key.ctx.waitForApproval({ token })parks until a person signals it from the console,POST /admin/api/runs/:id/signalor the MCP; the answer is{ fired: "signal", payload }.ctx.child(definition, input)runs a child and parks the parent until it lands:{ runId, status, output }.
Give every wait an id: a step that may move is found by its id on a later deploy (Changing a workflow).
A long step parks itself#
A step runs inside one function invocation, and the platform says when it will end it. i.budget.deadlineAt and i.budget.leftMs() read what is left; i.stop fires at the deadline. Pass i.stop to every call and i.yield() on every turn of a loop, and rethrow the abort: the step then parks the run with its intents recorded and runs again in a fresh invocation within seconds. Say needs: "30s" on a step that needs that long and it never starts in a window that cannot finish it. A catch that returns a value under i.stop lands a partial row as complete, so the doctor refuses that shape.
A poll in four lines#
run: async (ctx) => {
const found = await ctx.poll("shipment", (i) => lookUp(i.jobId, i.stop), {
every: "10m",
until: "24h",
done: (out) => out !== null,
input: { jobId: ctx.input.jobId },
irreversible: "a look at the outside",
});
if (pollTimedOut(found)) throw new Error("no shipment within a day");
return found.id;
},Each probe is a step row (shipment#1, shipment#2), a miss writes nothing, the run sleeps between probes, and the window ends as a value: the probe's output once done, else { timedOut: true, last }. The deadline is until from the first probe's row, never the clock.
A batch in six lines#
run: async (ctx) => {
const swept = await ctx.batch(
"orphans.sweep",
{ next: (cursor, size) => readPage(cursor, size) },
{ size: 100, needs: "120s", ledger: "chunk" },
async (rows, index, i) => deleteOrphans(rows, i),
{ irreversible: "a deleted mirror is not restored", effect: "external" },
);
return { chunks: swept.chunks, items: swept.items };
},The chunk is the unit: one step row per chunk, the resume point after a crash, the compensation's unit. Items read through a cursor so nothing sits in memory; the batch parks when the function's deadline nears and goes on in the next invocation, so a batch of any size runs to the end. A chunk's output must fit its row: counts, a cursor, a bounded delta, never the items. concurrency (at most 8) runs chunks as a wave; ledger: "chunk" lands a chunk's recorded writes in one transaction at its flush.
A cap in one line#
concurrency: { max: 8, key: (i) => i.tenant },At most eight runs of the definition at once per key; a start over the cap parks as a slot wait and is admitted in start order. Never a drop, never a retry loop. A provider's own rate limit is the client's bucket inside the step: the call waits for a refill within the attempt, and the run parks on a rate wait past it.
Durations, one grammar#
Every duration a door takes is "<n>ms", "<n>s", "<n>m", "<n>h" or "<n>d": a whole number and one unit, never a bare number. A step's timeout, a retry's delays, a poll's every and until, ctx.sleep, a schedule's every, a batch listener's maxWait and the definition's timeout all read it. An option no door takes is refused by name (step.option.unknown, workflow.option.unknown), so a misspelled one is never silently ignored.
Check it#
durable-sdk doctor --host holds the clock out of run bodies and the id onto a wait in a loop; the harness's t.advance("3h") moves time in a test, a tick a minute, so a timer, a slot and a delayed fact fire when due and never early. The whole contract of schedules, waits, polls and batches is the generated page Workflows.