Scheduling and time

Timers, waits, signals, schedules, polls, batches, caps, rate buckets; time inside one invocation.

Open in CursorView as Markdown

Generated from the SDK's own source (packages/durable-core/README.md) at build; edit there.

Time inside a run is ADR-0050's: ctx.sleep and ctx.sleepUntil park the run as WAITING on a wait row and hold no function (the tick's resumer wakes it at its moment, as attempt + 1 replaying its rows), ctx.waitFor waits for a fact with a deadline, ctx.waitForApproval for a signal, ctx.poll probes with a window, a definition's schedule (every or cron) is fired by the core's schedules tick task (a period of at least a minute anywhere; at least 10 s where the bound platform says subMinute, under which the task emits the coming minute's slots as delayed facts at their moments, ADR-0076 FP-036), and emit(…, { deliverAt }) delays a fact. The older pattern below, a tick task over your own tables with a time-bucketed key, still works and is still right where the due set lives in your data (a warehouse's pickjob.rematch scan runs on the core's dueScan this way).

A run that a fact should cancel declares it (ADR-0076 FP-033; Inngest's cancelOn): defineWorkflow({ cancelOn: [{ event: "order.cancelled", match: (i) => ({ orderId: i.orderId }) }] }), at most five entries, each a fact of the catalog with a match over the payload's plain fields (an object, or a function of the input) and an optional since (a pure function of the input: the moment the entry's look-back starts from, the run's start when null). The engine arms one cancel wait row per entry with the run's own create (no step row, no park), looks back over the facts delivered since the window's floor, and on a matching fact at the dispatcher's claim runs run.cancel under the fact's request id, with the entry on the action's input, its ledger row and the fact run.cancelled, before it fires the row; the cancel is the operator's (the next step boundary ends the attempt, a call in flight is aborted through i.stop, the completed steps compensate). A run that landed first is untouched, its rows closed landed with the landing; a redrive arms the entries again, and the fact that cancelled the first attempt never cancels the redriven run. The reaction graph draws a cancels edge from the fact to the workflow.

A caller outside the run that wants its answer waits with the long-poll await (ADR-0076 FP-035, D07; SQS WaitTimeSeconds, Restate attach, Trigger.dev triggerAndWait): awaitRun(id, { timeout: "20s" }) in the package holds until the run lands (COMPLETED, FAILED, COMPENSATED or UNDONE) or the wait ends and answers the run row as it stands with how it waited (how: none for a run that had landed or is gone, listen or poll); the console API's GET runs/:id?wait=<duration> (at most 20 s a request, refused by name past it) holds the request the same way and answers the detail's shape; durable-sdk await <runId> --api <url> asks it again until the landing or --timeout; and execute(input, { awaitMs }) keeps its in-process poll of a run another call started. The store says how the wait is served (Stores.landings): the reference store's finish statement says the run's id with pg_notify inside its own RETURNING (no second statement; the resumer's abandoned mark the same), a waiter holds one dedicated session on LISTEN of that channel for the length of its wait (released in a finally; at most AWAIT_LISTENERS_MAX a process, never more than the pool's capacity less its spare, the rest polling), and the answer after a landing is the notification's flight (run.await.afterLanding.p95Ms in the bench); a belt re-read every AWAIT_BELT_MS covers a landing no notification said (an undo, an older build's finish during a deploy). Whether a session hears a landing is judged by one probe on the first await and remembered for the process, never by the URL's text: a transaction pooler (a managed database's pooled endpoint, PgBouncer) takes the LISTEN and delivers nothing, so the probe answers false there and the waiter polls the run every AWAIT_POLL_MS (500 ms); postgresStores(…, { listen: false }) answers false with no probe. Nothing of a wait writes a row, a fact or a ledger entry.

