Temporal
Temporal is a durable execution platform. You write a multi-step business process (charge a card, reserve inventory, wait for the warehouse, send a confirmation, refund if anything fails) as ordinary code in Go, Java, Python, TypeScript or .NET, and Temporal guarantees that the code runs to completion, even if the machines running it crash halfway through, the network drops, or a step has to wait three days for a human.
What that means in practice:
- Durable state for free: Every step a workflow takes is recorded in an event history on the Temporal server. If the worker running it dies, another worker picks it up and continues from exactly where it stopped, with all its local variables intact.
- Retries and timeouts built in: Calls to unreliable things (APIs, databases, other services) are wrapped as activities with declarative retry policies and timeouts. You stop writing retry loops, state tables and cron-driven reconcilers by hand.
- Long-running by design: A workflow can sleep for 30 days, wait for an external signal or run for years. Waiting costs nothing; no thread is held.
- Code, not configuration: Workflows are written in a general-purpose language, with loops, conditionals and tests, instead of a JSON or YAML state machine.
Temporal began as a fork of Cadence, an orchestration engine built at Uber, and it's now one of the standard answers when an interview problem involves a long-running, multi-step process that must not get stuck or half-finish: payments and order fulfillment, onboarding flows, infrastructure provisioning, ML pipelines, and any "design a workflow engine" or "design a job orchestrator" question. Along the way we'll compare it with the two other tools that come up for the same problems, Airflow and AWS Step Functions.
The Problem It Solves
Consider placing an order. The steps are simple: charge the customer, reserve inventory, create a shipment, email a receipt. The hard part is everything between the steps:
- The payment service times out. Did the charge go through or not?
- The process crashes after charging but before reserving inventory. Who notices, and who finishes the job?
- Inventory is out of stock after the charge succeeded. Someone has to refund.
- The warehouse confirms shipment hours later through a webhook. Where does the process wait in the meantime?
Without an orchestrator, teams build the same machinery over and over: an orders table with a status column, a queue between each step, a cron job that scans for orders stuck in CHARGED for more than ten minutes, retry counters, and compensation logic scattered across services. It works, but the business process is spread across a dozen places and every edge case is a new bug.
Temporal's bet is that you should write the process in one place, as straight-line code, and let the platform make it durable.
Core Concepts
Workflow: A function that defines the process. It decides what happens and in what order: calling activities, waiting on timers, reacting to signals. Workflow code must be deterministic (more on why below). Each running instance is a workflow execution, identified by a workflow ID that you choose, such as order-81723.
Activity: A function that does the actual work with side effects: calling an API, writing to a database, sending an email. Activities can fail, time out and be retried. They're where all non-determinism lives.
Worker: A process you run in your own infrastructure that hosts your workflow and activity code. Workers poll Temporal for tasks, run them and report results. The Temporal server never runs your code; it only tells workers what to do next.
Task queue: A named queue that workers poll. Routing work to a task queue is how you send activities to the right fleet, for example GPU activities to gpu-workers and everything else to default.
Signals, queries and updates: Ways to interact with a running workflow. A signal sends it an asynchronous message ("the warehouse confirmed shipment"). A query reads its state without changing it ("what step is this order on?"). An update is a synchronous request that can change state and return a result.
Namespace: An isolation unit for workflows, roughly a tenant, with its own retention and limits.
Here's the order process in Python:
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
@workflow.defn
class OrderWorkflow:
def __init__(self):
self.shipped = False
@workflow.signal
def shipment_confirmed(self):
self.shipped = True
@workflow.run
async def run(self, order):
retry = RetryPolicy(initial_interval=timedelta(seconds=1),
backoff_coefficient=2.0, maximum_attempts=10)
opts = dict(start_to_close_timeout=timedelta(seconds=30), retry_policy=retry)
charge_id = await workflow.execute_activity(charge_card, order, **opts)
try:
await workflow.execute_activity(reserve_inventory, order, **opts)
except Exception:
await workflow.execute_activity(refund, charge_id, **opts) # compensate
raise
await workflow.execute_activity(create_shipment, order, **opts)
# Wait up to 7 days for the warehouse webhook to send a signal.
await workflow.wait_condition(lambda: self.shipped, timeout=timedelta(days=7))
await workflow.execute_activity(send_receipt, order, **opts)
It reads like a normal function. Yet if the worker crashes after charge_card returns, a new worker resumes at reserve_inventory without charging again. The seven-day wait doesn't hold a thread or a connection. And every retry, timeout and result is recorded and visible in Temporal's UI.
Architecture
A Temporal deployment has two halves: the Temporal Service (which you run yourself or buy as Temporal Cloud) and your workers.
The service is made of four roles, each horizontally scalable:
- Frontend: the gRPC API gateway. Clients start workflows and send signals through it; workers poll it for tasks. It handles rate limiting and routing.
- History service: the heart of the system. It owns the event history and mutable state of every workflow execution, decides what tasks to create next, and manages durable timers.
- Matching service: manages task queues. It hands tasks to workers that are long-polling for them.
- Internal worker service: runs Temporal's own background workflows (archival, replication, cleanup).
Behind them sits a persistence store: Cassandra, PostgreSQL or MySQL, holding event histories, workflow state, timers and task queue backlogs. An optional visibility store, usually Elasticsearch or OpenSearch, indexes workflow metadata so you can search ("all failed OrderWorkflow executions in the last hour").
Notice the direction of the arrows. Workers pull work by long-polling; the server never calls into your code. That means workers need only outbound network access, scale independently of the server, and can be deployed, restarted or rolled back freely, because a workflow's state lives on the server, not in the worker.
How Durable Execution Works
But what is actually happening under the hood? The trick behind Temporal is event sourcing plus replay.
Every workflow execution has an event history: an append-only log of everything that happened to it. For the order workflow, it starts like this:
1 WorkflowExecutionStarted {order: 81723}
2 WorkflowTaskScheduled
3 WorkflowTaskStarted
4 WorkflowTaskCompleted
5 ActivityTaskScheduled charge_card
6 ActivityTaskStarted
7 ActivityTaskCompleted {charge_id: "ch_9x2"}
8 WorkflowTaskScheduled
...
The worker and server cooperate through two kinds of tasks:
- A workflow task asks a worker to advance a workflow. The worker runs the workflow code until it blocks on something (an activity result, a timer, a signal) and replies with commands: "schedule activity
reserve_inventory." The History service records the commands as events and creates the matching activity task. - An activity task asks a worker to run one activity. The worker runs it and reports success or failure, which the History service appends to the history. That new event triggers another workflow task, and the cycle repeats.
Now suppose the worker crashes in the middle. Another worker picks up the next workflow task, but it doesn't have the workflow's in-memory state. So it replays: it runs the workflow function from the start, and every time the code calls execute_activity, the SDK checks the history. If the history already has a result for that call, the SDK returns the recorded result immediately instead of running the activity again. When the code reaches a point the history doesn't cover yet, it's caught up, and execution continues for real.
In normal operation, workers avoid full replays by keeping recently used workflows cached in memory (sticky execution). Replay is the recovery path, and it's what makes the guarantees hold.
Why Workflows Must Be Deterministic
Replay only works if running the same workflow code over the same history makes the same decisions in the same order. So workflow code must not do anything whose result could differ between the original run and a replay:
- No direct network calls, database access or file I/O. Put those in activities.
- No
datetime.now(), random numbers or UUID generation directly. Use the SDK'sworkflow.now(),workflow.random()andworkflow.uuid4(), which are recorded or derived from the history. - No native threads,
sleepor iteration over unordered maps. Use the SDK's timers and concurrency primitives.
The SDKs help: the Python SDK runs workflows in a sandbox that blocks many non-deterministic calls, and replays that diverge from the history fail loudly with a non-determinism error rather than doing the wrong thing silently.
Durable Timers
await workflow.sleep(timedelta(days=30)) doesn't hold anything open. The worker returns a "start timer" command, the History service writes a timer into its persistent timer queue, and the workflow is evicted from memory. Thirty days later, the timer fires, a TimerFired event is appended, and some worker (possibly one that didn't exist when the timer started) resumes the workflow. Millions of workflows can be waiting at the same time at almost no cost.
In an interview, this is the clean answer to "how do we send a reminder 3 days after signup?" or "how do we cancel an unpaid reservation after 15 minutes?" Each entity gets a workflow with a durable timer, and there's no polling job scanning a table. It's worth contrasting with the alternatives: a cron that scans
WHERE expires_at < now(), or a delayed-message queue.
Reliability Semantics
The guarantees are precise, and interviewers like to check that you know them:
- Workflow code runs effectively once. Its decisions are recorded, and replay never repeats a side effect, because workflows don't have side effects of their own.
- Activities run at least once. If a worker finishes an activity's work but crashes before reporting the result, Temporal can't tell, and it retries the activity. So activities must be idempotent. Pass an idempotency key (the workflow ID plus a step name) to the payment provider, or make writes upserts.
- Workflow IDs are unique among running executions. Starting a second
order-81723while the first is running is rejected by default. This makes "start a workflow" naturally idempotent, which is very useful when the trigger is an at-least-once message.
Activity timeouts are where most configuration effort goes:
| Timeout | Meaning | Typical use |
|---|---|---|
| Start-to-close | Max time for one attempt | Always set it; detects hung attempts |
| Schedule-to-close | Max total time across all retries | Bound how long to keep trying |
| Schedule-to-start | Max time waiting in the task queue | Detect that no workers are available |
| Heartbeat | Max time between heartbeats from a long activity | Detect a dead worker in minutes instead of waiting for a long start-to-close timeout |
Long activities, like a 2-hour video transcode, should heartbeat regularly and can include progress details, so a retry can resume from the last checkpoint instead of starting over.
Sagas and Compensation
Distributed processes that span services can't use a single database transaction. The standard pattern is a saga: a sequence of local steps, each with a compensating action that undoes it, run in reverse when a later step fails.
Without an orchestrator, sagas are painful: you need to persist which steps succeeded and make sure compensations run even if the coordinator crashes. In Temporal, a saga is a try/except block plus a list of compensations. Because the workflow is durable, the compensations are guaranteed to run, and because they're activities, they get retries too.
compensations = []
try:
await workflow.execute_activity(book_flight, trip, **opts)
compensations.append(cancel_flight)
await workflow.execute_activity(book_hotel, trip, **opts)
compensations.append(cancel_hotel)
await workflow.execute_activity(charge_card, trip, **opts)
except Exception:
for undo in reversed(compensations):
await workflow.execute_activity(undo, trip, **opts)
raise
Compensations are business operations (a refund, a cancellation email), not rollbacks. Other systems may have seen the intermediate state, so design compensations to be safe and idempotent too.
Scaling Temporal
Temporal scales horizontally by sharding workflow executions. Each workflow ID hashes to one of a fixed number of history shards (set when the cluster is created, often in the hundreds or thousands), and each shard is owned by exactly one History host at a time. All updates to a shard's workflows go through its owner, which keeps per-workflow processing serialized and consistent. Adding History hosts spreads shards more thinly. The shard count can't be changed later, so it's chosen with plenty of headroom.
Task queues scale similarly: a busy task queue is split into partitions spread across Matching hosts.
The important limits are per workflow, not per cluster:
- One workflow execution is a serialized unit. Its events are applied one at a time by one shard owner, so a single workflow can sustain only a modest rate of signals and activities, on the order of tens of events per second. Design so that throughput comes from many workflows, not one hot one. One workflow per order, not one workflow for all orders.
- Event histories have a size limit, around 50,000 events or 50 MB. A workflow that loops forever (a subscription that bills monthly for years, an entity workflow processing a stream of signals) calls continue-as-new periodically, which atomically closes the current run and starts a fresh one with the same workflow ID and a carried-over state, resetting the history.
- Payloads are stored in history. Activity inputs and outputs are persisted, so pass references (an S3 key) rather than large blobs.
Workers scale like any stateless fleet. You watch the task queue backlog (schedule-to-start latency) and add workers when it grows. Because workers pull, adding them requires no registration.
A useful back-of-the-envelope: at 1,000 new orders per second with 10 activities each, each activity generates roughly 3 events and each workflow task about 3 more. That's on the order of 60,000 history events written per second, which is a serious database load. It's why large self-hosted Temporal clusters typically run on Cassandra, and why many teams buy Temporal Cloud instead.
Versioning Workflows
Because running workflows replay against their history, changing workflow code is delicate. If you insert a new activity call before an existing one, every in-flight workflow fails to replay with a non-determinism error: the history says "activity A was scheduled" where the new code says "schedule activity B."
The options:
- Patching (
workflow.patched("add-fraud-check")in Python,GetVersionin Go): branch in code so old executions follow the old path and new ones the new path. Remove the old branch once old executions have finished. - Worker versioning: run old and new worker builds side by side, pin each execution to the build it started on, and drain the old fleet as its workflows complete.
- Short workflows make versioning easy: if every execution finishes in minutes, you can just let old ones drain.
Activity code has no such constraint; you can change an activity's implementation freely as long as its inputs and outputs stay compatible.
Temporal vs Airflow vs Step Functions
All three are called "workflow engines," but they're built for different jobs.
Apache Airflow schedules batch data pipelines. You define a DAG of tasks in Python ("extract at 2 AM, then transform, then load"), and a scheduler runs each task when its upstream tasks have finished, using an executor (Celery workers, Kubernetes pods). State lives in a metadata database. It's excellent for time-based ETL with backfills, but it isn't built for millions of concurrent, low-latency, event-driven executions, and tasks pass only small amounts of data to each other. See /system-design/etl-pipeline.
AWS Step Functions is a managed state machine service. You define states and transitions in JSON (Amazon States Language) or a visual editor, and each state typically calls a Lambda function or another AWS service. Standard workflows can run for up to a year with exactly-once step execution and are billed per state transition. Express workflows run for up to five minutes, are cheaper at high volume and have weaker delivery guarantees. No servers to run, and deep AWS integration, but complex logic in JSON gets unwieldy and you're tied to AWS.
| Temporal | AWS Step Functions | Apache Airflow | |
|---|---|---|---|
| Primary use | Durable business processes, microservice orchestration | Orchestrating AWS services and Lambdas | Scheduled batch and data pipelines |
| Definition | Code (Go, Java, Python, TS, .NET) | JSON state machine (ASL) | Python DAGs |
| Trigger | API, events, schedules | API, events, schedules | Mostly schedules, also sensors and API |
| Execution scale | Millions of concurrent executions | High (Express for very high volume) | Thousands of task runs, not per-request |
| Long waits | Durable timers, signals, years | Up to 1 year (Standard) | Sensors, not designed for long waits per entity |
| Latency per step | Tens of milliseconds | Tens to hundreds of milliseconds | Seconds or more (scheduler loop) |
| Operations | Self-host (Cassandra/SQL) or Temporal Cloud | Fully managed | Self-host or managed (MWAA, Astronomer) |
| Lock-in | Open source | AWS only | Open source |
The short version: Airflow for "run this pipeline every night," Step Functions for "glue these AWS services together without servers," Temporal for "this business process must finish correctly, no matter what, and it's complicated."
Temporal in an Interview
When to Use It
- Multi-step processes across services where partial failure is unacceptable: payments, order fulfillment, account onboarding, KYC checks, refunds. See /system-design/payment-system.
- Long waits and human steps: approvals, waiting for a webhook, reminders days later, trial expirations, reservation holds.
- "Design a workflow engine" or "design a job scheduler": Temporal's architecture (event-sourced histories, sharded by workflow ID, task queues with pulling workers, durable timer queues) is a strong blueprint to describe. See /system-design/workflow-engine and /system-design/job-scheduler.
- Replacing hand-rolled state machines: whenever your design has a status column, a retry counter and a cron that finds stuck rows, a durable workflow is the cleaner alternative.
Knowing Its Limitations
- Not for high-frequency, single-entity throughput. One workflow handles tens of events per second, not thousands. Don't model a hot counter or a stock order book as one workflow.
- Not a data pipeline engine. Moving terabytes between stages belongs in Spark, Flink or Airflow-orchestrated jobs; Temporal should pass references, not data.
- Added latency per step. Each activity is a round trip through the server and a database write, on the order of tens of milliseconds. Fine for business processes, wrong for a request that needs single-digit milliseconds.
- Determinism and versioning discipline. Developers have to learn the rules, and changing long-running workflows requires patching or worker versioning.
- Operational weight. Self-hosting means running a sharded, database-backed cluster plus Elasticsearch. Smaller teams usually use Temporal Cloud or Step Functions.
Questions You Might Get
- "What happens if the worker crashes mid-workflow?" The workflow task or activity task times out, another worker picks it up, replays the event history to rebuild state, skips completed activities using their recorded results, and continues. An activity that was running is retried.
- "How do you avoid charging a customer twice?" Activities are at-least-once, so the charge activity passes an idempotency key (workflow ID + step) to the payment provider. The workflow logic itself never re-executes a completed step.
- "How would you build Temporal?" Store each workflow's history in a sharded database keyed by workflow ID, assign each shard to one owner for serialized updates, put work in task queues that workers long-poll, persist timers in a timer queue per shard, and rebuild workflow state by replay.
- "Why not just use a message queue between services?" You can (that's choreography), but then the process state, retries, timeouts and compensations are scattered across services. An orchestrator keeps the whole process in one place where it can be read, tested and observed.
Summary
Temporal makes ordinary code durable. Workflows decide what happens and must be deterministic; activities do the side-effecting work and are retried at least once, so they must be idempotent. The server records every step in an event history, sharded by workflow ID, and workers pull tasks and rebuild state by replay after any failure. That gives you retries, timeouts, durable timers, signals and sagas without building them yourself.
In an interview, reach for Temporal (or a design modeled on it) whenever a process spans several services, can fail partway, or has to wait. Know the trade-offs: per-workflow throughput is modest, each step adds tens of milliseconds, and changing long-running code needs versioning. And know when the problem is really a nightly batch pipeline (Airflow) or simple AWS glue (Step Functions) instead.