Multi-Step Processes and Long-Running Jobs
This lesson is for software engineers facing system design questions where one user action sets off several steps across services: placing an order, onboarding a customer, exporting a large report. The hard part is not the happy path. It is what happens when step three fails after steps one and two already changed the world. By the end you will be able to design a process that either finishes or cleanly undoes itself, survives crashes and retries, and keeps the user informed while it runs.
The problem in one example
A customer clicks "Place order". Four things must happen:
Reserve the items in the inventory service.
Charge the card through the payment service (which calls an external provider).
Create a shipment in the fulfillment service.
Send a confirmation email.
Each service owns its own database. If the payment succeeds and the shipment call times out, you have taken money for an order nobody will ship. If the process crashes between steps, nothing remembers where it was. In an interview, the interviewer wants to hear you name these failure points and give each one a defined outcome.
Why not one big transaction?
The textbook answer to "all or nothing across databases" is a distributed transaction, usually two-phase commit: a coordinator asks every participant to prepare, then tells all of them to commit. Strong candidates explain why it is rarely used across services:
Locks are held across the network. Every participant keeps its rows locked from prepare until commit. One slow participant slows all of them.
The coordinator is a blocking point. If it fails after participants have prepared, they cannot safely commit or abort until it recovers.
External systems will not join. A card network or an email provider does not take part in your transaction.
So instead of preventing partial failure, you design for it.
Sagas: steps with compensations
A saga is a sequence of local transactions, each in one service, where every step has a compensating action that semantically undoes it:
Reserve inventory, compensated by releasing the reservation.
Charge the card, compensated by issuing a refund.
Create the shipment, compensated by cancelling it.
Send the email, which has no compensation, so it goes last.
If step three fails, the saga runs compensations for steps two and one in reverse order. What a saga gives up is isolation: while it runs, other requests can see its intermediate state (stock reserved, card charged, no shipment yet), and a compensation can itself fail and need retrying. In exchange, every run ends in a consistent, explainable state. Ordering matters: put steps that are hard to undo (sending email, calling a partner) as late as possible. Payments show the idea well: authorize the card early, which places a hold that can be voided at no cost, and capture the money only once the shipment exists, so the common failure needs a void instead of a refund.
There are two ways to coordinate a saga:
Orchestration. One component, the orchestrator, calls each service in turn and decides what to do on failure. The whole flow is readable in one place and easy to change. The orchestrator must store its own progress so a crash does not lose it.
Choreography. No central controller; each service listens for the previous step's event and publishes its own ("InventoryReserved" leads to payment, "PaymentCaptured" leads to shipment). It is loosely coupled, but the flow is spread across services, which makes it hard to see, change and debug once there are more than three or four steps.
A reasonable default in an interview: orchestration for business-critical flows with many steps, choreography for simple reactions such as "when an order ships, update the loyalty points".
Making steps safe to retry
Networks fail in the worst way: the request succeeded, but the response was lost. The caller cannot tell the difference, so it retries. Every step must therefore be idempotent: doing it twice has the same effect as doing it once. The standard tool is an idempotency key per step (for example order-8812:charge), stored with the result in the same local transaction as the side effect; a repeat returns the stored result. This is covered in Scaling Data.
Retries need limits. Use exponential backoff with jitter: wait about 1, 2, 4, 8 and 16 seconds, which is 31 seconds over five retries, with a random spread so thousands of clients do not retry in lockstep. After the last attempt, stop and escalate.
The outbox: never lose the event
A saga that starts from an event has the dual-write problem: the order service writes the order, then publishes "OrderPlaced", and a crash between the two leaves an order no step ever hears about. Publishing first has the opposite bug. The fix is the outbox: write the event to an outbox table in the same local transaction as the order, and let a relay publish it. The relay may publish twice after a crash, which the idempotent steps above already absorb. Queues and Event Streams in Depth covers the relay and change data capture.
Durable workflow engines
Writing an orchestrator by hand means building state storage, timers, retries and recovery yourself. Durable workflow engines provide this as infrastructure: you write the flow as ordinary code, and the engine records each step's result so that after a crash the workflow resumes from the last completed step instead of starting over. Timers ("cancel the hold if not paid in 30 minutes") survive restarts too. In an interview, it is fine to say "I would run this as a durable workflow" as long as you can explain what that buys you: persisted progress, retries with backoff, and timeouts. Know the one rule it imposes. Recovery works by replaying the workflow code against the recorded results, so the workflow body must be deterministic: every side effect, clock read or random value goes inside a recorded step, or a replay takes a different path from the original run. The same replay is why changing the code of a flow with runs in progress needs versioning.
Long-running jobs
Some steps take minutes, not milliseconds: rendering a video, generating a year-end report, importing a million-row spreadsheet. Never hold the user's HTTP request open for them.
Accept and return immediately. The API writes a job record with status
queuedand responds with a job id (HTTP 202 Accepted).Queue the work. Workers pull jobs from a queue, set status to
running, and record progress ("40 of 100 pages").Report status. The client polls
GET /jobs/{id}every few seconds, or the server pushes updates over a WebSocket or server-sent events.Detect stuck workers. A worker sends a heartbeat while it runs; if heartbeats stop past a timeout, the job is returned to the queue for another worker.
Park poison jobs. A job that fails on every attempt (a corrupt file) must not retry forever. After a set number of attempts, move it to a dead-letter queue, mark it
failed, and alert someone.
Worked example: order checkout
Prompt: "Design the backend for placing an order in an online store."
A weak answer: "The order service calls inventory, then payment, then shipping, then email. If anything fails we return an error." It never says what happens to the reservation and the charge when shipping fails, and it assumes the order service never crashes mid-flow.
A strong answer:
The API writes the order with status
pendingplus an outbox event, in one transaction, and returns the order id.An orchestrator, run as a durable workflow, drives the steps: reserve stock, authorize payment, create the shipment, capture payment, send the email. Each call carries an idempotency key derived from the order id.
Failures map to compensations: a shipping failure voids the authorization and releases the stock, then marks the order
cancelledand tells the customer.Transient failures retry with backoff; a payment still failing after the retries ends the saga with compensation, not an infinite loop.
The order page shows status from the order record, so the customer sees "Processing", "Confirmed" or "Cancelled, refunded".
Monitoring tracks orders stuck in
pendingbeyond five minutes and the dead-letter queue size.
The difference is not the number of boxes. It is that every failure point has a named outcome, which is what the deep dive and scalability dimension asks for (failure modes), and that each choice, from orchestration to authorize-then-capture, is justified (trade-offs).
Follow-ups to expect
"What if a compensation itself fails?" Compensations retry like any step; if they still fail, the case goes to a queue for a human, and the order shows a state that says so.
"Can the customer see an inconsistent state?" Briefly, yes. Say so, and show which state you display (pending) while the saga runs.
"How do you avoid double charging on retry?" The idempotency key on the charge call, which the payment provider also honors.
"Orchestration or choreography?" Pick one and justify it with the number of steps and who needs to change the flow.
What changes with seniority
Mid-level candidates should recognize that a multi-service flow can fail halfway and propose retries and compensation. Senior candidates design the full saga, idempotency and the outbox, and explain the visible intermediate states. Staff-level candidates also cover operability: how a stuck saga is found and repaired, how the flow changes without breaking in-flight runs, and which steps the business would rather fix manually than automate.
Mistakes that cost points
Assuming the happy path. Every arrow between services is a place the process can stop.
Writing to the database and the broker separately. Use an outbox.
Retrying without idempotency. Retries plus non-idempotent steps equal duplicate charges.
Irreversible steps first. Send the email last.
Synchronous long jobs. Return a job id and report progress.
Practice it
Spend fifteen minutes on a user onboarding flow: create the account, provision a workspace, charge the first month, send a welcome email. Write the saga, the compensation for each step and the failure you would alert on. Then practice it inside a full design: when a chat message is accepted, it must be stored and delivered to every member, even if a delivery worker crashes, in Design a Real-Time Chat System. For how retried requests interact with contended resources, read Dealing with Contention.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Design a URL ShortenerSystem Design · Medium
- Design a Rate Limiter ServiceSystem Design · Medium
- Design Live Score Alert FanoutSystem Design · Medium
- Design a Video Upload and Transcoding PipelineSystem Design · Medium
Read next
- Handling Large Files: Uploads, Processing and Delivery
Keep large files off your API servers with presigned and resumable multipart uploads, keep metadata and stored bytes consistent, process files after upload, and deliver them through a CDN with range requests.
7 min read
- Scaling Reads
Apply the read-scaling moves in order (fix queries, denormalize, add replicas, cache, precompute), check each against a read-rate estimate, and handle replication lag and hot keys.
8 min read
- Scaling Writes
Raise write capacity by writing less, splitting latest state from history, batching behind a durable log, sharding by the write key and splitting hot counters, and size bursts and backpressure with real arithmetic.
8 min read
- Real-Time Updates
Choose between polling, long polling, server-sent events and WebSockets, route each update to the server holding the recipient's connection, and handle ordering, reconnection, missed messages and presence.
7 min read