The pattern: a time-bucketed intent. A tick task (or your own cron route) selects what is due from your data and starts a workflow whose key names the due bucket. The bucket comes from the data, never from the clock, so the key stays pure and a second tick that sees the same due item starts no second run (a warehouse's rates.refresh ran this way before it declared a schedule).

A telehealth reminder, 24 hours before an appointment:

// workflows/reminder.send.ts
import { defineWorkflow } from "@/durable";
import { sendSms } from "../steps/sms";

export const sendReminder = defineWorkflow({
  name: "reminder.send",
  // the appointment's own start time, to the hour, is the bucket
  key: (i: { clinic: string; appointmentId: string; startsAt: string }) =>
    `reminder.send:${i.clinic}:${i.appointmentId}:${i.startsAt.slice(0, 13)}`,
  scope: (i) => i.clinic,
  async run(ctx) {
    await ctx.step(sendSms, {
      appointmentId: ctx.input.appointmentId,
      kind: "24h",
    });
    ctx.emit("reminder.sent", {
      clinic: ctx.input.clinic,
      appointmentId: ctx.input.appointmentId,
      kind: "24h",
    });
  },
});
// durable.config.ts (excerpt): runs after the dispatch lanes, inside the tick budget
tickTasks: [
  {
    name: "reminders.due",
    async run(ctx) {
      const due = await db.appointment.findMany({
        where: {
          startsAt: { gte: ctx.now(23 * 3600e3), lt: ctx.now(25 * 3600e3) },
          cancelled: false,
        },
        select: { id: true, clinicId: true, startsAt: true },
      });
      for (const a of due) {
        await sendReminder.execute(
          {
            clinic: a.clinicId,
            appointmentId: a.id,
            startsAt: a.startsAt.toISOString(),
          },
          { actor: "system:cron" },
        );
      }
    },
  },
];

The window is two hours wide and the tick runs every minute: an appointment is selected many times and reminded once, because the key is the same each time. An expiring hold, a batch settlement, a release of a reservation are the same shape: hold.expire:<holdId>, settlement.run:<till>:<date>. The task runs a workflow per due item, so a slow item does not block the others and each has its own limbo.

Delayed facts (ADR-0050 decision 1). emit(name, payload, { deliverAt }) and ctx.emit(…, { deliverAt }) write the row with its moment (OutboxEvent.deliverAt); the dispatcher, the stuck query, retention and the relay do not see it before then, and ctx.cancelScheduled(key) cancels it by key before its moment. That gives "send this fact in 15 minutes" without a sleeping function. A listener on it is the reaction.

Priority and fairness per partition (ADR-0076 D06, FP-025). A fact's priority is a seconds offset on its ordering moment alone: emit(name, payload, { priority }) and ctx.emit(…, { priority }) take an integer in −600…600 (PRIORITY_MAX_S), defineWorkflow({ priority }) is the default of a run's facts and on(…, { priority }) the listener's run's, each door refusing an offset off the grammar by name; the row's orderAt (occurredAt less the offset, the database's generated column) is what every read inside a partition orders and compares by, so a fact emitted ahead stands before the rows of its partition that occurred within its offset and behind the older ones, the key, the delivery and occurredAt unchanged and nothing moved across partitions. Fairness between partitions is the dispatcher's lane order (SQS fair queues' shape): a partition whose claims in a pass pass the window's quota (ceil(limit × FAIR_SHARE), 25 of the default 200) yields the next claim to the quietest partition the pass holds a row of, and a pass whose full window was one partition's looks past it once (the same window read with the partitions it holds excluded, head-checked, delivered first); never a drop, never a second read of a row, no statement added for the share (DispatchResult.yielded, the line event.window_yielded). Measured on the throughput bench: the quiet partitions' p95 emit-to-delivered beside a 1 000-row neighbour 1 514 ms → 36 ms.

Tenant fairness and quotas (ADR-0078 D06, SR-006). Where tenants share one database the share is a group's: createDurable({ fairness: { group } }) names the group a partition's claims are counted under, so the lane order's quota is judged per group (a tenant's partitions share one share of the window and yield to the quietest group's partition; the partition stays the ordering unit); the default group is the partition itself, and tenantGroup is the plane's rule (the tenant:<id> prefix of the partition, the partition whole otherwise). A bucket per tenant stands at the two doors, createDurable({ quotas: { tenant, emit, start } }): the tenant resolved from the fact's or the run's scope (tenantOf), one token taken from rate.tenant.<id>.emit at emit() and from rate.tenant.<id>.start at execute() before any row is written, one statement; a take over the bucket is a value, never an error ({ emitted: false, refused: "quota", retryAt }, { status: "refused", reason: "quota", retryAt }), nothing is taken on a door with no quota bound or for the engine's own starts (a listener's run, a child, a resume, a redrive, a continuation, an operator action), and each option is refused by name off its shape at the boot. Measured on the throughput bench's tenant-group case (32 hot partitions of one tenant beside 31 quiet partitions of another): the quiet tenant's p95 591 ms per partition → 75.5 ms per group.

The producer's idempotency key (ADR-0076 D06, FP-026). emit(name, payload, { idempotencyKey, ttl }), ctx.emit(…, { idempotencyKey, ttl }) and execute(input, { idempotencyKey, ttl }) take the request's own id (a webhook's delivery id, a client's request id) and hold it for ttl (24 h unless said, 30 days at most) in a keyed row of its own (DedupeKey), judged inside the same statement as the fact's insert or the run's begin: a repeat inside the window inserts nothing and answers the first's id as a value ({ emitted: false, deduplicated: true, id }, { status: "deduplicated", runId }), never an error; the catalog key stays the fact's identity and the definition's key the run's, the two composing. The expired rows go with the retention pass (expired_dedupe_keys). SQS FIFO's MessageDeduplicationId, EventBridge's DeduplicationId, Inngest's event id and Trigger.dev's idempotencyKey are the same shape.

Out of scope, plainly: holding a function open across a wait (a parked run holds no function and is woken as a new attempt) and a signal delivered into a body mid-step (run.signal fires a wait the body parked on, ADR-0050 decision 3). For a function that must stay resident, use Temporal, Vercel Workflow or DBOS; the FAQ says when.