Skip to content

Temporal and Workflow Engines

Advanced 47 min read Part 15 of 18

Durable execution with Temporal: workflows vs activities, event history and replay, determinism, retries, timers and signals, and Step Functions and Airflow.

Summary#

A workflow engine runs multi-step business processes so that they survive crashes, retries and long waits without you hand-building state machines. Temporal is the best-known example of durable execution. You write the process as ordinary code (charge the card, reserve inventory, wait for delivery, send an email). Temporal records every step's result in a durable event history, and if a worker dies, it reconstructs the function's state by replaying that history on another machine.

The price is a programming discipline and an extra system to run:

  • Workflow code must be deterministic.
  • Side effects must live in retryable, idempotent activities.
  • The cluster (or Temporal Cloud) becomes part of your critical path.

Why It Exists#

Imagine the backend of an online shop. When a customer places an order, five things must happen:

  1. Charge the card.
  2. Reserve the inventory.
  3. Request a shipment.
  4. Wait until the package is delivered.
  5. Send a review request.

If failures didn't exist, the code would be ten lines:

// The code we wish we could write
async function processOrder(order: Order) {
  await chargeCustomer(order);        // Stripe
  await reserveInventory(order);      // inventory DB
  await requestShipment(order);       // carrier API
  while (!(await isDelivered(order))) {
    await sleep(days(5));             // a process sleeping for days?
  }
  await sendReviewEmail(order);
}

Every line of it is a problem in production:

  • Crashes mid-way. Stripe charges the customer, and the server crashes before it records that fact. A replacement server has no idea whether the charge happened. If it runs the step again, the customer is charged twice. If it skips the step, the order ships unpaid.
  • Long waits. Nobody keeps a process alive for five days per order. With a million orders in flight, that's a million idle processes, and every deploy or restart kills them all.
  • External events. Delivery doesn't happen on a schedule. The carrier calls a webhook whenever the package arrives. Something has to route that webhook to this order's half-finished process and resume it.
  • Retries and timeouts. The carrier API times out. Should you retry? How many times, with what backoff? What if the step runs twice?
  • Visibility. Support asks "where is order 8812 stuck?", and the answer is spread across logs on five services.

The traditional fix is to break the function apart:

  • persist a status column (CHARGED, RESERVED, SHIPPED...);
  • put "do the next step" messages on a queue;
  • run a cron job that scans for orders stuck too long;
  • write a webhook handler that looks up the order and advances its state;
  • add retry tables, dead-letter queues and an outbox.

This works, and Multi-step Processes walks through those event-driven and orchestration options. But you end up with the business logic smeared across handlers, cron jobs and state columns. You've built a bespoke, under-tested workflow engine without meaning to. The tell-tale sign is a growing state machine plus scheduler plus retry framework that nobody wants to touch.

Durable execution engines turn that infrastructure into a product. The lineage matters for understanding the design:

  • AWS Simple Workflow Service (SWF, 2012) and Microsoft's Durable Task Framework (the engine behind Azure Durable Functions) pioneered code-as-workflow with replay.
  • Engineers with that background built Cadence at Uber, open-sourced around 2017, to run Uber's many long-running business processes.
  • In 2019, Cadence's creators, Maxim Fateev and Samar Abbas, founded Temporal Technologies and forked Cadence into Temporal. It's MIT-licensed, with SDKs for Go, Java, TypeScript, Python, .NET, PHP and Ruby, and a managed Temporal Cloud.

Alongside this code-first lineage there are other engines. Declarative state machines include AWS Step Functions (2016), which uses JSON or YAML state definitions, and Netflix Conductor, open-sourced in 2016 for microservice orchestration. Batch DAG schedulers include Apache Airflow (created at Airbnb in 2014, and an Apache top-level project since 2019), Dagster, Prefect and Argo Workflows. They solve overlapping but different problems, which we'll compare below.

How It Works#

The concepts in Temporal (Workflows, Activities, replay, determinism) can feel strange at first. The quickest way to see why each one exists is to build a tiny durable-execution framework ourselves, one failure at a time.

Step 1: Survive a crash by recording results and replaying#

Several lines of processOrder touch the outside world: Stripe, the inventory database, the carrier. If one of those calls succeeds and the server dies, we need a durable record that it happened.

So we route every external call through our framework. When a call finishes, the framework appends an event to a durable, per-order history:

ChargeCustomerCompleted   { result: "pay_123" }
ReserveInventoryCompleted { result: "res_456" }

The server crashes before requesting shipment. Another server picks the order up and runs processOrder again from the top. This time, each time the function asks the framework to do an external call, the framework first checks the history:

  • chargeCustomer: a completed event exists, so it returns pay_123 without calling Stripe.
  • reserveInventory: a completed event exists, so it returns res_456.
  • requestShipment: there's no event, so it actually calls the carrier and records the result.

The function's local variables, loop counters and branch decisions are all rebuilt by re-executing the code against recorded results. That's replay. The original process is gone, but its execution survives, because the history is durable.

This splits our code naturally into two kinds:

  • Orchestration logic, the function body that decides what to do next. It's replayed many times and must never itself touch the outside world. Temporal calls this a Workflow.
  • External operations that do real work (calling Stripe, writing a database, sending an email). They run once per attempt, and their results are recorded. Temporal calls these Activities.

There's one gap replay can't close. If Stripe charged the card and the worker crashed before the framework recorded the completion, the history says nothing, and the activity will be attempted again. The engine guarantees the activity's result is recorded at most once in the history. It can't guarantee the side effect happened at most once. So activities must be idempotent. Pass Stripe an idempotency key derived from the workflow id and step, such as order-8812-charge, and make database writes upserts. See Idempotency.

Step 2: Make replay predictable with determinism#

Replay only works if the re-executed code makes the same decisions it made the first time. Suppose we add same-day shipping for orders placed before 5 PM:

if (new Date().getHours() < 17) await requestSameDayPickup(order);
else await requestNextDayPickup(order);

The order arrives at 4:59 PM. The workflow charges the card, reserves the stock, sees it's before 5 PM, and requests a same-day pickup. The history now reads Charge, Reserve, SameDayPickup. Then the worker crashes. At 5:03 PM, a new worker replays the code. Charge and Reserve return their recorded results, but the clock now reads 17:03, so the code takes the next-day branch. The history says the next step was a same-day pickup, while the code asks for a next-day pickup. The replay has diverged, and the framework can't safely continue.

The fix is to route every source of nondeterminism through the framework too. The workflow asks the framework for "now". On first execution, the framework records the value. On replay, it returns the recorded time, not the new machine's clock. The same applies to random numbers, UUIDs and anything else that could differ between runs. Temporal's SDKs provide workflow-safe versions: workflow.Now() and workflow.SideEffect in Go, and in the TypeScript SDK, a sandbox where Date and Math.random are replaced with deterministic versions. The rule for workflow code is: no direct I/O, no wall clock, no randomness, no threads, no global mutable state. Anything that reads the world goes in an activity.

