Summary#
Many real business operations are not one write but a sequence of steps across different services, external providers and people. An order, for example, goes through five steps:
- Charge the card.
- Reserve stock.
- Book a courier.
- Wait for a warehouse picker.
- Email the receipt.
Any step can fail, time out or take days. The server running the sequence can crash or be redeployed in the middle. A multi-step process must still finish correctly, or undo what it did, whatever happens.
There are four main approaches, from simplest to most powerful:
- Single-server orchestration with careful checkpoints.
- State machines stored in the database. A row records where each process is, and a runner advances it.
- Sagas. A sequence of local transactions, each with a compensating action that semantically undoes it, coordinated by events (choreography) or by a central coordinator (orchestration).
- Workflow engines and durable execution. Temporal, AWS Step Functions and similar systems persist every step's result. A crashed process resumes exactly where it stopped, and timers that wait days, human approvals and retries become ordinary code.
Whatever the tool, the core ideas are the same: persist progress after every step, make every step idempotent, define what to do when a step fails for good, and never keep the only copy of a process's state in memory.
Why It Exists#
Inside a single database, a transaction makes several writes atomic: all happen or none do. Real applications have to coordinate things a database cannot wrap in one transaction:
- Other services with their own databases, such as payments, inventory and shipping.
- External providers such as Stripe, a shipping carrier, an email service or an LLM API. These are slow, rate-limited and sometimes down.
- Waiting. A process may wait for a courier to accept, for a package to be delivered, or for a cooling-off period to pass.
- People. A manager must approve an expense, a reviewer must check a document, a customer must confirm by email.
Take the order flow from the summary. Written naively, it is six lines of code:
charge(order)
reserveInventory(order)
createShippingLabel(order)
waitForPick(order) -- a human, maybe hours
sendConfirmation(order)
markComplete(order)Jimmy Bogard gave a well-known conference talk about sequences like this, called "Six Little Lines of Fail". Its point is that each line hides several failure modes:
- The server crashes after
chargeand beforereserveInventory. The customer has paid, nothing is reserved, and no process remembers the order exists. chargetimes out. Did the charge happen or not? A blind retry may double-charge. Not retrying may ship an unpaid order.reserveInventoryfails because the item is out of stock. The charge must now be refunded. Who remembers to do that, and what if the refund fails?waitForPicktakes eight hours. No web request can stay open that long, and no process should sit in memory waiting.- A deploy restarts every server mid-flow. Thousands of in-flight orders lose their place.
- The business changes the flow next month, adding a fraud check before shipping. What happens to orders already halfway through the old flow?
Each issue can be patched in isolation. You can add retries, a delay queue for the wait, a cron job to find stuck orders, a flag to avoid double refunds, and a webhook handler for the picker. But the patches are scattered across services. System concerns (crashes, retries, timeouts) get tangled with business concerns (what if the item is missing?), and nobody can see the whole flow in one place. This is the kind of code that dominates on-call rotations.
The numbers make it unavoidable. Suppose each of six steps succeeds 99.9% of the time on the first try. The whole flow then succeeds without intervention 0.999^6 ≈ 99.4% of the time. At 1 million orders per day, about 6,000 orders a day hit some failure. Without automatic recovery, every one of them is a support ticket, a refund or a lost sale. A multi-step process design turns those 6,000 failures into automatic retries and compensations.
Interviewers like this topic because it separates designs that work on a whiteboard from designs that work in production. It shows up in payment systems, ride-hailing trip lifecycles, notification pipelines, order fulfilment, onboarding flows and, increasingly, AI agent pipelines. An agent pipeline is a long chain of slow, flaky, stateful LLM and tool calls.
How It Works#
The solutions form a spectrum. Simple options keep the flow inside one service. Powerful options hand the bookkeeping to a dedicated engine.
Moving down the spectrum buys more guarantees and visibility, at the cost of more infrastructure and new rules to learn. A good design picks the simplest point that handles the flow's failure modes.
Why multi-step flows fail midway#
Before choosing a tool, it helps to see exactly how these flows break. There are seven distinct failure modes, and every design must answer each one.
- Crash between steps. The process dies after step 2 commits and before step 3 starts. If progress lived only in memory, the flow is orphaned: half-done and forgotten.
- Crash inside a step, after the side effect but before recording it. The process calls Stripe and Stripe charges the card. Then the process crashes before writing "charged" to its database. On restart it does not know the charge happened. This is the dual-write problem: the external effect and your own record are two separate writes, and no transaction spans both.
- Ambiguous timeouts. A request times out. The remote side may have done the work, may be doing it, or may never have received it. The only safe responses are to retry with an idempotency key, so the remote side deduplicates, or to query the remote side for the outcome.
- Permanent business failures. These are not crashes but real "no" answers: the card is declined, the item is out of stock, the address is invalid. Retrying will not help. The flow must take a different branch or undo earlier steps.
- Long waits. Some steps wait minutes to weeks, for a courier, a human or a delivery. Holding a thread, a connection or an in-memory object for that long is impossible at scale.
- Concurrency on one process. Two events for the same order arrive at once, such as "payment captured" and "customer cancelled". If two handlers advance the same process in parallel, they can corrupt its state.
- Code changes during flight. A flow that lasts days will see several deploys. The new code must be able to resume executions that the old code started.
Failure modes, in depth#
The record-then-act ordering problem. For any step with an external side effect, you choose between two orders, and each fails differently:
- Act, then record: call Stripe, then write "charged". A crash in between gives a charge with no record. The retry charges again unless Stripe deduplicates by idempotency key.
- Record, then act: write "charging", then call Stripe, then write "charged". A crash after "charging" leaves an unknown state. On restart you must ask Stripe "did charge X happen?" or retry with the same idempotency key.
Neither ordering alone is enough. What makes it safe is idempotent side effects. Derive a stable idempotency key from the process ID and step name, such as order-551:charge. Send it on every attempt, so the provider performs the effect at most once however many times you call. Stripe's API, for example, accepts an Idempotency-Key header and returns the original result for a repeated key. If a provider offers no idempotency, you need a lookup-before-retry step: query the provider's records for this operation before trying again. See Idempotency.
The outbox for your own events. When a step updates your database and must publish an event, such as "order paid, now reserve stock", use a transactional outbox. Write the state change and an outbox row in one local transaction. A relay then publishes the outbox rows. A crash after commit cannot lose the event, and a crash before commit loses both. See Change Data Capture.
Timeouts must be chosen per step. A step needs three timeouts:
- A per-attempt timeout, for how long to wait for one call, such as 10 seconds for a payment API.
- A retry budget, for how long to keep retrying transient errors, such as 15 minutes with exponential backoff.
- A business deadline, for how long the step may take in total before the process takes a fallback path, such as "if no courier accepts within 20 minutes, cancel and refund".
Mixing these up is a classic bug. Retrying a declined card for 15 minutes is pointless. Giving up on a flaky shipping API after one 10-second timeout fails orders that one more attempt would have saved.
Classifying errors. Every step must sort its failures into transient errors (network blips, 5xx responses, rate limits), which are retried with backoff, and permanent errors (declined, invalid, not found), which are not retried but trigger a business decision. Some errors are unknown, such as a timeout. Treat those as transient, but only when the step is idempotent.
Single-server orchestration#
The simplest approach puts the sequence in one service, often the one that received the user's request. It calls each step in order and handles errors inline:
handlePlaceOrder(req):
order = db.insert(order, status = 'created')
try:
payment = payments.charge(order, idempotencyKey = order.id + ':charge')
db.update(order, status = 'paid', paymentId = payment.id)
inventory.reserve(order, idempotencyKey = order.id + ':reserve')
db.update(order, status = 'reserved')
catch OutOfStock:
payments.refund(payment, idempotencyKey = order.id + ':refund')
db.update(order, status = 'cancelled')This is a fine starting point when the steps are fast, typically seconds in total, few in number, and failures are rare. Two habits make it much safer:
- Persist progress after every step, so a crash leaves a record of how far the flow got.
- Use idempotency keys, so the steps can be safely re-run.
It breaks down in three cases:
- When the process crashes. The record says "paid" and nothing is driving the order forward. You need a recovery sweeper: a background job that finds orders stuck in an intermediate state for too long and resumes or compensates them. With that, you have half-built a state machine runner.
- When a step waits. A request handler cannot wait eight hours for a picker. The wait has to become an event that resumes the flow later.
- When the flow grows. With ten steps, each with retries, timeouts and compensations, the handler becomes a tangle. Every new edge case adds another branch.
Once you need the sweeper, you are halfway to the next option, so it is better to build that option deliberately.
State machines stored in the database#
The next step up makes the process explicit data. Each process instance, such as each order, is a row with a status column and the fields needed to continue. A runner, which is a pool of workers, repeatedly finds rows that need action, performs the next step, and moves the row to its next state. Any worker can resume any row, because all the state is in the database rather than in a particular process's memory.
A practical table looks like this:
id,typeandstatus.version, for optimistic concurrency on transitions.next_action_at: when the runner should next look at this row. This field covers retries, timeouts and timers.attemptsandlast_error.- Step outputs such as
payment_idandreservation_id. Compensations need these. You can only refund a payment if you stored its ID. deadline_at, the business deadline for the current state.created_atandupdated_at.
The runner loop is a variant of the job-queue claim covered in Pattern: Managing Long-Running Tasks:
-- Claim a batch of processes that are due, without blocking other runners
SELECT id, status, version FROM orders
WHERE status IN ('created', 'paid', 'reserved', 'refunding')
AND next_action_at <= now()
ORDER BY next_action_at
LIMIT 50
FOR UPDATE SKIP LOCKED;
-- After performing the step, move state with a guarded update
UPDATE orders
SET status = 'reserved', reservation_id = :rid, version = version + 1,
attempts = 0, next_action_at = now() + interval '20 minutes' -- courier deadline
WHERE id = :id AND status = 'paid' AND version = :v;How the pieces map:
| Process need | How a DB state machine handles it |
|---|---|
| Crash between steps | The row still says paid with next_action_at in the past, so another runner picks it up |
| Retries with backoff | On a transient error, set next_action_at = now() + backoff(attempts) and increment attempts |
| Timers and deadlines | Set next_action_at to the deadline; when it passes, the runner takes the timeout branch |
| External events (webhooks) | The handler does a guarded update, such as reserved to shipped only if the current status is reserved |
| Concurrency on one process | Guarded updates with version or a status check, so only one transition wins |
| Audit trail | Append each transition to an order_events table in the same transaction |
This approach is underrated. For many systems, a well-built state machine table plus a runner is the right answer:
- It needs nothing beyond the database you already run.
- The state is queryable with SQL, as in "how many orders are stuck in
paidfor more than an hour?" - Support staff can read the state directly, and it survives any crash.
The approach is also known as a process manager, a name popularised by Gregor Hohpe and Bobby Woolf's Enterprise Integration Patterns (2003). A process manager is a component that keeps the state of each process instance and decides the next step as messages arrive.
State machines in the database, in depth#
Make transitions explicit. Keep a transition table in code, such as {paid: {stock_reserved: 'reserved', out_of_stock: 'refunding'}}, and reject any transition not in it. Every state change goes through one function. That function checks the transition is legal, does a guarded update and writes the audit row. Ad hoc UPDATE orders SET status = ... scattered around the codebase is how impossible states, such as "shipped but refunded", appear.
Terminal and stuck states. Define terminal states, such as delivered and cancelled, that never change. Then alert on rows that stay in any non-terminal state past an age threshold. A "stuck processes" dashboard grouped by state and age is the single most useful operational view for any workflow system, whatever the technology.
Fairness and hot spots. The runner's ORDER BY next_action_at gives oldest-first processing. If one customer creates 100,000 processes at once, they can starve everyone else. Add a per-tenant cap, or priority classes, as covered in the long-running tasks pattern.
Where it gets painful. The approach strains as flows grow:
- Branching and parallelism. "Reserve stock in three warehouses in parallel, and continue when any two succeed" is awkward to model as a single status column. You end up with child rows and join logic.
- Many timers per process. A reminder at 24 hours, escalation at 48 hours and auto-cancel at 7 days needs several timer columns or a separate timers table.
- The code becomes the flow, but scattered. The flow's logic is split between the transition table, step handlers, webhook handlers and the sweeper. Reading the "happy path" means reading five files.
- Versioning. Adding a state means migrating in-flight rows, or supporting old and new transitions at once.
- Throughput. Every step is at least one database write, plus the claim. At thousands of transitions per second, the orders table and its indexes become hot. Partition by ID range or tenant, or move to an engine built for it.
When you find yourself building a generic "workflow table" with JSON state, timers and retries for many process types, you are rebuilding a workflow engine. That is the point to evaluate one.
The saga pattern, recapped#
A saga is the standard model for a multi-step process across services. The term comes from Hector Garcia-Molina and Kenneth Salem's paper "Sagas" (SIGMOD 1987). A saga is a sequence of local transactions T1, T2, ..., Tn, each committed in one service's own database. For each step there is a compensating transaction C1, C2, ..., which semantically undoes it. The saga guarantees one of two outcomes:
- All steps complete: T1, T2, ..., Tn.
- The saga stops at some step j and compensates in reverse: T1, ..., Tj, then Cj, ..., C1.
There is no global lock and no two-phase commit. Each step commits immediately, and other transactions can see intermediate states, which is the price of avoiding distributed locks. The Distributed Transactions page compares sagas with 2PC and TCC in detail. Here is the order flow as an orchestrated saga, with a failure in the middle:
Compensation is semantic, not a rollback. You cannot un-charge a card, but you can refund it. You cannot un-send an email, but you can send a correction. A compensation is a new forward action that restores business consistency. That has four consequences:
- Compensations can fail too, so they must be retried until they succeed, and they must be idempotent.
- Some steps cannot be compensated at all, such as a shipped parcel, a released payout or a sent SMS. Order the steps so that these happen last.
- Compensations may be partial or have a cost. A refund may take days to reach the customer, and a cancellation fee may apply.
- Other users may have seen the intermediate state. A customer saw "order confirmed" before it was cancelled, so notifications must handle that.
Ordering steps: compensatable, pivot, retriable. Chris Richardson's Microservices Patterns (Manning, 2018) gives a useful structure:
- Compensatable steps come first. They can be undone, like a stock reservation or a card authorisation.
- The pivot is the go or no-go point. Once it commits, the saga will run to completion. Capturing payment is a common pivot.
- Retriable steps come after the pivot. They are guaranteed to succeed eventually with retries, like sending the receipt or creating the shipment record.
With this ordering, the saga either fails before the pivot and compensates cleanly, or passes the pivot and only ever retries forward.
Event-driven choreography#
In a choreographed saga there is no central coordinator. Each service listens for events and reacts by doing its step and publishing a new event:
Strengths:
- Loose coupling. Services know about events, not about each other. A new consumer, such as a loyalty-points service, can subscribe to
OrderPlacedwithout changing anyone else. - No single coordinator to scale or fail.
- Natural fit for event-driven systems that already run on Kafka or a similar log. See Event-Driven Architecture.
Weaknesses, which are often decisive for complex flows:
- The flow is implicit. No single place describes the order lifecycle. To understand it, you must trace event subscriptions across many services. Distributed tracing helps, but cannot show the intended flow.
- Compensation logic is spread out. Every service must know which failure events should trigger its own undo, and the failure paths are the least tested.
- Cyclic dependencies. Payment listens to inventory events and inventory listens to payment events, so changes ripple in both directions.
- Timeouts are hard. "If no courier is booked within 20 minutes, cancel" needs someone to own a timer. In pure choreography nobody does, so a coordinator sneaks back in.
- Changing the flow is risky. Inserting a fraud check between payment and inventory means changing which event inventory listens to, across teams and deploys.
A rule of thumb: use choreography for short, stable flows, typically two to four steps, where loose coupling matters most. Notifications fanning out from a domain event are a good example. Use orchestration for long, branching or frequently changing flows where someone must own deadlines and compensations. Many systems mix both: an orchestrator drives the core flow, and publishes domain events that other services choreograph around.
Workflow orchestration engines#
A workflow engine is a dedicated system that runs the coordinator for you. You describe the flow, and the engine handles four things:
- Persistence. It stores every step's result and the current position durably.
- Scheduling. It decides which step runs next and hands it to a worker.
- Retries and timeouts. These follow per-step policies you declare.
- Timers and external events. It can wait for a deadline or a signal without holding any worker.
There are three families, and they are not interchangeable.
1. Durable execution engines: workflows as code. Examples are Temporal, its predecessor Cadence (built at Uber), Restate, DBOS, and Microsoft's Azure Durable Functions (built on the Durable Task Framework). You write the workflow as an ordinary function in Go, Java, TypeScript, Python or .NET. The engine makes that function durable: if the process running it dies, another process continues it from the same point, with all local variables intact. Branches, loops, parallelism and error handling are plain language constructs. This family suits complex, long-lived, per-entity business processes, such as one workflow per order, payment, trip or user onboarding, at very high volume.
2. Managed state-machine services: workflows as configuration. Examples are AWS Step Functions, defined in the JSON-based Amazon States Language, Google Cloud Workflows, defined in YAML, and Netflix's Conductor, a JSON DSL that is now community-maintained. You declare states (task, choice, parallel, map, wait) and transitions, and the service executes them, calling Lambda functions, containers or AWS service APIs directly.
AWS Step Functions offers two types:
- Standard workflows can run for up to a year. They give exactly-once execution of each state transition and keep a full visible history. They are priced per state transition.
- Express workflows can run for up to five minutes, give at-least-once execution when started asynchronously, and are built for very high event rates. They are priced by duration and request count.
This family suits teams already deep in one cloud, flows of moderate complexity, and teams that want a visual graph and no servers to run. Limits to plan around:
- Each state's input and output payload is capped, at 256 KB in Step Functions.
- A Standard execution's history is capped at 25,000 events.
- Expressing complex logic in JSON becomes unwieldy.
3. DAG schedulers for data pipelines. Examples are Apache Airflow, created at Airbnb in 2014, Dagster, Prefect and Argo Workflows on Kubernetes. A pipeline is a directed acyclic graph of tasks, usually run on a schedule, such as "every night at 02:00: extract, transform, load, then refresh the dashboards".
How Airflow differs from the first two families, and why it is the wrong tool for business processes:
- Batch orientation. Airflow runs DAG runs, usually tied to a schedule and a data interval, such as "the run for 2026-12-01". It is not built to start a fresh workflow per order, a million times a day, in milliseconds.
- Scheduling latency. Its scheduler loop has seconds of latency between tasks. That is fine for hour-long ETL jobs and poor for interactive flows where a user is waiting.
- No first-class signals or long waits per instance. Airflow has sensors that poll for a condition, but waiting days for a specific customer's approval, and reacting instantly when it arrives, is not its model.
- Static graphs. DAGs are mostly defined up front, while business workflows branch on runtime data constantly.
- Data-centric features. It offers backfills, catch-up runs, data-aware scheduling and lineage, which business processes don't need.
Use Airflow and its relatives for data pipelines, and durable execution or Step Functions for business processes. See Batch and Stream Processing.
How durable execution works#
Durable execution looks like magic, because a plain function survives crashes. It is easiest to understand by imagining building it yourself, one problem at a time.
Problem 1: survive a crash without repeating side effects. Route every external operation through the framework. When an operation finishes, the framework appends a record of it, with its result, to a durable event history for that workflow execution:
WorkflowStarted { orderId: 551 }
ActivityCompleted { name: charge, result: payment p-77 }
ActivityCompleted { name: reserve, result: reservation r-12 }If the worker crashes now, a new worker loads the history and replays the workflow function from the beginning. When the code calls charge, the framework sees a recorded result and returns p-77 immediately, without calling Stripe. The same happens for reserve. When the code reaches bookCourier, there is no recorded result, so the framework actually runs it. The function's local variables are rebuilt by re-executing the code, so nothing needs to be serialised except the history.
This splits the code into two kinds:
- Workflow code is the orchestration logic. It is replayed, so it must be deterministic.
- Activities are the operations that touch the outside world, such as API calls, database writes and emails. They run once per attempt, and their results are recorded.
Problem 2: replay must make the same decisions. Suppose the workflow says "if the time is before 17:00, request same-day pickup". The first run at 16:59 takes the same-day branch. The worker crashes, and replay happens at 17:03, so the code now takes the other branch. The history says same-day pickup was requested, but the replayed code asks for next-day. The execution no longer matches its history. So workflow code must be deterministic. Anything that can differ between runs must go through the framework, which records the value the first time and returns the same value on replay:
- the current time;
- random numbers;
- UUIDs;
- reading configuration;
- calling another service.
This is why Temporal's SDKs provide workflow-safe versions of the clock, sleep and random functions, and why calling the network directly from workflow code is forbidden.
Problem 3: wait for days without a process. sleep(5 days) cannot hold a thread for five days, and a million waiting orders cannot hold a million threads. So the framework turns the sleep into a durable timer. It records "TimerStarted, fire at May 15 10:00" in the history, stores a timer task ordered by deadline, and unloads the workflow entirely. No worker is used while it waits. A timer service scans due timers. When the deadline arrives, it appends "TimerFired" and schedules the workflow to run. Replay reaches the sleep, sees that it has fired, and continues. A workflow can sleep for months at the cost of a database row.
Problem 4: let the outside world wake the workflow. Delivery doesn't take a fixed time. You want to wait until the carrier says "delivered". The carrier's webhook calls the engine, which appends a "PackageDelivered" event to that workflow's history and schedules it to run. Replay reaches waitUntilDelivered, finds the event and continues. Temporal calls this external input a signal. Signals are recorded durably even if the workflow is not currently waiting for them, so an early signal is not lost.
The remaining gap: activities are at-least-once. If Stripe charges the card and the worker crashes before reporting completion, the engine never recorded it. It will retry the activity after its timeout. Durable execution does not remove the need for idempotency. It narrows it to one place, the activity boundary, where you pass an idempotency key derived from the workflow ID and step.
Durable execution, in depth#
Activity options are the retry policy. For each activity call, you declare timeouts and a retry policy, and the engine enforces them:
- Start-to-close timeout: the maximum time for one attempt.
- Schedule-to-close timeout: the total time including retries.
- Heartbeat timeout: for long activities that report progress. If a heartbeat is missed, the engine assumes the worker died and retries elsewhere. A heartbeat can carry progress details, so the next attempt resumes rather than restarts.
- Retry policy: the initial interval, backoff coefficient, maximum interval, maximum attempts, and a list of non-retryable error types, such as
CardDeclined.
The workflow code then sees only final outcomes: success, or a failure after the policy is exhausted. It branches on those like ordinary exceptions. System-level retries are configuration, and business-level decisions are code. This is the separation that the patched-together approach lacked.
Queries and updates. Beyond signals, engines let outside callers query a running workflow's state read-only, as in "what step is order 551 on?", without touching the database. Newer Temporal versions add updates: a synchronous request that the workflow can validate and respond to, such as "change the delivery address, if the order hasn't shipped".
Child workflows and fan-out. A workflow can start child workflows, such as one per item in an order or one per page of a crawl, and wait for some or all of them. Children have their own histories, which keeps each history small, and their own retry and timeout policies.
Workflow ID as the business key. Start the workflow with ID order-551. The engine guarantees that only one open execution exists per ID, which gives deduplication on start for free. A duplicate "start order 551" request fails or returns the existing execution, depending on the ID-reuse policy. Signals are addressed by the same ID, so the carrier webhook only needs the order ID.
Engines in comparison:
- Temporal provides the server, as open source or a hosted cloud service, and SDKs for Go, Java, TypeScript, Python, .NET and PHP. Persistence is Cassandra, PostgreSQL or MySQL.
- Restate and DBOS are newer takes. Restate runs as a single binary with an embedded log. DBOS stores workflow state in your own PostgreSQL. Both aim to lower operating cost.
- Azure Durable Functions gives orchestrator functions with replay semantics on Azure Functions.
- AWS Step Functions is not replay-based. It is a state-machine interpreter, but it gives similar durability and retry guarantees for declaratively defined flows.
Timers and human-in-the-loop steps#
Many processes wait on people and calendars, not machines:
- An expense report needs manager approval.
- A new seller's documents need a compliance review.
- An account deletion has a 30-day grace period during which the user can cancel.
- An unpaid invoice gets a reminder at day 7, a final notice at day 14, and goes to collections at day 30.
- A free trial converts to paid after 14 days unless cancelled.
These are hard with ordinary infrastructure, because the waits are long, the outcome arrives from outside, and there are escalation timers racing against the human. In a durable workflow, the logic reads directly:
How the pieces work:
- A durable timer races a signal. In Temporal's TypeScript SDK,
condition(() => approved !== undefined, '48 hours')waits until a signal handler setsapproved, or until 48 hours pass, and returns which happened. No worker is held during the wait. - The human acts through the product's UI. The approve button calls your API, which sends a signal to workflow
expense-9041. The workflow, not the UI, decides what the approval means. It might ignore a late approval after auto-rejection. - Step Functions uses task tokens. A state declared with
.waitForTaskTokenpauses and emits a unique token, which you store with the approval request. When the human approves, your API callsSendTaskSuccesswith the token and the result, and the execution continues. AHeartbeatSecondsorTimeoutSecondssetting on that state provides the escalation deadline. - In a DB state machine, the same thing is a status of
awaiting_approvalwithdeadline_at. The approval endpoint does a guarded update, and the runner moves rows whose deadline has passed to the escalation state.
Design points for human steps:
- Make the human action idempotent and addressed. An approve link clicked twice, or approve and reject clicked in two tabs, must produce one decision. The workflow accepts the first valid signal and ignores the rest.
- Store who decided and when. This is part of the audit trail, and often a compliance requirement.
- Keep human-facing state queryable. "Your request is waiting for Priya since Tuesday" comes from querying the workflow or its state row, not from guessing.
- Plan for the person never acting. Every human wait needs a deadline and a default outcome.
- Business-calendar timers. "Three business days" is not 72 hours. Compute deadlines with a calendar activity, which is non-deterministic and so must not run in workflow code, then sleep until that instant.
Compensation, in depth#
Compensation is where multi-step designs succeed or fail, because it is the least exercised code path. Six principles keep it reliable.
1. Record what you need to undo. Every step's result must be stored: the payment ID, reservation ID or shipment ID. Without the payment ID you cannot refund. In durable execution these are just local variables. In a DB state machine they are columns.
2. Compensate in reverse order, only for completed steps. Push a compensation onto a stack after each step succeeds. On failure, pop and run them in reverse. Steps that never ran have nothing to undo. Steps whose outcome is unknown, because of a timeout, need a compensation that is safe if the step never happened, like "release reservation r-12, or do nothing if it doesn't exist".
3. Compensations must be idempotent and retried until they succeed. A refund that fails because the payment provider is down must be retried for hours if necessary, not abandoned. Give compensations generous retry policies. Route the ones that truly fail, such as "refund rejected because the card account is closed", to a manual resolution queue with full context, rather than dropping them.
4. Some actions can't be undone, so move them past the pivot. Sending an email, shipping goods, paying out to a seller or calling a non-refundable partner API should happen only after the point of no return. If you must do something irreversible early, add a semantic compensation: an apology email, a return label, or a clawback request.
5. Prefer reservations over actions before the pivot. An authorisation on a card is compensatable by voiding it, which the customer never sees. A capture needs a refund, which takes days to appear. A stock hold with a TTL is compensatable, or self-expiring, while a stock deduction is harder to reverse. The more of the pre-pivot steps are reservations, the cheaper failure becomes. See Pattern: Dealing with Contention for TTL holds.
6. Forward recovery is often better than backward recovery. Not every failure should compensate. If the courier booking fails, retry with a different courier provider, or wait and retry later, before refunding the customer. Compensation, or backward recovery, is for when the business goal is truly unreachable. Forward recovery keeps pushing towards completion.
A compensation stack in workflow code looks like this, in Temporal-style TypeScript:
export async function orderWorkflow(order: Order): Promise<string> {
const undo: Array<() => Promise<void>> = [];
try {
const auth = await authorizeCard(order); // compensatable
undo.push(() => voidAuthorization(auth.id));
const hold = await reserveStock(order); // compensatable
undo.push(() => releaseStock(hold.id));
const courier = await bookCourierWithFallback(order); // forward recovery inside
undo.push(() => cancelCourier(courier.id));
await captureCard(auth.id); // pivot: no undo after this
undo.length = 0;
await sendReceipt(order); // retriable until it succeeds
return 'completed';
} catch (err) {
for (const step of undo.reverse()) {
await step(); // each has its own retry policy
}
await notifyCustomerCancelled(order, String(err));
return 'cancelled';
}
}Making a step run exactly once#
"Exactly once" for a side effect is impossible to guarantee in general across a network, because a crash at the wrong moment always leaves doubt. What you can achieve is exactly-once effect: at-least-once execution plus deduplication at the receiver.
- Stable idempotency keys per step, such as
workflowId + ':' + stepName, orworkflowId + ':' + stepName + ':' + iterationinside loops. Send the same key on every retry. Never derive it from attempt numbers or timestamps. - Receivers that deduplicate. Your own services store processed keys in a table with a unique constraint, written in the same transaction as the effect, often called an inbox. External providers such as Stripe deduplicate by
Idempotency-Key. - Lookup before retry for providers without idempotency. Before re-sending a bank transfer, query the bank for a transfer with your reference. Only send it if none exists.
- Engine guarantees cover the orchestration, not the world. Temporal records each activity completion exactly once in the history, and Step Functions Standard executes each state transition exactly once. But the activity body itself may run more than once if a worker dies after doing the work and before reporting it.
Updating workflows that are already running#
A workflow that lasts days will see many deploys. With replay-based engines this is a real hazard. If you change the workflow code, replaying an old history through the new code may take different branches or call activities in a different order. The engine then raises a non-determinism error, and the execution is stuck until fixed. There are three strategies, from lightest to heaviest.
1. Versioning branches in code. Mark the change point so that old executions take the old path and new executions take the new one:
- In Temporal's TypeScript SDK,
if (patched('add-fraud-check')) { await fraudCheck(order); }records a marker the first time new code passes that point. - On replay, executions that started before the patch have no marker, so they skip the new step. Executions with the marker take it.
- Once all old executions have finished, you call
deprecatePatch, and later remove the branch.
Go and Java have an equivalent GetVersion API.
2. Versioned workers. Run the old and new code side by side. Each execution is pinned to the worker build it started on, and the old fleet keeps running until its executions drain. Temporal's worker versioning, which routes executions by build ID, and Step Functions versions and aliases both support this. It is cleaner for large changes, at the cost of running two fleets for a while.
3. New workflow type plus migration. For a big redesign, create orderWorkflowV2, start all new executions on it, and let V1 executions finish naturally. For very long-lived executions, such as subscriptions lasting months or entity workflows that never end, write a migration. Signal each V1 execution to stop at a safe point and hand over its state, then have it continue as new, restarting itself as a V2 execution carrying the current state.
DB state machines have the same problem in a different form. Adding a state or changing a transition means deciding what happens to rows already in the old states. Usually this means a data migration plus code that accepts both old and new transitions during the rollout.
Test it. Temporal provides a replayer. You download real production histories, replay them against the new code in CI, and the build fails on any non-determinism error. This is the single best protection against stuck executions after a deploy.
Keeping workflow state small#
Every event in a workflow's history is stored, and the whole history is loaded to replay. Histories that grow without bound slow replay and hit engine limits. Temporal warns as a history passes about 10,000 events or 10 MB, and terminates executions at around 50,000 events or 50 MB. A single payload is capped at a few megabytes. Step Functions caps state payloads at 256 KB and Standard execution histories at 25,000 events. Four techniques keep state in check:
- Store references, not payloads. Pass an S3 key or a database ID between steps, not the 40 MB PDF or the full list of 100,000 recipients. The activity fetches the data it needs. This is the same claim-check idea as in Pattern: Handling Large Files and Blobs.
- Continue-as-new for long loops. An entity workflow, such as one workflow per subscription that loops monthly, would accumulate events for ever. After a number of iterations, or when the history is large, it calls continue-as-new. This atomically completes the current execution and starts a fresh one with the same workflow ID and the current state as input, so the history resets.
- Child workflows for fan-out. Processing 10,000 items in one workflow creates tens of thousands of events. Instead, start children in batches, say 100 children each handling 100 items. Each history stays small, and the parent only records children starting and finishing.
- Keep large state outside. Shopping carts, documents and model outputs belong in a database or object store. The workflow keeps only the small control state: IDs, statuses and counters.
Dealing with external events#
Most real workflows react to the outside world: payment webhooks, carrier updates, user clicks, partner callbacks. Five rules keep external events safe.
- Correlate by business key. Give each workflow a deterministic ID derived from the business entity, such as
order-551. The webhook handler extracts the order ID from the payload, or from metadata you attached earlier, like Stripe metadata, and signals that workflow. No lookup table is needed. - Verify, then signal fast. The webhook endpoint should check the signature, deduplicate by the provider's event ID, signal the workflow, and return 200 quickly. Heavy work happens inside the workflow. If the engine is briefly unavailable, write the event to a durable queue first and signal from there, so the provider's retries are not your only safety net.
- Events can arrive early, late, twice or out of order.
- Early: a "delivered" event arrives before the workflow reaches its wait. Durable signals are buffered in history, so the workflow sees it when it gets there.
- Late: a payment confirmation arrives after the workflow already timed out and cancelled. The workflow, or a follow-up handler, must decide whether to refund automatically or reinstate the order.
- Twice: deduplicate by event ID.
- Out of order: use timestamps or sequence numbers from the source, and ignore stale updates.
- Signal-with-start. For events that may arrive before any workflow exists, such as the first event for a new entity, use signal-with-start. It delivers the signal to the workflow, starting it first if it is not yet running. Two racing webhooks then cannot create two workflows.
- Poll when you must. Some partners have no webhooks. A polling activity with heartbeats and backoff, such as "check shipment status every 30 minutes until delivered or 14 days pass", is acceptable and still durable.
Worked example: order fulfilment at 2 million orders a day#
The flow has six steps:
- Fraud check.
- Authorise the card.
- Reserve stock at the nearest warehouse, falling back to the next nearest.
- Wait for the warehouse pick confirmation, up to 4 hours, or escalate.
- Capture payment. This is the pivot.
- Book the courier, wait for delivery (typically 1 to 3 days), and send a review request 2 days after delivery.
Volume:
- 2 million orders per day is about 23 per second on average. At a 5× peak, it is about 115 per second.
- Each order produces about 12 activities, 3 timers and 2 to 3 signals: pick confirmed, courier assigned, delivered.
- In Temporal terms, that is roughly 60 history events per order.
- 60 events × 115 orders per second ≈ 7,000 history writes per second at peak. That is well within a moderately sized cluster on Cassandra or a sharded SQL store.
Open executions. Orders stay open for about 5 days on average, through delivery plus the review-request timer. So about 2 million × 5 = 10 million executions are open at any time. They cost storage, not compute. At about 30 KB of history each, that is around 300 GB, plus retention of closed histories for, say, 7 days. Almost all of them are idle, waiting on timers or signals.
Workers are sized by work, not by open executions. Activities run at about 115 × 12 ≈ 1,400 per second at peak, and most are API calls taking 50 to 500 ms. By Little's law, about 1,400 × 0.3 s ≈ 420 activity slots are busy at once. With about 50 concurrent activities per worker process, about 10 worker processes suffice, so run 20 to 30 for headroom and isolation. Separate task queues isolate slow or sensitive work. For example, a payment queue runs on a hardened worker pool, and a warehouse queue gets its own rate limits matched to each warehouse system's capacity.
Failure behaviour:
- A worker dies mid-activity: the activity times out and retries on another worker. Workflow code replays from history on whichever worker picks it up next.
- A warehouse API goes down for an hour: reservation activities retry with backoff, capped at a 2-hour budget, then fall back to the next warehouse. Orders slow down but nothing is lost.
- The engine cluster has an outage: nothing progresses during it, but nothing is lost either. Timers that should have fired during the outage fire on recovery. Size the cluster for the catch-up burst.
The design choice in one sentence: at this volume and complexity, with long waits, human steps, fallbacks and a pivot, a durable execution engine saves months of building and debugging a home-grown state machine. At 20 orders a day with three steps, a status column and a runner would be simpler and entirely sufficient.
When to Use It#
Use explicit multi-step process handling, through a state machine, saga or workflow engine, when a flow has any of these properties:
- It spans services or providers that cannot share one database transaction, such as payment, inventory, shipping, KYC (know-your-customer identity checks) or email.
- It takes longer than a request. Minutes, hours or days of processing or waiting.
- It involves people or calendars: approvals, reviews, grace periods, reminders, trials or escalations.
- Partial completion is costly. A charge without a shipment, or an account created without provisioning, must be undone or completed.
- It has complex error handling: fallbacks, compensations, retries with business deadlines.
- It must be auditable, answering "what happened to order 551, step by step?"
Common interview scenarios include:
- payment processing and payouts;
- order fulfilment and delivery;
- a ride-hailing trip lifecycle (request, match, pickup, trip, payment, rating);
- user onboarding and KYC;
- infrastructure provisioning;
- notification campaigns with retries and preferences;
- video processing pipelines;
- AI agent workflows that chain LLM calls, tool calls and human review.
When NOT to Use It#
- One database, one transaction. If all the steps touch tables in the same database and finish in milliseconds, use a database transaction. A saga adds complexity and removes isolation for no benefit.
- Simple async jobs. "Resize this image" or "send this email" is a single background job with retries, not a workflow. See Pattern: Managing Long-Running Tasks.
- Pure data pipelines. Scheduled ETL and analytics DAGs belong in Airflow, Dagster or Spark, not in a per-entity business workflow engine.
- Very high-rate, very short flows. Per-event stream processing at hundreds of thousands of events per second, such as click aggregation, belongs in a stream processor like Flink or Kafka Streams. Starting a workflow per click would be absurd.
- Don't introduce an engine for one flow. Running a Temporal cluster has a real operational cost, although the hosted service reduces it. For one or two simple flows, a DB state machine is often the better trade.
- In an interview, don't reach for it by reflex. If the problem is a URL shortener or a news feed, there is no multi-step process worth orchestrating. Mention a workflow engine only where the flow genuinely needs one.
How to Implement It#
- Draw the flow as a state diagram first. List every step, its success outcome, its permanent failures, its timeout, and what happens next in each case. Most bugs are visible on the diagram before any code exists.
- Classify each step: compensatable, pivot or retriable. Reorder so that irreversible steps come after the pivot, and prefer reservations over final actions before it.
- Define a compensation for every compensatable step, and make each one idempotent and safe to run even if the forward step never happened.
- Give every side effect a stable idempotency key, derived from the process ID and step name, and make receivers deduplicate.
- Set three timeouts per step: per attempt, total retry budget, and business deadline. Separate transient from permanent errors.
- Choose the execution model:
- A DB state machine for a few simple flows.
- Choreography for short, loosely coupled reactions.
- Step Functions or Cloud Workflows for cloud-native flows of moderate complexity.
- Temporal or another durable execution engine for many complex, long-lived flows.
- Correlate external events by business key, verify and deduplicate webhooks, and plan for events that arrive early, late or twice.
- Keep state small: references, not payloads; continue-as-new for loops; child workflows for fan-out.
- Plan versioning before the first deploy: patch markers or versioned workers, plus replay tests in CI.
- Observe everything: a stuck-process dashboard grouped by state and age, compensation rates, manual-queue depth, and the latency of each step.
Here is a durable order workflow with a human wait, a timer race and a fallback, in Temporal's TypeScript SDK:
import { proxyActivities, defineSignal, setHandler, condition, sleep } from '@temporalio/workflow';
import type * as acts from './activities';
const { authorize, voidAuth, reserve, release, capture, bookCourier, email } =
proxyActivities<typeof acts>({
startToCloseTimeout: '30 seconds',
retry: { maximumAttempts: 10, backoffCoefficient: 2, nonRetryableErrorTypes: ['Declined'] },
});
export const picked = defineSignal('picked');
export const delivered = defineSignal('delivered');
export async function fulfilOrder(o: { id: string; warehouses: string[] }): Promise<string> {
let isPicked = false, isDelivered = false;
setHandler(picked, () => { isPicked = true; });
setHandler(delivered, () => { isDelivered = true; });
const auth = await authorize(o.id); // key: o.id + ':auth'
let hold: string | undefined;
for (const wh of o.warehouses) { // forward recovery: next warehouse
hold = await reserve(o.id, wh).catch(() => undefined);
if (hold) break;
}
if (!hold) { await voidAuth(auth); return 'cancelled: no stock'; }
if (!(await condition(() => isPicked, '4 hours'))) { // timer races the signal
await email(o.id, 'warehouse-escalation');
if (!(await condition(() => isPicked, '20 hours'))) {
await release(hold); await voidAuth(auth); return 'cancelled: not picked';
}
}
await capture(auth); // pivot: forward only from here
await bookCourier(o.id);
await condition(() => isDelivered, '14 days');
await sleep('2 days'); // durable timer, no worker held
await email(o.id, 'review-request');
return 'completed';
}| Technology | Fits when |
|---|---|
| Status column + runner (PostgreSQL/MySQL, SKIP LOCKED) | A few flows, modest volume, and you want no new infrastructure |
| Kafka / SNS+SQS events (choreography) | Short reactive flows across loosely coupled teams; fan-out of domain events |
| AWS Step Functions (Standard / Express) | AWS-native flows calling Lambda and AWS services; visual graphs; up to 1 year (Standard) |
| Google Cloud Workflows | GCP-native orchestration of HTTP and Google Cloud APIs, defined in YAML |
| Temporal (self-hosted or cloud) | Many complex, long-lived, per-entity workflows in code; signals, timers, versioning at scale |
| Cadence | Existing Cadence deployments; Temporal's open-source predecessor from Uber |
| Restate / DBOS | Durable execution with lighter operations: embedded log, or state in your own PostgreSQL |
| Azure Durable Functions | Azure-native orchestrations with replay semantics on serverless functions |
| Netflix Conductor / Orkes | JSON-defined orchestration of microservices with a visual UI |
| Airflow / Dagster / Prefect / Argo | Scheduled data pipelines and batch DAGs, not per-request business processes |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single-server orchestration | Simplest; easy to read; no new infrastructure | Crashes orphan flows; can't wait long; grows into a tangle | Few fast steps, rare failures, with a sweeper |
| DB state machine + runner | Durable; SQL-queryable; uses the existing DB | Flow logic scattered; timers and parallelism awkward; hot tables at scale | A handful of flows at moderate volume |
| Choreographed saga | Loose coupling; no coordinator; easy to add consumers | Implicit flow; spread-out compensation; nobody owns timeouts | Short, stable flows; domain-event fan-out |
| Orchestrated saga (custom) | One place owns the flow and compensations | You build persistence, retries and timers yourself | Few complex flows and a strong reason to avoid an engine |
| Managed workflow (Step Functions) | Serverless; visual; durable; exactly-once transitions (Standard) | JSON/YAML DSL; payload and history limits; cloud lock-in; cost per transition | Cloud-native flows of moderate complexity |
| Durable execution (Temporal and others) | Workflows as plain code; durable timers, signals, retries; scales to millions of open executions | New infrastructure and concepts; determinism rules; versioning discipline | Many complex, long-lived workflows |
| DAG scheduler (Airflow) | Great for scheduled data pipelines, backfills, lineage | Seconds of scheduling latency; not per-entity; weak for signals and long waits | Batch ETL and analytics |
Common Pitfalls#
- Keeping process state only in memory. Any crash or deploy orphans in-flight flows. Persist after every step.
- Non-idempotent steps. Retries, which every model has, double-charge, double-ship or double-email.
- Idempotency keys that change between attempts, such as keys that include a timestamp or attempt number. They defeat deduplication entirely.
- Retrying permanent errors. A declined card retried 10 times annoys the bank and delays the customer. Mark such errors non-retryable.
- Missing compensations, or compensations that are never tested. The failure path runs for the first time in production, during an incident.
- Irreversible actions before the pivot, such as emailing "your order shipped!" before payment is captured.
- Non-deterministic workflow code in replay engines: reading the clock, random numbers, environment variables or the network directly. This leads to non-determinism errors after a crash or deploy.
- Changing workflow code without versioning. Every in-flight execution breaks on replay.
- Unbounded histories: loops without continue-as-new, or large payloads passed between steps.
- No deadline on human waits. Processes wait for ever for someone who left the company.
- Choreography for long, branching flows. Nobody can explain the order lifecycle, and nobody owns the 20-minute courier timeout.
- Using Airflow for per-order business processes, or Temporal for nightly ETL. Each is the wrong tool for the other's job.
- No stuck-process monitoring. The first sign of a broken step is an angry customer a week later.
Real-World Examples#
- Uber, Cadence and Temporal. Uber built Cadence, an open-source workflow engine, to run long-lived business processes reliably. Two of its creators, Maxim Fateev and Samar Abbas, later founded Temporal Technologies, and Temporal began as a fork of Cadence. Their earlier work on Amazon's Simple Workflow Service (SWF) and Microsoft's Durable Task Framework shaped the durable execution model.
- AWS Step Functions launched in 2016. AWS documents its use for order processing, ETL orchestration, machine-learning pipelines and human approval flows, the latter through task tokens.
- Netflix Conductor. Netflix open-sourced Conductor in 2016 to orchestrate microservice workflows, such as content ingestion and encoding pipelines, with JSON-defined workflows. Netflix later stopped maintaining it, and the project continues through the community and Orkes.
- Airbnb Airflow. Airbnb created Airflow in 2014 for scheduling data pipelines, and it became an Apache project. It is the archetype of the DAG scheduler, and a useful contrast with business-process engines.
- Microsoft. Azure Durable Functions and the Durable Task Framework brought replay-based orchestration to serverless functions on Azure.
- Stripe publicly documents idempotency keys on its API. That is the property that makes payment steps safe to retry from any orchestrator.
Case studies that use this pattern#
- Design a Payment System: authorisation, capture, ledger entries, payouts, webhooks and reconciliation as a saga with a pivot.
- Design a Ride-Hailing App: a trip lifecycle state machine from request to rating, with timeouts on driver acceptance.
- Design a Notification System: multi-channel delivery with retries, preferences and fallbacks.
- Design a Local Delivery Service: order placement, picking, courier dispatch and delivery tracking.
- Design a Video Streaming Platform: upload, transcode fan-out, packaging and publishing.
- Design a Job Scheduler: job dependencies, retries and durable timers.
- Design ChatGPT: agent and tool-call pipelines with long, flaky steps.
In the Interview#
Deep Dive: Inside a durable execution engineShow
How does an engine like Temporal or Cadence keep millions of workflows alive, survive crashes, and fire timers on time? The architecture is worth knowing, because the same ideas come back whenever you build your own orchestrator.
The pieces. A Temporal cluster has four server roles plus a persistence layer:
- Frontend: a stateless gRPC gateway. It handles rate limiting, authentication and routing.
- History service: owns workflow state. Workflow IDs are hashed onto a fixed number of history shards, often 512 to 16,384 and chosen at cluster creation. Each shard is owned by exactly one history host at a time, with ownership managed through a membership ring and lease. That gives a single writer per shard, so updates to one workflow are serialised without distributed locks.
- Matching service: hosts task queues. Workers long-poll it for workflow tasks and activity tasks.
- Worker service (internal): runs system workflows such as archival and replication.
- Persistence: Cassandra, MySQL or PostgreSQL. Optionally Elasticsearch or OpenSearch for visibility queries ("all workflows of type X in state Y").
Workers report results (the completed task plus new commands) back through the frontend to the owning history shard, which closes the loop.
What a shard stores. For each workflow execution, a shard keeps:
- An append-only event history: WorkflowExecutionStarted, ActivityTaskScheduled, ActivityTaskCompleted, TimerStarted, TimerFired, SignalReceived, and so on.
- Mutable state: a compact summary of the execution right now (pending activities, pending timers, the next event ID), so the server never has to replay history itself.
- Task tables:
- transfer tasks, meaning "push this to matching";
- timer tasks, meaning "fire at time T";
- replication tasks, for multi-cluster setups.
The transactional-outbox trick. When a workflow task completes with commands such as "schedule activity charge" or "start a 48-hour timer", the history service writes, in one database transaction:
- the new events;
- the updated mutable state, with a condition on the expected next event ID, which is optimistic concurrency;
- the transfer and timer tasks.
A shard-local queue processor then reads the task tables and dispatches the tasks: it pushes activity tasks to matching and fires due timers. This is exactly the outbox pattern. The state change and the "send this" intent commit atomically, so a crash between them cannot lose or duplicate an activity at the scheduling level. The activity's execution is still at-least-once, which is why idempotency remains your job.
Timers. Timer tasks are stored keyed by fire time. Each shard's timer processor scans a time window ahead and loads due timers into memory. When one fires, it appends a TimerFired event and schedules a workflow task. One million sleeping workflows therefore cost a million rows, not a million threads. Timer precision is typically within a second or so, which is fine for business deadlines.
Matching and sync match. When an activity task arrives and a worker is already long-polling, matching hands it over directly. This is sync match: no database write, and latency of a few milliseconds. If no poller is waiting, the task is persisted to the task queue's backlog. Task queues are partitioned (for example, 4 partitions by default in Temporal), with forwarding between partitions so that a poller on an empty partition can still get work.
Sticky execution. Replaying a long history for every workflow task would be expensive. Workers therefore cache the workflow's in-memory state, and the server sends the next task for that execution to a sticky queue owned by the same worker. Only the new events are sent. If that worker dies or doesn't respond within the sticky timeout (a few seconds), the task falls back to the normal queue, and another worker does a full replay. Replay is the slow path for recovery, not the fast path.
The per-workflow ceiling. Because one shard owns a workflow, and each workflow task is a serialised read-modify-write, a single workflow execution can sustain only tens of events per second. Temporal's guidance is to keep a single workflow under a few events per second sustained. Cluster throughput scales by running more workflows, not by making one workflow hot. The design rule follows: one workflow per business entity (order, trip, user onboarding). Never use one global workflow as a coordinator for everything; that is a hot key.
Scaling numbers, back of the envelope. Assume 5,000 workflow starts per second, about 10 events per workflow, and about 3 database writes per event batch. Persistence must then sustain roughly 50,000 event appends per second, typically batched into about 15,000–25,000 transactions per second. That load is spread over thousands of shards. It sits in Cassandra territory, or a well-sharded MySQL/PostgreSQL fleet. Uber has publicly described running Cadence at the scale of hundreds of millions of workflows a day, so the architecture is proven. It is also not free: you operate a stateful distributed database cluster plus four services. That is why managed offerings (Temporal Cloud) and lighter-weight alternatives exist:
- Restate: an embedded log.
- DBOS: workflow state in your own PostgreSQL, checkpointed in the same transaction as your step writes when possible.
How the alternatives map.
- Step Functions hides all of this behind a managed service. You pay per state transition on Standard, and by duration and memory on Express.
- DBOS collapses history, mutable state and tasks into PostgreSQL tables, and recovers by re-running workflows from the last checkpointed step.
- Restate puts a durable log in front of your service handlers and journals each step's result.
The core idea is identical across all of them: record progress durably before moving on, so recovery is a deterministic replay or resume, never a guess.
Deep Dive: Determinism, versioning and replay safetyShow
Replay-based engines (Temporal, Cadence, Azure Durable Functions) recover a workflow by re-running its code from the start against the recorded history. On replay:
- every
await activity(...)returns the recorded result instead of calling the activity again; - every timer that already fired resolves immediately.
For this to work, the code must issue the same sequence of commands on every run. The engine checks this. If, at event 7, the history says "ActivityTaskScheduled: reserve" but the code now asks to schedule "charge", it raises a non-determinism error. The workflow then blocks, or the task fails repeatedly, until a fixed version is deployed.
What breaks determinism.
| Source | Why it breaks | Safe replacement |
|---|---|---|
Date.now(), new Date() | Different value on replay | SDK workflow.now(); the TypeScript SDK patches Date inside the sandbox |
Math.random(), UUIDs | Different value on replay | SDK deterministic random / uuid4() seeded from history |
| Network, DB, file I/O | Result changes and isn't recorded | Move the call into an activity |
Threads, native goroutines, setTimeout | Scheduling order varies | SDK coroutines, workflow.Go, durable sleep |
| Iterating an unordered map | Iteration order may change | Sort keys first |
| Reading env vars or global config | Value changes between deploys | Pass it in as input or read it via an activity |
| Code changes to an in-flight path | New command sequence | Versioning (below) |
The SDKs help:
- The TypeScript SDK runs workflow code in a deterministic V8 sandbox. It replaces
DateandMath.randomand forbids Node built-ins. - The Go SDK ships a static analyser (
workflowcheck). - Java and Python provide workflow-safe APIs and sandboxes. Python's sandbox restricts many standard-library modules.
Versioning with patches. Suppose you need to add a fraud check between authorisation and reservation, while thousands of orders are mid-flight. You write:
if (patched('add-fraud-check')) {
await fraudCheck(order.id);
}Here is how the patch behaves:
- New executions take the new branch. The SDK records a marker event in their history.
- Old executions replaying past this point find no marker where the new code expects one, so
patchedreturns false and they skip the check. - Old executions that haven't reached this point yet take the new branch when they get there.
The patch lifecycle has three steps:
- Deploy with
patched(). - Once no pre-patch executions remain open (check with a visibility query), replace it with
deprecatePatch('add-fraud-check')and keep only the new branch. The marker is still tolerated. - Once no executions with the marker remain, delete the call entirely.
Go and Java express the same idea with GetVersion(changeID, minSupported, max), which returns an integer version recorded in history.
Worker versioning (build IDs). Patching gets messy when a change is large. The alternative is to pin each execution to the code version it started on. Workers report a build ID, and the server routes an execution's tasks only to compatible workers. You run old and new worker fleets side by side until the old executions finish, then retire the old fleet. This works well for short and medium workflows. For entity workflows that live for months, combine it with continue-as-new, so that each run can move to the newest version at a clean boundary.
The replayer as a safety net. Download real histories from production, sampled per workflow type, and run them through the SDK's Replayer against the new code in CI. Any non-determinism fails the build before deploy. This is the single most effective practice for teams running replay engines. It turns a production incident into a red test.
Why non-replay engines care too. Step Functions and DBOS do not replay workflow code in the same way:
- Step Functions interprets a state machine definition.
- DBOS re-executes the workflow function but skips completed steps by their recorded outputs. That still requires the steps to be called in a consistent order.
Every durable engine still faces the same question: what happens to executions already in flight when the definition changes? Step Functions pins each execution to the definition version it started with, and supports versions and aliases for gradual rollout. Database state machines face it as "a new state was added, but old rows don't know about it". You handle that with a data migration, or a mapping from old states to new ones. The general principle: running processes are data, and changing their code is a schema migration.
Deep Dive: Saga semantics, lost isolation and countermeasuresShow
A saga trades atomic isolation for availability. Garcia-Molina and Salem ("Sagas", SIGMOD 1987) define a saga as a sequence of local transactions T1…Tn with compensations C1…Cn−1. The system guarantees that one of two sequences executes:
- T1, T2, …, Tn (success), or
- T1, …, Tj, Cj, …, C1 for some j (backward recovery).
Each Ti is atomic and isolated locally. The saga as a whole is not isolated. Other transactions see intermediate states, which leads to three classic anomalies.
- Lost update. Saga A writes a value, saga B overwrites it, then A's compensation "restores" the old value and wipes out B's change. Example: A reserves a seat, B changes the seat's price, and A's compensation restores a snapshot that includes the old price.
- Dirty read. Saga B reads a value written by saga A that A later compensates. Example: B sees "credit limit reserved = 500", approves a second order on that basis, and then A's refund changes the picture.
- Fuzzy (non-repeatable) read. A step reads a value twice within the saga and gets different results, because another saga committed in between.
Chris Richardson's Microservices Patterns (2018) lists practical countermeasures, borrowed from the multi-database transaction literature:
- Semantic lock. A compensatable step sets an application-level flag: status
PENDING, or a*_PENDINGstate. Other sagas treat a flagged record carefully. They might fail, wait, or proceed with awareness. The flag is cleared by the pivot (commit) or by the compensation. The hold rows in Dealing with Contention are semantic locks with a TTL. - Commutative updates. Design operations so that their order doesn't matter:
debit(50)/credit(50)instead ofset balance = 450. A compensation becomes the inverse delta, never a snapshot restore, which eliminates the lost-update anomaly. - Pessimistic view. Reorder steps to reduce business risk from dirty reads. For example, increase available credit only in the last step (retriable), and decrease it early (compensatable). A dirty read then sees less credit than reality, never more.
- Reread value. Before overwriting, reread the record and check that it hasn't changed. This is optimistic concurrency at the saga level. If it changed, abort and possibly restart.
- Version file. Record operations as they arrive, so that out-of-order ones can be reordered or cancelled. Example: a cancel arrives before the authorisation it cancels, so the record notes it and the later authorisation becomes a no-op.
- By value. Choose the concurrency mechanism by business risk. Run low-risk requests as sagas, and route high-risk ones (a $1M transfer) through a distributed transaction or a stricter path.
Backward vs forward recovery.
- Backward recovery runs compensations in reverse order. It's natural before the pivot.
- Forward recovery retries the remaining steps until they succeed. It's mandatory after the pivot, because the pivot can't be undone.
Garcia-Molina and Salem also discussed save-points, which let a saga back up partially and then roll forward from there. They also covered sagas where compensation is impossible: there, forward recovery with retries is the only option, and the system must ensure that the remaining steps eventually succeed. In practice, most production sagas are backward until the pivot, forward after it. That is Richardson's compensatable → pivot → retriable ordering.
What compensation cannot fix. Externally visible side effects (an email sent, an SMS delivered, a webhook a partner already acted on) can only be followed by a corrective message. That is why notifications belong after the pivot, or behind a short delay. And because compensations run during failures, they must be the most reliable code in the system:
- idempotent;
- retried with a generous budget;
- monitored;
- backed by a manual-resolution queue when they finally fail.
A saga is not finished when the happy path works. It is finished when every abort path has been run in a test, and the anomalies above are either impossible or acceptable to the business.
Choosing between a saga and a distributed transaction. Two-phase commit across services gives isolation, but it blocks while the coordinator is down, and it needs every participant to support XA-style prepare. Most HTTP APIs (Stripe, carriers, email providers) cannot participate. Sagas work with any API that offers an idempotent action and some form of undo. Within one database, or one Spanner-style system, use a real transaction. Across independently owned services and third parties, a saga with the countermeasures above is usually the only option. Distributed Transactions covers 2PC, 3PC and their failure modes in depth.
Key Takeaways#
- Any flow with more than one side effect across services will fail halfway at some point. Design the failure paths first.
- Persist progress after every step: in a status row, a saga log, or a workflow history. Recovery must be resume, not guess.
- Make every step idempotent with a stable key. Retries are guaranteed in every model, so you can't avoid them, only make them harmless.
- Order steps as compensatable, then pivot, then retriable. Compensate backward before the pivot and retry forward after it. Compensations are semantic, not rollbacks.
- Choose the lightest model that works:
- single-server code for short flows;
- a DB state machine for a few flows;
- choreography for loose reactions;
- Step Functions or durable execution for many complex, long-lived workflows.
- Durable execution writes workflows as plain code, with durable timers, signals and retries. In return you accept determinism rules, versioning discipline and small state.
- Correlate external events by business key, deduplicate them, and handle early, late and duplicate arrivals explicitly.
- Sagas give up isolation. Counter that with semantic locks, commutative updates and careful ordering, and monitor stuck and failed compensations.