Timers: Why a 30-Day Sleep Costs Nothing

The Sequence

Sequence of a 30-day workflow sleep across three lanes: worker, server and persistence. The workflow calls workflow.Sleep for 30 days, so the worker sends the server a StartTimer command for 30 days. The server appends TimerStarted to history and inserts a timer task with fire_at equal to now plus 30 days. The worker then evicts the workflow from its cache: zero threads, zero memory. Thirty days pass in which no process holds this workflow. Then the server's timer scan finds the task's fire_at reached; the server appends TimerFired and WorkflowTaskScheduled, and any polling worker gets the workflow task. That worker replays history, Sleep returns, and the next line of workflow code runs.
A 30-day sleep: the workflow leaves memory, and a timer task brings it back The sleep is just two saved rows: a TimerStarted event, and a timer task with a wake-up time. For all 30 days, that row is the only cost of the workflow.

Two things in that picture make this work:

  1. The timer is a row in a queue sorted by time. It is not a callback waiting in memory. Each history shard (see Inside the server) has a timer queue, sorted by wake-up time. A background process keeps asking "is anything due?" So a billion waiting timers cost a billion rows and an index scan. They take up no memory.
  2. The workflow is removed from memory between tasks. Workers keep recently active workflows in a cache, so they don't have to replay them every time (see Workers and task queues). But a workflow that will do nothing for 30 days is dropped from the cache within seconds. When the timer fires, a worker rebuilds it by replay. So "how many open workflows can I have?" is a question about storage, not memory.

cost of a sleeping workflow ≈ its history rows + one timer-task row

Everything in Temporal that waits uses this same timer: activity timeouts, workflow timeouts, and the pause between retries. There is only one way to wait in Temporal, and this is it.

  • Guarantees: A timer fires once, at or after its deadline. It survives any number of restarts of the workers and the server. It uses no memory or threads while it waits.
  • Does not guarantee: That the timer fires on time. Or that waiting is free if you do it over and over: each wait adds history events, and history has a size limit (see History limits and continue-as-new).