Step 3: Let the workflow wait with durable timers#

Now consider sleep(5 days). Keeping a process alive for five days per order is absurd. So when the workflow calls sleep, the framework:

  1. records TimerStarted { fireAt: "May 15 10:00" } in the history and in a deadline-ordered durable timer index;
  2. stops running the workflow entirely, freeing the worker for other orders.

A background timer processor scans the index for due deadlines. It doesn't touch the millions of waiting workflows, only the next-due entries. Five days later it finds ours, appends TimerFired, and schedules the workflow to run. Replay reaches sleep, sees both TimerStarted and TimerFired in the history, and continues.

If the timer processor's host crashes, another instance recovers the pending timers from storage. An outage can delay a timer, but it can't lose it. That's how a workflow can "sleep" for five days, five months or a year at the cost of a database row, not a process.

Step 4: Let the outside world wake the workflow with signals#

Delivery doesn't follow a timer. It happens whenever the carrier's webhook fires. So waitUntilDelivered simply blocks the workflow (no process stays alive) until an event is appended to its history. When the webhook arrives, our API calls the framework: "append PackageDelivered to workflow order-8812." The new event triggers another run. Replay reaches waitUntilDelivered, finds the event, and proceeds to send the review email.

Temporal calls this external input a Signal: an asynchronous message to a running workflow, durably recorded in its history.

We've now rebuilt Temporal's whole programming model from four failures. The order process can be written almost exactly as the naive version:

// Temporal TypeScript SDK style (workflow code: deterministic)
import { proxyActivities, sleep, condition, defineSignal, setHandler } from "@temporalio/workflow";
import type * as acts from "./activities";
 
const { chargeCustomer, reserveInventory, requestShipment, sendReviewEmail, refund } =
  proxyActivities<typeof acts>({
    startToCloseTimeout: "30 seconds",
    retry: { initialInterval: "1s", backoffCoefficient: 2, maximumInterval: "5m",
             nonRetryableErrorTypes: ["CardDeclined"] },
  });
 
export const delivered = defineSignal("delivered");
 
export async function processOrder(order: Order): Promise<void> {
  let isDelivered = false;
  setHandler(delivered, () => { isDelivered = true; });
 
  const paymentId = await chargeCustomer(order, `order-${order.id}-charge`); // idempotency key
  try {
    await reserveInventory(order);
  } catch (e) {
    await refund(paymentId);              // compensation (saga)
    throw e;
  }
  await requestShipment(order);
  const arrived = await condition(() => isDelivered, "30 days");  // durable wait + timeout
  if (!arrived) return;                    // escalate to support in a real system
  await sleep("2 days");                   // durable timer
  await sendReviewEmail(order);
}

The Temporal programming model in detail#

Workflows

A Workflow Definition is the code. A Workflow Execution is one running instance, identified by a Workflow ID that you choose, such as order-8812, plus a system-generated Run ID. Temporal guarantees that only one open execution per Workflow ID exists in a namespace. That's a built-in uniqueness lock: starting order-8812 twice returns "already started" rather than creating a duplicate. Workflow ID reuse policies decide whether a closed ID may be reused, for example "allow only if the previous run failed".

Executions can run for seconds or years. Each Workflow Task (one step of running workflow code) has a short timeout, 10 s by default. An optional Execution Timeout bounds the whole thing, and a Run Timeout bounds a single run.

Workflow code produces commands: schedule activity, start timer, start child workflow, complete, and so on. It reacts to events: activity completed, timer fired, signal received. Inside a workflow you can use loops, conditionals, local variables, and lightweight coroutines (workflow.Go and channels in Go, Promise.all in TypeScript) to fan out in parallel. Everything is replayable because every interaction with the world goes through the SDK.

Activities

An Activity is a normal function that may do anything: call APIs, query databases, run ML inference, transcode video. It runs on a worker, and Temporal records the outcome.

Activities have four timeouts, and confusing them is a common mistake:

TimeoutMeasuresTypical use
Schedule-To-StartTime waiting in the task queue before a worker picks it upDetect missing or overloaded worker fleets (alert rather than retry, since a retry would wait in the same queue)
Start-To-CloseMaximum time for one attemptAlways set it: it's how Temporal detects a crashed worker mid-attempt
Schedule-To-CloseTotal time across all attempts including retriesOverall deadline ("give up charging after 1 hour")
HeartbeatMaximum gap between heartbeats from a long-running attemptLong activities (a 2-hour transcode) report progress; a missed heartbeat means the worker died, so retry sooner than Start-To-Close

Heartbeats can carry progress details. A retried attempt can read the last heartbeat payload, for example "processed 7,400 of 10,000 files", and resume instead of starting over.

The retry policy is declarative, with an initial interval, a backoff coefficient, a maximum interval, maximum attempts, and non-retryable error types. Temporal's default policy retries activities indefinitely, starting at 1 s with a 2× backoff, capped at 100× the initial interval. Infinite retries suit transient failures, but you must mark business errors (card declined, invalid address) as non-retryable so the workflow can handle them. The retries happen inside Temporal, at no cost to the workflow code, and they're visible in the history. These are the same principles as Resilience Patterns, turned into configuration.

Two activity variants are worth knowing:

  • Asynchronous completion. An activity can return a task token and complete later, when an external system calls back. This suits human approvals and third-party callbacks without polling.
  • Local activities run inside the workflow worker's process, without a separate task-queue round trip, and are recorded via a marker event. They're useful for very short calls (under a second or so) where latency matters. The trade-off is weaker isolation and coarser retry semantics.

During retries, the history records only the final outcome of an activity, plus its attempt count. It doesn't add an event per failed attempt, which keeps histories small even with aggressive retry policies.

Workers and Task Queues

Workers are your processes, running your workflow and activity code. Temporal's servers never execute your code. Workers long-poll a named Task Queue, such as orders or payments, for tasks. There are two kinds of task:

  • A Workflow Task: "run this workflow's code forward from its latest events and tell me the next commands."
  • An Activity Task: "execute this activity with these inputs."

You can route activity types to dedicated fleets by giving them separate task queues: GPU transcoders on gpu-transcode, PCI-scoped payment calls on payments, cheap email senders on email. Each fleet scales independently. Because workers poll outbound to Temporal, they can run in private networks with no inbound ports.

Signals, Queries and Updates

These are the three ways the outside world talks to a running workflow:

  • Signal: asynchronous, fire-and-forget input that's durably recorded, such as "delivered", "cancel order" or "driver accepted". Signal-With-Start starts the workflow if it isn't running and then signals it. That gives an idempotent entry point for webhooks.
  • Query: a synchronous, read-only look at workflow state, such as "what step is order 8812 on?". It's served by a worker running a query handler against the current state, and it's not recorded in the history.
  • Update: a synchronous, tracked request that may change state and returns a result. An example is "apply this coupon and return the new total". It can have a validator that rejects the update before anything is written. Updates are recorded, so they replay correctly.

Composition: child workflows, Continue-As-New and schedules

  • Child workflows let a parent start other workflows, such as one per video segment or one per line item. Each has its own history, which limits history size and gives separate retry and timeout scopes. The parent can wait for children or abandon them (parent close policy).
  • Continue-As-New atomically completes the current run and starts a new run of the same Workflow ID with fresh inputs and an empty history. Long-lived "entity" workflows use it, such as a subscription that bills monthly forever, or a loop polling every hour. Otherwise their history would grow without bound (see the limits below).
  • Schedules replace cron. They're durable, pausable, backfillable and overlap-aware ("skip if the previous run is still going"), and each scheduled action starts a workflow. They're far more robust than cron on one machine.

Sagas and compensation

Distributed workflows can't take a database transaction across Stripe, inventory and the carrier. The standard answer is the saga: a sequence of local steps, each with a compensating action that semantically undoes it (a refund for a charge, a release for a reservation). Run compensations in reverse order when a later step fails. In Temporal, a saga is just a try/catch with a list of compensations. The engine guarantees the compensation code itself runs to completion through crashes, which is the hard part of hand-rolled sagas.

Compensations aren't rollbacks. Other systems may have observed the intermediate state: the customer saw a pending charge, or a warehouse picked the stock. So compensations must themselves be idempotent and retryable, and some actions, such as sending an email, can't be compensated at all. Put those last. The theory of sagas versus two-phase commit is in Distributed Transactions.

Versioning: changing code while workflows are running

A workflow started last month replays with today's code. If you insert a new activity call before an existing one, the replayed commands no longer match the history. The result is a non-determinism error, and the workflow is stuck until the code is fixed. Temporal offers three tools:

  • Patching: patched("add-fraud-check") in TypeScript and Python, or workflow.GetVersion in Go and Java. It branches on whether this execution started before or after the change. Old executions take the old path when they replay, and new ones take the new path. Once no old executions remain, you remove the old branch.
  • Worker Versioning: pin executions to the worker build that started them, and run old and new worker builds side by side until the old executions drain.
  • Replay tests: download production histories and replay them against the new code in CI. A non-determinism error in CI is cheap, while one in production can stall thousands of workflows.

Temporal under the hood#

In most interviews you won't need Temporal's internals. But they're a superb case study in building a scalable, durable system, and they let you design "a workflow engine" yourself when the interviewer takes Temporal off the table.

The four services each scale as independent fleets:

  • The Frontend is a stateless entry point. It authenticates, rate-limits per namespace, and routes each request to the History or Matching host that owns it.
  • The History service is the heart. It owns every workflow execution's durable state, applies each state transition (activity completed, signal received, timer fired, commands from a workflow task), and runs the transfer and timer queues.
  • The Matching service manages task queues. It hands tasks to waiting pollers, or persists them if none are waiting.
  • Workers are your processes. Temporal also runs an internal worker for its own system workflows.

History shards

A cluster may track tens of millions of open executions, so the History service is sharded. Each Workflow ID hashes to one of a fixed number of history shards. The number is chosen at cluster creation (512, 4,096 or more for big clusters) and can't be changed later, so size it for the future. Each History host owns a subset of shards, using a membership ring (Temporal uses the Ringpop library for membership). When hosts join or fail, shard ownership moves. A range id stored with each shard fences the old owner's writes, so two hosts can never both commit transitions for the same shard. That's the same fencing-token idea as in ZooKeeper and etcd, implemented with conditional writes in the database.

Mutable state, event history and the transfer queue

For each execution, the History service persists two things:

  • The event history: an append-only list of events such as WorkflowExecutionStarted, ActivityTaskScheduled, ActivityTaskCompleted, TimerStarted and WorkflowExecutionSignaled. It's the source of truth used for replay.
  • Mutable state: a compact, materialised snapshot of "what is happening right now", such as pending activities with their attempt counts, outstanding timers, child workflows and signal counters. It could be recomputed from the history, but it's kept so the service can answer "is this activity still pending?" without scanning thousands of events.

When an activity completes, the History host does one atomic write in its shard. It appends the new events, updates the mutable state, and inserts an internal transfer task, "dispatch a Workflow Task for order-8812 to queue orders". A background transfer queue processor reads committed transfer tasks and pushes them to Matching. This is the transactional outbox pattern: the state change and the intent to notify are committed together, so a crash between them can't lose the next step. Duplicates are handled because dispatch is idempotent, keyed on the task's id.

Timers use the same mechanism. A timer task with a fire time is stored in the shard's timer queue, ordered by deadline. The timer processor loads the next-due window into memory and fires each due timer by writing TimerFired and a transfer task atomically. A million sleeping workflows cost a million small rows and zero compute.

Matching, sync match and task queue partitions

When History pushes a task and a worker is already long-polling that queue, Matching hands the task over directly. This sync match involves no database write, which is the common case for a healthy, well-provisioned fleet. If no poller is waiting, Matching persists the task and delivers it when a worker polls. A growing persisted backlog is the clearest sign that a worker fleet is under-provisioned, and Schedule-To-Start latency is the metric to alert on.

A busy queue is split into partitions (a small number by default, configurable upwards), spread across Matching hosts, so one hot queue isn't limited by one machine.

Sticky execution and the workflow cache

Replaying a 5,000-event history for every workflow task would be expensive. So workers keep recently used executions in memory: the reconstructed state, paused at its last await. After a worker processes a workflow task, Temporal routes the next task for that execution to a sticky queue specific to that worker. The worker resumes from memory and processes only the new events.

If the worker crashes or evicts the execution from its cache, the sticky task times out after a short sticky schedule-to-start timeout, a few seconds by default. Temporal then falls back to the normal queue, and any worker replays the full history. History gives correctness, and the cache gives performance. Cache size, set as a number of cached executions per worker, is one of the main worker tuning knobs.

One workflow task, end to end

Each arrow that changes state is a durable write to the shard's database rows. A simple three-activity workflow touches the persistence layer roughly 10–20 times over its life. That's where Temporal's capacity planning centres (see the scaling Deep Dive).

How the cluster scales

The elegant property is that waiting is nearly free. A million orders awaiting delivery consume database rows, not workers. Worker compute scales with work that's ready to run. So a burst of delivery webhooks needs more email workers, not more Temporal servers.

Conversely, if the rate of state transitions (events per second) grows, adding workers won't help. You need more History and Matching capacity, and above all more database throughput, because every transition is a write. Teams therefore watch two different dials:

  • Worker-side: Schedule-To-Start latency, slot utilisation, and the cache hit rate.
  • Service-side: per-shard and persistence latency, and shard lock contention. The latter means one very hot workflow serialises all its updates through its shard.

For multi-region resilience, Temporal supports namespace replication to a standby cluster. Histories are replicated asynchronously, and you fail a namespace over when a region goes down. Recent events may be lost or need conflict resolution, the usual cost of asynchronous replication covered in Multi-Region Data.

Temporal vs AWS Step Functions vs Airflow (and the rest)#

Workflow engines fall into three families with genuinely different design centres.

1. Code-first durable execution: Temporal, Cadence, Azure Durable Functions, Restate, DBOS, Inngest. The workflow is a function in a general-purpose language, made durable by recording and replaying.

  • Strengths: arbitrary control flow (loops, conditionals, dynamic fan-out, sagas in try/catch); ordinary unit tests; IDE support; versioning through code; workflows lasting months; huge numbers of concurrent executions.
  • Costs: the determinism discipline, and running or buying the cluster.
  • Newer entrants vary the storage model:
    • DBOS (from a research group including Michael Stonebraker and Matei Zaharia) stores workflow state in your own PostgreSQL through a library, with no separate cluster.
    • Restate is a log-based runtime that sits in front of your services.
    • Inngest is event-driven and serverless-oriented.

2. Declarative state machines: AWS Step Functions, Netflix Conductor, Google Cloud Workflows. The workflow is a JSON or YAML definition: a graph of states (Task, Choice, Wait, Parallel, Map, Catch and Retry) whose tasks invoke Lambda functions, containers or AWS service APIs directly.

  • Strengths:
    • fully managed and serverless, with nothing to operate;
    • visual graphs of every execution;
    • native integrations with about 200 AWS services, so a workflow can call DynamoDB or SQS without writing glue code;
    • IAM-based security.
  • Limits:
    • Logic in a DSL becomes awkward for complex branching.
    • Payloads between states are capped at 256 KB, so you pass S3 pointers instead.
    • Standard workflows run up to 1 year with exactly-once state transitions, but they're billed per state transition (on the order of $25 per million) and capped at 25,000 history events.
    • Express workflows run up to 5 minutes, at high volume, billed per request and duration, with at-least-once semantics for asynchronous runs.
    • The definitions are AWS-specific.
  • Netflix Conductor offers a similar JSON-DSL model as open source. It was created at Netflix for microservice orchestration, and is now maintained by the community and Orkes.

3. Batch DAG schedulers: Apache Airflow, Dagster, Prefect, Argo Workflows. These are built for data pipelines: "every night at 02:00, extract from these sources, transform, load the warehouse, then train the model".

  • How Airflow works: a DAG of tasks is defined in Python. The scheduler triggers DAG runs on a schedule or by event. Executors (Celery, Kubernetes) run the tasks, with task-level retries, backfills over historical dates, sensors, and a rich UI over runs.
  • What it isn't for: high-volume, low-latency, per-entity workflows. A run per order, at thousands per second, with sub-second step latency, is not its domain. The scheduler loop adds seconds of latency per task. Passing data between tasks (XCom) is meant for small metadata. And DAG structure is mostly fixed at parse time, although dynamic task mapping helps.
  • The others: Dagster adds asset-centric modelling ("this table is produced by this computation"), Prefect emphasises dynamic Python flows, and Argo runs container DAGs natively on Kubernetes.
DimensionTemporalAWS Step FunctionsApache Airflow
DefinitionCode (Go, Java, TS, Python, .NET...)JSON/YAML state machine (Amazon States Language)Python DAG files
Design centrePer-entity business processes, long-running, high concurrencyServerless orchestration of AWS services and LambdasScheduled batch data pipelines
DurationSeconds to years (Continue-As-New for unbounded)Standard up to 1 year; Express up to 5 minMinutes to hours per run
VolumeMillions of open executions; thousands of starts/s with a scaled clusterStandard: moderate (cost per transition); Express: very highTens to thousands of DAG runs per day typical
Step latencyTens of ms per transitionTens to hundreds of ms per transitionSeconds per task (scheduler loop)
Control flowArbitrary code: loops, dynamic fan-out, sagasDSL: Choice, Parallel, Map, CatchStatic-ish DAG; branching operators; dynamic task mapping
External eventsSignals, Updates, async activity completionCallback task tokens (.waitForTaskToken)Sensors (polling), dataset triggers
OperationsSelf-host (Cassandra/SQL + services) or Temporal CloudFully managedSelf-host or managed (MWAA, Cloud Composer, Astronomer)
Lock-inOpen source (MIT); portableAWS onlyOpen source; portable
Pick whenComplex, long, critical processes in your servicesYou're all-in on AWS and flows are simple to moderateNightly ETL/ELT, ML training pipelines, backfills

Rules of thumb:

  • One independent background job (resize this image, send this email): use a plain queue and workers (Message Queues). An engine is overkill.
  • Event choreography. Services react to each other's events on Kafka, with no central coordinator, which is very loosely coupled. It works for simple flows owned by different teams, but end-to-end visibility and compensation become hard as the steps multiply. See Event-Driven Architecture.
  • Several dependent steps, waits, compensations, and a need to answer "where is it stuck": use an orchestrating workflow engine.
  • Data pipelines on a schedule: Airflow, Dagster or Prefect. Use stream processing for continuous event flows (Batch and Stream Processing).

Use cases#

Payments and money movement. A payment workflow might authorise a card, run fraud checks, capture funds, write the ledger, notify the merchant, and schedule a payout in T+2 days. Each step calls an external system with its own idempotency key. Retries with backoff handle processor outages. Compensations (void, refund) handle later failures. The durable timer handles the payout delay. Every execution's history doubles as an audit trail: which call was made, when, with what result. Reconciliation can be a scheduled workflow. See Design a Payment System.

User onboarding and KYC (know-your-customer). A new account goes through several stages:

  1. Create the account, send a verification email, and wait up to 7 days for the click (a signal with a timer as the timeout), sending reminders on days 1 and 3.
  2. Run identity verification through a third party, which calls back asynchronously, sometimes hours later.
  3. If the check is ambiguous, wait for a human reviewer's decision (an Update).
  4. Provision resources, and start the trial.
  5. Thirty days later, convert the trial or downgrade.

As hand-written code, this is a state machine with a cron job and five tables. As a workflow, it's one readable function.

Ride matching (Uber-style). For each ride request, a workflow:

  1. sends the offer to the best driver candidate;
  2. waits up to 10 seconds for an accept signal, using a durable timer;
  3. moves on to the next candidate on a decline or timeout;
  4. finishes when a driver accepts or the candidates run out, falling back to widening the search radius.

The workflow survives a matching-service crash without dropping requests, and each request's history shows exactly which drivers were tried. The cost is a new system to learn and operate, which is usually worth it when a dropped request means lost revenue. This is covered in Design a Ride-Hailing App (Uber).

Media processing DAGs (YouTube-style). An upload workflow splits a video into segments and fans out child workflows or activities: transcode each segment into several resolutions in parallel on a GPU task queue, then generate thumbnails and captions. It then joins the results, writes the manifests, and publishes. If a worker dies mid-DAG, only the unfinished segment activities are retried. The history shows which segments are done. Heartbeats let a 20-minute transcode report progress and resume. See Design a Video Streaming Platform (YouTube / Netflix).

Reservation expiry (flash sales and ticketing). When a customer reserves an item, a workflow starts a 10-minute durable timer. If the payment signal arrives first, it confirms the order. If the timer fires first, it releases the stock. This takes expiry logic out of the sale service and survives restarts. At very high volume, a TTL on a Redis key or a reserved_until column swept periodically may be cheaper. Interviewers will want you to compare the two. See Design a Flash Sale and E-commerce Checkout.

Other common uses:

  • Infrastructure provisioning: create a VPC, wait for it, create clusters, configure DNS, with rollback on failure. HashiCorp and others have used workflow engines for cloud operations.
  • Subscription billing: an entity workflow per subscription that bills monthly and uses Continue-As-New.
  • Order fulfilment across warehouses and carriers.
  • Human-in-the-loop approvals.
  • Data migrations at scale, one child workflow per tenant.
  • AI agents and LLM pipelines, where each tool call and model call is an activity that is retried, recorded and resumed after crashes. This is covered in AI Agents, Tool Use and Advanced RAG.

Limits#

Temporal is powerful, but it has real constraints that you should state in an interview:

  • History size limits. Temporal Cloud and the defaults cap a single execution's history at 51,200 events or 50 MB, with warnings around 10,240 events or 10 MB. A workflow that loops forever, or fans out to 100,000 activities in one execution, will hit them. Use child workflows to split work, and Continue-As-New to reset long-running loops.
  • Payload size. Inputs and results are stored in the history, with a default limit of about 2 MB per payload. Large data belongs in object storage, passed by reference. A 4 GB video never goes through Temporal, only its S3 key does.
  • Determinism is a real tax. Engineers must learn the rules and use SDK-safe APIs. Changing code safely requires patching or worker versioning, and replay tests. Non-determinism errors stall executions until fixed.
  • It's not a stream processor. Continuously aggregating 1 million events per second is Flink's or Kafka Streams' job, not Temporal's. One workflow per event at that rate is a costly misuse.
  • It's not a database or a queue for simple jobs. Don't model each row update as a workflow. Use a plain queue for independent tasks.
  • Activities still need idempotency. Temporal retries them, so external side effects may be attempted more than once.
  • Throughput per execution is limited. All of one workflow's events serialise through its shard. A single "global counter" workflow receiving 1,000 signals per second becomes a hotspot. Shard the work across many executions.
  • Latency. Each state transition takes tens of milliseconds, so a 10-step workflow adds about 100–500 ms of orchestration overhead. That's fine for business processes, but wrong for the synchronous path of a 50 ms API.
  • Operational weight. Self-hosting means running Frontend, History and Matching fleets plus Cassandra or SQL and a visibility store, all of which must be monitored and upgraded. Temporal Cloud removes this but adds cost and a dependency.
  • The interview caveat. If the question is "design a job scheduler" or "design a workflow engine", writing "use Temporal" solves the hard part in one box. Interviewers may not accept it, and you should be ready to design the internals described above.

When to Use It#

Use a durable workflow engine when you see these signals:

  • Several dependent steps that must all happen (or be compensated), across services or third parties: payments, orders, onboarding, provisioning.
  • Waiting is part of the process: for a human, a webhook, a timeout or a schedule. That might be 10 seconds for a driver, 7 days for an email click, or 30 days for a trial.
  • Partial failure would be expensive: double charges, lost orders, stuck provisioning, dropped ride requests.
  • You're already building the machinery: status columns plus a cron sweeper plus retry tables plus an outbox plus dead letters. You're writing a workflow engine; adopt one.
  • You need per-entity visibility: "show me exactly what happened to order 8812, and when".
  • High concurrency of mostly idle processes: millions of open subscriptions, shipments or trials that each act rarely.

Pick something else instead when:

  • It's a single independent async job: SQS, RabbitMQ or a job queue with retries.
  • It's scheduled batch data work: Airflow, Dagster, Prefect or Argo.
  • It's continuous high-volume event processing: Kafka with Flink or Kafka Streams.
  • You're all-in on AWS with simple-to-moderate flows and want zero operations: Step Functions.
  • The steps are owned by many teams with simple reactions: event choreography over Kafka, with a saga log for visibility.

When NOT to Use It#

  • On the synchronous request path of latency-critical APIs. Each transition costs tens of milliseconds. Use it to start or signal processes, not to serve a 20 ms read.
  • For simple fire-and-forget jobs. It adds determinism rules, a cluster and versioning concerns for no benefit. In a notification system, for example, the queue-and-retry machinery is the interesting design.
  • As a stream processor or message bus. One workflow per event at hundreds of thousands per second is costly and fragile.
  • To store application data. Workflow state is for orchestration. Business entities belong in your database.
  • When the team can't absorb the discipline. Engineers who don't understand replay will write non-deterministic workflows, such as calling Date.now() or the database directly. Budget for training, linting, replay tests and code review rules.
  • In an interview where the engine is the problem. If asked to design a job scheduler or workflow system, design the History, Matching and timer internals rather than pointing at Temporal.

How to Implement It#

  1. Model the process explicitly before writing any code. List the steps, external systems, waits, timeouts, human inputs, failure outcomes and compensations. Decide the Workflow ID (a business key like order-<id>) so that starts are naturally deduplicated.
  2. Split workflow and activity code. Workflows only orchestrate. Every I/O call (APIs, databases, files, clocks, random numbers) becomes an activity, or an SDK-safe call.
  3. Make every activity idempotent. Derive idempotency keys from the workflow id and step name, use upserts and conditional writes, and rely on downstream deduplication (Stripe idempotency keys, for example).
  4. Set timeouts and retry policies per activity. Always set Start-To-Close. Add Heartbeat for long activities, and Schedule-To-Close as an overall deadline. Mark business errors non-retryable. Cap backoff.
  5. Design external interaction. Use signals for events, Updates for synchronous changes with validation, queries for status pages, and Signal-With-Start for webhooks that may arrive first.
  6. Bound the history. Use child workflows for large fan-outs (more than about 1,000 activities), Continue-As-New for long loops, and pass references (S3 keys), not blobs.
  7. Separate task queues by resource and trust: GPU, payments (PCI-isolated), bulk email. Size each worker fleet using Schedule-To-Start latency and slot-utilisation metrics.
  8. Plan versioning from day one. Use patching or worker versioning, run replay tests in CI against sampled production histories, and lint for forbidden calls in workflow code.
  9. Choose hosting. Temporal Cloud, or self-host on Kubernetes with Cassandra (for large scale) or PostgreSQL or MySQL (smaller), plus Elasticsearch or SQL for advanced visibility. Pick the history shard count up front.
  10. Observe and operate.
    • Dashboards for workflow failure rates, activity retry counts, Schedule-To-Start latency, and persistence latency.
    • Search attributes (CustomerId, OrderStatus) so support can find executions.
    • Alerts on stuck workflows and on non-determinism errors.
    • Runbooks for resetting a workflow to an earlier event after a fixed bug.

Here's an activity with heartbeats and an idempotency key (TypeScript SDK style):

// Activity code: normal Node.js, may do I/O. Runs on a worker.
import { Context } from "@temporalio/activity";
 
export async function chargeCustomer(order: Order, idemKey: string): Promise<string> {
  const res = await stripe.paymentIntents.create(
    { amount: order.totalCents, currency: "usd", customer: order.customerId, confirm: true },
    { idempotencyKey: idemKey }            // retries return the same PaymentIntent
  );
  if (res.status === "requires_payment_method") {
    throw ApplicationFailure.nonRetryable("card declined", "CardDeclined");
  }
  return res.id;
}
 
export async function transcodeVideo(input: { s3Key: string; renditions: string[] }) {
  const ctx = Context.current();
  const start = (ctx.info.heartbeatDetails as number) ?? 0;   // resume after retry
  for (let i = start; i < input.renditions.length; i++) {
    await runFfmpeg(input.s3Key, input.renditions[i]);
    ctx.heartbeat(i + 1);                    // progress; missed heartbeat => retry elsewhere
  }
}
TechnologyFits when
Temporal (self-hosted)Complex, long-running, high-concurrency business processes; you can operate Cassandra or SQL plus the services
Temporal CloudSame model without operating the cluster; consumption pricing
CadenceExisting Uber-lineage deployments; Temporal's predecessor, still open source
AWS Step FunctionsAWS-native orchestration of Lambdas and AWS APIs; visual workflows; low ops
Azure Durable FunctionsCode-first durable orchestration on Azure Functions (C#, JS, Python)
Netflix Conductor / OrkesJSON-defined microservice orchestration with a UI; polyglot workers
Apache Airflow / Dagster / PrefectScheduled batch and ML pipelines, backfills, data assets
Argo WorkflowsContainer-native DAGs on Kubernetes (CI, ML, batch)
DBOS / Restate / InngestLighter-weight durable execution (library on Postgres, log-based runtime, event-driven serverless)
Queue + state table + sweeperOne or two steps, low complexity, or when adding a new system isn't justified

Trade-offs#

OptionProsConsPick when
Code-first engine (Temporal)Arbitrary logic in real code; durable timers, signals, sagas; per-execution history; huge concurrencyDeterminism discipline; versioning care; cluster or cloud dependency; history and payload limitsBusiness-critical multi-step processes with waits and compensations
Declarative engine (Step Functions)Fully managed; visual; native AWS integrations; IAMDSL awkward for complex logic; 256 KB payloads; per-transition cost; AWS lock-inAWS-centric, moderate-complexity flows
DAG scheduler (Airflow)Scheduling, backfills, data-ecosystem operators, UISeconds of per-task latency; not per-entity; static-ish DAGsBatch ETL and ML pipelines
Choreography (events)Loose coupling; no central engine; teams own their reactionsHard to see end-to-end state; compensation logic scattered; cyclic dependenciesSimple flows across team boundaries
DIY state machine (DB + queue + cron)No new technology; full controlYou rebuild retries, timers, outbox, visibility and recovery, and test them less well1-2 step processes; very constrained environments

Common Pitfalls#

  • Non-deterministic workflow code: Date.now(), Math.random(), direct HTTP or database calls, iterating over unordered maps, threads. Replay diverges and executions stall.
  • Non-idempotent activities. Retries double-charge or double-ship. Always pass idempotency keys.
  • No Start-To-Close timeout, or relying on Schedule-To-Close alone. A crashed worker's attempt isn't detected for a long time.
  • Infinite retries on business errors. Card declines retried forever. Mark them non-retryable and handle them in the workflow.
  • Unbounded history. Signal loops or huge fan-outs in one execution hit the 50K-event limit. Use child workflows and Continue-As-New.
  • Big payloads in the history: blobs, documents, full API responses. Store them in S3 and pass keys.
  • Deploying incompatible workflow changes without patching or worker versioning. Replay tests in CI catch this.
  • One hot workflow used as a global coordinator (all signals through one execution). Shard by entity.
  • Treating workers as the bottleneck when it's persistence. Rising transition latency needs History and database capacity, not more workers.
  • Using it for everything, turning simple queue jobs into workflows and adding latency and operations for nothing.

Real-World Examples#

  • Uber built Cadence to orchestrate long-running business processes across its services and open-sourced it. Cadence's creators, Maxim Fateev and Samar Abbas, then founded Temporal Technologies in 2019 and forked Cadence into Temporal. Temporal's core concepts (event history, replay, decision or workflow tasks, task lists or queues, history shards) come directly from Cadence.
  • AWS Simple Workflow Service (SWF), launched in 2012, introduced the decider and activity worker model to a wide audience. AWS Step Functions, launched in 2016, moved AWS customers to a declarative, serverless state-machine model.
  • Microsoft's Durable Task Framework powers Azure Durable Functions. It's a code-first orchestration model with replay and determinism rules very similar to Temporal's.
  • Netflix created and open-sourced Conductor (2016), a JSON-DSL orchestrator for its microservice workflows such as content ingestion and encoding pipelines. It's now maintained outside Netflix by the community and Orkes.
  • Airbnb created Apache Airflow (2014) to schedule and monitor data pipelines as Python DAGs. It became the most widely deployed batch orchestrator, with managed offerings on AWS (MWAA), Google Cloud (Composer) and Astronomer.
  • Typical scenario: e-commerce order processing. An order workflow charges the card (with an idempotency key), reserves stock, books a shipment, waits up to 30 days for a delivery signal, sends a review request two days later, and compensates by refunding and releasing stock on failure. Support looks up any order's execution history by Workflow ID.

Case studies that use this pattern#

In the Interview#

Deep Dive: Designing a durable workflow engine yourselfShow

When an interviewer says "you can't use Temporal; design it", here is the blueprint, derived from first principles.

Requirements. The engine must:

  • run millions of concurrent executions, most of them idle;
  • deliver thousands of state transitions per second;
  • guarantee that no step is lost, and that each step's result is recorded once;
  • provide timers from seconds to months, external signals, retries with backoff, and per-execution visibility;
  • tolerate any single machine failing.

Data model. Shard everything by workflow_id:

Every state transition is one atomic write within a shard. Each event (activity completed, signal received, timer fired) is processed by the shard's owner:

  1. Load the mutable state, from cache or the database.
  2. Validate the transition. Is this activity still pending? Is the attempt number current?
  3. Append the events at next_event_id.
  4. Update the mutable state.
  5. Insert any transfer or timer tasks.

All of this is done in one transaction (SQL), or in one batch inside one partition (a Cassandra LOGGED batch on the same partition key). The write is conditional on the shard's range_id, so a deposed owner's write fails. That conditional is the fencing token. Shard ownership is managed by a membership service or by leases in the database itself.

Dispatch through an outbox. Transfer tasks are read by an in-memory queue processor per shard, in task-id order, and pushed to the task queue service. The shard keeps an ack level: the highest task id below which everything has been dispatched. After a crash, the new owner re-reads from the ack level. Some tasks may be dispatched twice, so task delivery is at-least-once, and the receiving side deduplicates using (run_id, event_id, attempt). This is the Change Data Capture and transactional outbox idea applied internally.

Timers. Each shard's timer tasks are ordered by (fire_at, task_id). The processor reads the next window (say the next 5 minutes) into an in-memory min-heap. When a timer comes due, it executes a normal state transition: append TimerFired, and insert a transfer task. New timers due inside the current window are added to the heap directly.

A thundering herd is a real risk. If a million subscriptions all renew at midnight UTC, a million timers fire in the same second. Spread them with jitter at creation time ("renew between 00:00 and 02:00"), and rate-limit dispatch per namespace.

Task queues and workers. The queue service keeps per-queue partitions. A worker long-polls for a few tens of seconds. If a task is waiting or arrives during the poll, it's handed over (sync match). Otherwise, tasks are persisted to a backlog table. A task delivered to a worker is not "done" until the worker reports a result to the history service, which validates it against the mutable state.

If the worker dies, the Start-To-Close timeout, itself a timer task created when the activity started, fires a retry or a timeout transition. So no separate visibility-timeout mechanism is needed in the queue. The history service is the single authority on whether an attempt is still current.

Executing workflow code: replay or state machine? You have two options:

  1. Replay-based SDK (Temporal-style). Workers receive the history, re-run the workflow function, and send back commands. This gives a great developer experience, but requires the determinism discipline.
  2. Explicit state machine (Step Functions-style). The engine itself interprets a declarative definition, so it needs no SDK replay. It's simpler to build and to make safe, but less expressive.

In an interview, option 2 is quicker to explain. Mention option 1 as the developer-friendly evolution.

Capacity sketch. Suppose 5,000 workflow starts per second, each with 8 activities and 1 timer. Each activity causes roughly three transitions (scheduled, started or completed, and the next workflow task), plus workflow-task transitions. Call it about 30 transitions per workflow, or about 150,000 transitions per second. At roughly 2–4 database writes per transition, that's 300k–600k writes per second. That's firmly in Cassandra territory (tens of nodes), or a heavily sharded SQL fleet. It explains why large Temporal and Cadence deployments use Cassandra, and why history shard count (say 16,384) and persistence latency are the primary scaling levers. Worker CPU is usually the cheaper part.

Visibility. Listing and searching executions ("all failed payment workflows for customer X today") is a separate, eventually consistent index. Copy workflow-open and workflow-close records, plus search attributes, to Elasticsearch or a SQL table through the same outbox. Never query the sharded history store for lists.

Deep Dive: Replay, determinism and exactly-once, preciselyShow

How replay matches code to history. During replay, the SDK runs the workflow function and intercepts each command the code produces (schedule activity X, start timer, start child). It checks each command against the next corresponding event in the history: ActivityTaskScheduled with the same activity type, TimerStarted, and so on.

  • If they match, the SDK doesn't send the command again. It feeds the recorded result (ActivityTaskCompleted) back into the code when the code awaits it.
  • If the code produces a command the history doesn't contain at that position, or the history contains an event the code never produced, the SDK raises a non-determinism error. The workflow task fails and is retried, and the execution makes no progress until a worker with compatible code picks it up.

Only commands are compared, not arbitrary code. So you can freely change logging, local computation that doesn't affect commands, and activity implementations. What you can't change on a running execution is the sequence or type of commands it would produce.

Deterministic concurrency. Workflow code may run several branches concurrently: goroutines via workflow.Go, or Promise.all in TypeScript. The SDK runs these coroutines cooperatively on one thread, in a deterministic order: each runs until it blocks on an SDK future. So the interleaving is identical on every replay. That's why native threads, go statements, select over native channels and setTimeout are forbidden in workflow code. They introduce scheduling the SDK can't reproduce.

Side effects and markers. For a tiny nondeterministic computation (generate a UUID, read a feature flag), SideEffect runs the function once and records the result as a marker event. On replay, it returns the recorded value. Local activities use the same marker mechanism. Mutable side effects record a new marker only when the value changes. The guiding principle is that anything not derivable from history must become history.

Exactly-once, stated carefully. Temporal provides:

  • Exactly-once execution of workflow logic, in effect. The workflow's effects on its own state (commands accepted by the history service) occur once, even though the code may be executed many times through replay.
  • At-least-once execution of activities, with their results recorded at most once. An attempt that completes after a newer attempt was scheduled is rejected by the history service's attempt check, so only one completion is ever recorded.
  • Effectively-once external effects, only if each activity is idempotent on its target system.

This is the same layering as Flink's exactly-once state with idempotent or transactional sinks, and as Kafka's idempotent producers. Exactly-once is always "at-least-once delivery plus deduplication at the boundary". See Delivery Semantics.

Relation to event sourcing. The event history is an event-sourced log of one workflow's lifecycle, and the mutable state is its current projection. Replay is the event-sourcing rebuild, with one twist: the "fold" function is your workflow code, made deterministic by construction. Many lessons from Event Sourcing and CQRS transfer: keep events small, version them, snapshot (Continue-As-New) when logs grow long, and treat projections (visibility) as eventually consistent.

Versioning strategies, compared.

StrategyHowProsCons
Patching / GetVersionCode branches on a marker recorded when the execution first reached that pointFine-grained; no infra changesBranches accumulate; must remember to remove old paths
Worker Versioning (build ids)Executions pinned to the worker build that started them; new builds get new executionsClean code; no branchesMust run old workers until their executions drain (could be months for long workflows)
New workflow typeprocessOrderV2; old executions finish on V1Simplest mental modelDuplicated code; signals and queries must target the right type
Continue-As-New into new versionLong-lived entity workflows hop to new code at the next Continue-As-NewNatural for infinite loopsOnly at loop boundaries

Reset. When a bug causes a batch of workflows to fail, Temporal can reset an execution to an earlier workflow-task event. It truncates the history from that point into a new run, and the fixed code re-executes from there, while signals received after that point can be re-applied. This is a powerful operational tool, and also a reminder that activities executed after the reset point may run again, so idempotency matters here too.

Testing. SDKs ship a time-skipping test environment. A workflow that sleeps 30 days completes in milliseconds in a unit test, because the test server advances time when all workflows are blocked. Combine this with replay tests over real histories to catch both logic bugs and determinism regressions before deployment.

Deep Dive: Operating at scale: limits, failure modes and costShow

Choosing the history shard count. Shards are the unit of parallelism and ownership. Each shard's transitions are serialised by one owner, so a cluster's maximum transition rate is roughly shards × per-shard throughput. A shard can sustain on the order of hundreds to a few thousand transitions per second, depending on the persistence layer. Because the count is fixed at creation, operators pick large values (4,096 or 16,384) for clusters expected to grow. Too few shards cap throughput. Too many add per-shard overhead, such as memory for queue processors and ownership churn, on small clusters.

Hot executions. All transitions of one execution serialise through its shard and its mutable-state lock. A workflow receiving 500 signals per second, perhaps a "global inventory" workflow, becomes the bottleneck, and its history explodes towards the 50K-event limit within minutes. The design fix is to shard by entity, one workflow per SKU or per order, and to aggregate elsewhere (in a database or stream processor). Treat a single workflow like a single-threaded actor: great for per-entity orchestration, terrible as a global coordinator.

Fan-out at scale. Suppose you process 1 million files in a nightly migration. One workflow with a million activities would blow through the history limit. Use a tree of child workflows instead. A parent starts 1,000 children, each child processes 1,000 files, using Continue-As-New in batches of 100 if needed. Limit concurrency with a semaphore pattern inside the parent, so you don't flood downstream systems with 1 million simultaneous calls. The same structure gives per-batch retries and progress reporting.

Failure modes:

  • Persistence outage or latency spike. Every transition stalls. Workflows don't fail, they just pause: activities completing during the outage retry their completion report, and timers fire late. This is the engine's "fail safe" property. Plan the database for the cluster's peak transition rate plus headroom.
  • Worker fleet outage. Tasks back up in Matching, and Schedule-To-Start latency climbs. Activities with a Schedule-To-Start timeout fail fast, if you set one, so alert on the backlog. When workers return, they drain the backlog, so make sure downstream systems can absorb the burst. Rate-limit activities per task queue if needed.
  • Poison workflow. A bug, or a non-determinism error, makes a workflow task fail on every attempt. The execution retries the workflow task indefinitely without failing the workflow. Monitor workflow-task failure counts, fix the code, and roll forward or reset.
  • Retry storms against a dependency. Thousands of executions retrying a failing payment provider with the same backoff can keep it down. Cap the retry rate with a maximum interval, rate-limit per task queue, or add circuit-breaker logic in activities.
  • Timer stampedes. Synchronised schedules (all trials expiring at midnight) need jitter.
  • Region loss. With namespace replication, fail over to the standby cluster. Executions continue from the replicated history, minus any events not yet replicated. Activities in flight may be re-executed in the new region, which is idempotency again.

Latency budget, worked. A ride-matching workflow:

  1. Start the workflow (about 20 ms).
  2. Schedule "offer to driver 1" (a workflow task plus an activity dispatch, about 30–50 ms).
  3. The push notification is sent by the activity.
  4. Wait for the accept signal, with a 10 s timer.
  5. The signal arrives, and a workflow task runs (about 30 ms).
  6. Complete.

The orchestration overhead is about 100–150 ms against a 10 s human wait, so it's negligible. Contrast this with using a workflow to serve an API read of 20 ms, where the overhead is 5–10×. Durable execution belongs on the asynchronous edge of the system.

Cost comparison, rough. Take 10 million order workflows per month, each with about 15 state transitions in Step Functions terms. That's 150 million transitions. At about $25 per million Standard transitions, it costs roughly $3,750 per month, before Lambda costs. Express workflows would be cheaper per run, but they're limited to 5 minutes and can't wait for delivery. Temporal Cloud prices by actions (starts, signals, activities, timers), and self-hosting costs the database cluster plus the service fleet plus engineering time. At small scale, managed services win decisively. At very large scale, teams compare self-hosting cost against managed pricing, and the real cost is usually the engineering time to operate the database layer. Prices change, so treat these as orders of magnitude and verify the current pricing.

Observability checklist:

  • workflow start, complete and fail rates per type;
  • activity failure and retry rates per type;
  • Schedule-To-Start latency per task queue;
  • workflow task failures (non-determinism);
  • persistence latency and errors;
  • shard ownership changes;
  • history size distribution (alert near the limits);
  • the number of open executions per type, which catches leaks such as workflows waiting for signals that never come.

Pair these with business search attributes, so support can find stuck customers quickly. General practice is in Observability.

Key Takeaways#

  • Durable execution lets you write a multi-step, long-running process as ordinary code that survives crashes, because the engine records each step's result in an event history and rebuilds state by replaying it.
  • Workflows orchestrate and must be deterministic (no direct I/O, clock or randomness). Activities do the real work, are retried under policies and timeouts, and must be idempotent, because at-least-once execution is unavoidable.
  • Durable timers and signals make waiting free. A workflow can wait 10 seconds for a driver or 30 days for a trial to end while occupying a database row, not a process.
  • Temporal's server shards executions by workflow ID across history shards. It commits each transition atomically with outbox-style transfer and timer tasks, matches tasks to polling workers through task queues, and caches workflow state on workers (sticky execution).
  • Sagas with compensations, child workflows, Continue-As-New and versioning are the core patterns for correctness, history limits and safe code changes.
  • Choose by design centre:
    • Temporal for complex per-entity business processes;
    • Step Functions for AWS-native managed state machines with modest complexity;
    • Airflow, Dagster or Prefect for scheduled batch pipelines;
    • a plain queue for single jobs;
    • Kafka with Flink for streams.
  • Know the limits: about 50K events or 50 MB of history per execution, about 2 MB payloads, tens of milliseconds per transition, hot-execution serialisation, and the operational weight of the cluster. If the interview asks you to design a workflow engine, design these internals rather than naming Temporal.