All posts
System Design Mastermind · F11
  • System design
  • Interview prep
  • Idempotency
  • Distributed transactions

Idempotency, exactly-once and sagas

Foundations F11. What to say when the interviewer asks "the call timed out and the client retried: did you charge twice?" and "payment worked but the courier booking failed: now what?": why a timeout is an unknown, operations that are idempotent by design, idempotency keys done properly, idempotent consumers, what exactly-once really means, two-phase commit and why services avoid it, sagas with compensations, and how to order a saga's steps and keep it alive through crashes. Each idea is told as a story you'll remember, with a lab that compares 2PC and a saga on a hot item and counts the refunds and double charges.

23 Oct 2026 · 25 min read · interactive

Share

Start here

Every design that moves money, books a seat or calls another service eventually gets the same follow-up: "the call timed out, so the client retried. Did you just charge the customer twice?" And then the harder one: "the payment went through but the courier booking failed. Now what?"

This page covers eight ideas: why a timeout is an unknown and not a failure, operations that are idempotent by design, idempotency keys done properly, idempotent consumers, what "exactly-once" really means, two-phase commit and why services avoid it, sagas with compensations, and how to order a saga's steps and keep it running through crashes. The previous page (queues and event streams) covered delivery guarantees and the outbox; this one is about making the effects safe. Distributed consensus was on the coordination page; event sourcing and CQRS are left out on purpose.

The one story for this page

A Hyderabad wedding, booked from a phone

Priya's family is planning her wedding in Hyderabad, and her brother Arjun is booking everything from his phone over three weeks. Every idea on this page happens to him:

  • He sends the caterer's advance on UPI. The app spins, then says "pending". Did the money go? (a timeout is an unknown)
  • He tells the decorator "make it 400 chairs", not "add 50 more chairs", so saying it twice does no harm. (idempotent by design)
  • The caterer writes every advance against the family's booking number, so a second payment for the same booking is spotted at once. (idempotency keys)
  • At the reception, the return-gift counter ticks each guest's name off the list, so nobody walks away with two boxes. (idempotent consumers)
  • The pandit counts the 108 chants on his mala, one bead per chant. (exactly-once, and its boundary)
  • At the muhurtham, the pandit asks both families "ready?" and everyone freezes until he says "now". (two-phase commit)
  • The hall cancels after the caterer is booked, so Arjun cancels the caterer and loses the cancellation fee. (sagas and compensations)
  • His uncle's advice: book what's refundable first, pay the non-refundable advance last, and keep a notebook of what's done. (ordering steps, durable workflows)

The family and vendors are made up for teaching; they are not any real business's system.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

A timeout is an unknown, not a failure

A call that times out has three possible outcomes, not two: it didn't happen, it happened, or it's still happening. The caller can't tell which, so the only safe plan is a retry the server can recognise.

The story · remember it like this

The UPI payment that says "pending"

Arjun pays the caterer's ₹50,000 advance on UPI. The app spins for 30 seconds and shows "Transaction pending". His bank SMS hasn't come. The caterer hasn't seen anything.

He has three choices. Pay again: if the first one went through, the caterer gets ₹1,00,000. Assume it failed and tell the caterer so: if it went through, everyone is confused for a day. Or wait for the bank to tell him, which it will, because the system was built to give every payment a final answer.

What he must not do is treat "I didn't hear back" as "it didn't happen". The money might be sitting in the caterer's account already. The phone simply never got the reply.

What it really is

A remote call can end in three ways:

  • Success: you got a reply that says it worked.
  • Failure: you got a reply that says it didn't (a 4xx, a declined card). Safe to report; usually not worth retrying.
  • Unknown: a timeout, a dropped connection, a 502 from a proxy, a crash of your own process. The request may never have arrived, may have been done, or may still be running.

The unknown is not rare: it comes from every network blip, deploy, failover and GC pause, and at scale it happens many times a minute. Because the caller can't tell "not done" from "done but the reply was lost", it has two safe options:

  • Retry in a way the server recognises as a repeat (an idempotent operation or an idempotency key), so doing it twice has the effect of doing it once.
  • Ask: look up the outcome by a reference the caller chose before the first try (a status endpoint, a reconciliation job).

Both need an identifier that exists before the first attempt. A retry that looks like a brand-new request is the bug.

In a real system ✅ Seen · RBI; Stripe

India's payment rules are built around the unknown. The RBI's circular on failed transactions (September 2019, in force from October 15, 2019) sets deadlines for exactly this case: for a UPI transfer where the customer's account was debited but the beneficiary wasn't credited, the beneficiary bank must reverse it by T+1 (T is the day of the transaction), and pays the customer ₹100 for every day of delay after that. For a debit with no confirmation at the merchant, the deadline is T+5.

Stripe's API docs say the same for developers: "if a connection error occurs, you can safely repeat the request" only when the request carries an idempotency key. For API v1, Stripe saves the status code and body of the first request with a given key once execution begins, including 500 errors, and returns that saved response to retries.

Trade-offs
  • Retrying with a key: fast recovery and no duplicates; but the server must store keys and results, and every client must send them.
  • Not retrying, and reconciling later: simple for the caller, but the user waits for a final answer, and someone has to build the reconciliation job anyway.
Say it in the interview

A timeout from the payment provider is an unknown, not a failure. The order stays in PAYMENT_PENDING, we retry with the same idempotency key, and a reconciliation job settles anything still pending after a few minutes by asking the provider for the payment by our reference.

Trap

Treating a timeout as a failure: showing "payment failed" and letting the user pay again, or rolling back your own order while the charge went through. Name the third outcome out loud.

Idempotent by design: set, don't add

An operation is idempotent if doing it twice leaves the same state as doing it once; design writes as "set to", "create this ID" or "change if still version 7", and retries stop being dangerous.

The story · remember it like this

"Make it 400 chairs"

Arjun phones the decorator: "add 50 chairs". The line crackles; he isn't sure the decorator heard, so he calls again: "add 50 chairs". Now there are 100 extra chairs, and the bill says so.

His mother does it differently. She says "make it 400 chairs in total". Say it once or five times, there are 400 chairs.

And when two aunts both phone the decorator with changes, she adds one more rule: "change it to 400 only if your list still says 350." If an aunt already changed it, the decorator calls back instead of silently overwriting her.

What it really is

Idempotent means f(f(x)) = f(x): the second time changes nothing. It's about the state left behind; the reply may differ (the second DELETE can return 404).

Ways to get it without extra machinery:

  • Absolute instead of relative: "set balance_hold = 500" or "status = SHIPPED", not "add 500" or "next status".
  • Client-chosen IDs: the client creates order 8f3c…, and a unique constraint on that ID turns a repeated INSERT into a no-op (or a clear "already exists").
  • Conditional writes (optimistic concurrency): "update if version = 7" (HTTP If-Match with an ETag, a SQL WHERE version = 7, a DynamoDB condition expression). A repeat, or a write based on stale data, fails instead of applying twice.
  • Natural state machines: "move order 42 from PAID to SHIPPED" applies once; the repeat finds it already SHIPPED and does nothing.

HTTP defines GET, HEAD, OPTIONS, PUT and DELETE as idempotent and POST and PATCH as not (RFC 9110). That's a promise the server must keep, not something HTTP enforces: a PUT handler that appends a row isn't idempotent.

Some operations can't be made idempotent this way: "send an SMS", "charge ₹500", "call a partner API". Those need a key (next concept).

In a real system ✅ Seen · RFC 9110; AWS

RFC 9110 (June 2022) defines a method as idempotent if "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request", and says clients may retry such requests automatically. Its conditional request headers (If-Match, If-Unmodified-Since) give a 412 Precondition Failed when the resource has changed, which is how REST APIs prevent lost updates.

DynamoDB's TransactWriteItems lets each write carry a condition (for example "only if the seat is still free"); if any condition fails, "the entire transaction request was canceled" with a TransactionCanceledException.

Trade-offs
  • Absolute writes are naturally safe, but they need the client to know the full new value, and two clients can overwrite each other; add a version check where that matters.
  • Client-chosen IDs make creates idempotent with one unique index; the cost is that IDs come from clients, so they must be random enough (UUIDs) and validated.
Say it in the interview

Seat holds are a conditional write: UPDATE seats SET held_by = :order WHERE seat_id = :s AND held_by IS NULL. A retry from the same order finds held_by already set to itself and returns success; a different order gets a conflict.

Trap

Saying "PUT is idempotent, so we're safe" while the handler increments a counter or sends an email. Idempotency is a property you design into the handler, not something the verb gives you.

Idempotency keys, done properly

The client makes one unique key per intended action and sends it on every retry; the server stores the key, a fingerprint of the request and the result in the same transaction as the effect, and answers repeats from what it stored.

The story · remember it like this

The caterer's booking number

The caterer gives every family a booking number, PR-0412 for Priya's wedding, and writes every payment in a ledger against it, with the amount and what it was for.

When Arjun's UPI app says "pending" and he pays again, the caterer looks at the ledger: "PR-0412, advance, ₹50,000, already received at 3:10 pm." He refunds the second payment and tells Arjun he's covered.

Three rules make the ledger work. The number is given out once, when the booking is made, not each time Arjun pays. If Arjun's cousin quotes PR-0412 for a different amount, the caterer doesn't guess; he phones to ask. And the caterer keeps the ledger until well after the wedding, because a cheque that arrives late is still a duplicate.

What it really is

How it works:

  • The client generates the key (a UUID v4) once per intent, when the user starts the checkout, not per attempt and not per tap. It stores the key with the pending action, so a retry after an app restart reuses it.
  • It sends the key on every attempt, usually in an Idempotency-Key header.
  • The server, in one database transaction: inserts the key (unique), with a hash of the request and the owner (scope keys per customer); performs the effect; stores the response with the key.
  • A repeat with a finished key gets the saved response. A repeat with a different request body is an error (the client reused a key by mistake). A repeat while the first is still running gets a "try again shortly" (409) rather than a second execution.

The hard part is an effect outside your database, such as calling a card network. You can't put it in your transaction, so record progress in steps: save "started" with the key, call the provider with your key passed on (so the provider deduplicates too), then save the result. A retry resumes from the last recorded step. Something must also finish requests whose clients gave up: a background job that resumes stalled keys.

Keys are kept for a window, not forever: long enough to cover every retry and redelivery, then deleted.

In a real system ✅ Seen · Stripe; AWS

Stripe (checked October 2026): keys are up to 255 characters, V4 UUIDs suggested; for API v1, keys may be pruned once they are at least 24 hours old, after which a reused key starts a new request; the idempotency layer "compares incoming parameters to those of the original request and errors if they're not the same"; and a request that conflicts with one still executing isn't saved, so it can be retried.

AWS's Builders' Library article on idempotent APIs (January 2021) describes EC2's ClientToken: the SDK generates one if the caller doesn't and reuses it on retries; the token and the resource it creates must be recorded in one ACID operation; the same token with different parameters is a validation error; and EC2 keeps tokens for "the lifetime of the resource, plus an interval". DynamoDB's ClientRequestToken is valid for just 10 minutes after the first request completes.

Brandur Leach's 2017 write-up of Stripe-style keys in Postgres names the steps "atomic phases" with "recovery points" (started, ride_created, charge_created, finished), a locked_at column that makes a concurrent repeat get 409 Conflict, and a "completer" that pushes stalled requests to the end.

Trade-offs
  • A longer key window catches late retries but costs storage (keys × request rate × window); the lab shows the size. Size it to the longest retry or redelivery window you allow.
  • Storing the full response lets repeats get an identical answer; storing only "done" plus the resource ID is smaller, and AWS's advice is a semantically equivalent answer, not a byte-identical one.
Say it in the interview

The app generates an idempotency key when the user lands on the pay screen and keeps it until it sees a final answer. The payment service inserts the key with a request hash in the same transaction as the payment row, passes the key on to the card provider, and answers any repeat from the saved result. Keys are kept 7 days, longer than any retry we allow.

Trap

Generating the key per HTTP attempt (so every retry looks new), or checking "have I seen this key?" and then writing in a separate step, which lets two concurrent repeats both pass the check. Insert the key with a unique constraint, in the same transaction as the effect.

Idempotent consumers: deduplicate where the effect happens

A consumer that gets at-least-once delivery records each message's ID in the same transaction as its effect, so a redelivered message finds its ID already there and is skipped.

The story · remember it like this

The return-gift counter

At the reception, 1,200 guests each get a box of sweets on the way out. Cousin Kiran runs the counter with the guest list and a pen. Each guest gives their name, he hands over a box and ticks the name, in one movement.

Some guests come back: "I don't think I got mine." Kiran checks the tick, smiles, and says they did. A few uncles try twice on purpose. Same answer.

What would break it: if Kiran handed over the box, got distracted, and ticked later. Or if two counters shared one list but each kept their own ticks. The tick and the box have to happen together, at the same counter.

What it really is

Queues and logs deliver at least once (the previous page): after a consumer crash, a rebalance or a visibility timeout, the same message comes again. The consumer makes that harmless:

  • Give every message a stable ID set by the producer (an event ID, or the outbox row's ID), not by the broker.
  • In the consumer, in one transaction: insert the ID into a processed_messages table with a unique key, and apply the effect. If the insert hits the unique key, skip the message and acknowledge it.
  • Or make the effect itself idempotent (an upsert keyed by order_id, a conditional state change) so no extra table is needed.
  • If the effect is outside your database (an email, a partner API), pass the message ID on as that system's idempotency key; if it has none, you can only narrow the window, not close it.

Two details interviewers probe:

  • Check, then act is a race. Two consumers can both see "not processed" and both act. Use the unique constraint or a conditional write, not a read followed by a write.
  • Dedup windows. Brokers that deduplicate do it for a window (SQS FIFO: 5 minutes). Your table's window is your choice; keep IDs at least as long as messages can be redelivered or replayed.
In a real system ✅ Seen · AWS; Temporal

Amazon SQS FIFO queues drop messages sent with a deduplication ID already used in the last 5 minutes; after that, the same ID is accepted again (AWS docs).

Temporal's docs give the same advice for workflow steps (Activities): an Activity can finish its work and its Worker crash before reporting success, so it runs again; idempotency keys "are enforced by the service you are calling from your Activity, not by the Activity itself", and the Workflow Run ID plus the Activity ID makes a key that stays the same across retries but is unique across workflow runs.

The Debezium outbox post (February 2019) has consumers check each event's UUID against a table of processed messages, because "a few events may be processed a second time" after a restart.

Trade-offs
  • A processed-IDs table works for any effect in the same database, but grows with traffic; partition it by day and drop old days past the replay window.
  • Making the effect itself idempotent (upsert, conditional update) needs no table, but not every effect can be written that way.
Say it in the interview

The ledger consumer inserts event_id into processed_events and writes the ledger entry in one transaction. A redelivered event hits the primary key, and we acknowledge it without writing. We keep event IDs for 14 days, longer than our longest replay.

Trap

Deduplicating in a cache (Redis SETNX) and writing to the database separately: a crash between the two either loses the message or lets it through twice. The ID and the effect go in the same transaction.

What "exactly-once" really means

No system can deliver a message exactly once over an unreliable network; what systems offer is exactly-once processing inside one boundary, by retrying and deduplicating, and end to end you get it only if every effect outside that boundary is idempotent.

The story · remember it like this

108 beads on the pandit's mala

The pandit must chant a mantra exactly 108 times. He can't remember a count that long through a three-hour ceremony, so he uses a mala of 108 beads and moves one bead with each chant. If a guest interrupts him, he looks at his fingers and knows where he is.

The trick is that the chant and the bead move together. If he chanted and forgot to move the bead, he'd chant that one again: at least once. The mala makes his count exactly once.

But it only counts his chants. Each time he finishes a round, an assistant rings the temple bell for the families to throw rice. If the assistant isn't sure he rang it, he rings it again, and the mala can't help with that. The bell needs its own rule.

What it really is

Three different claims hide under "exactly-once":

  • Exactly-once delivery (each message arrives once): not achievable over a lossy network. A sender that never retries can lose messages; one that retries until acknowledged can duplicate them.
  • Exactly-once processing inside a system: the system retries and deduplicates, and commits its state and its input position together, so after a crash each input affects the system's state once. Kafka transactions (read from Kafka, write to Kafka, commit offsets, atomically), Flink checkpoints, and AWS Step Functions Standard workflows all offer this.
  • Exactly-once effect end to end: what the business needs (one charge, one email). You get it by at-least-once delivery plus idempotent effects at every boundary the data crosses.

So the precise answer is: "exactly-once" is at-least-once plus deduplication, and it holds only inside the boundary that does the deduplicating. Every external side effect needs its own idempotency.

This is the end-to-end argument (Saltzer, Reed and Clark, 1984): a lower layer can't fully guarantee what only the endpoints know how to check, so duplicate suppression belongs in the application.

In a real system ✅ Seen · Flink; AWS; paper

Flink's 2018 post on end-to-end exactly-once (Flink 1.4, December 2017) is explicit about the boundary: inside Flink, checkpoints mean "each incoming event affects the final results exactly once", but an external sink "must provide a means to commit or roll back writes that coordinate with Flink's checkpoints". Flink does this with a two-phase commit: a checkpoint is the pre-commit, and the sink commits once the checkpoint completes.

AWS Step Functions Standard workflows "follow an exactly-once model, where your tasks and states are never run more than once, unless you have specified Retry behavior"; asynchronous Express workflows are at-least-once, so "an execution could potentially run more than once".

Saltzer, Reed and Clark (ACM TOCS, November 1984) put it in one line: duplicate suppression "must be accomplished by the application itself with knowledge of how to detect its own duplicates."

Trade-offs
  • Using a system's exactly-once mode (Kafka transactions, Flink 2PC sinks) removes duplicates inside it at the cost of latency (results appear only after a commit or checkpoint) and throughput.
  • At-least-once plus idempotent effects works across any mix of systems and is cheaper; it's the default to propose.
Say it in the interview

Exactly-once delivery isn't possible; I aim for exactly-once effect. Kafka transactions cover our Kafka-to-Kafka steps. The two effects outside Kafka, the ledger write and the email, are idempotent: the ledger by event ID, the email by an idempotency key at the provider.

Trap

Saying "we use Kafka with exactly-once, so there are no duplicates" when the consumer charges a card. The interviewer's next question is what happens when it crashes after the charge and before the commit.

Two-phase commit, and why services avoid it

2PC makes several databases commit or abort together: a coordinator asks everyone to prepare, then tells them all to commit. It's correct, but locks are held across network round trips, and if the coordinator dies after prepare, everyone waits.

The story · remember it like this

"Ready?" at the muhurtham

At the muhurtham, the auspicious minute, the pandit turns to both families: "Is everyone ready?" The bride's side says yes. The groom's side says yes. From that moment, nobody may leave the mandap, change their mind or wander off for tea. They've promised.

Then the pandit says "now", and the mangalsutra is tied. Done, for both families at once.

If either side had said "wait, the groom's uncle isn't here", the pandit would have called it off for both. The weak point is the pandit. If he faints between "ready?" and "now", two families stand frozen in the mandap. They can't go ahead on their own, because they don't know if the other side said yes, and they can't leave, because they promised.

What it really is

Two-phase commit (2PC), for a transaction across several participants (databases, or services that each own one):

  • Phase 1, prepare: the coordinator asks each participant to prepare. Each one makes the change durable but not visible, keeps its locks, and votes yes (it promises it can commit) or no.
  • Phase 2, commit or abort: if every vote is yes, the coordinator logs "commit" and tells everyone; otherwise "abort". Participants apply the decision and release their locks.

Why it's rare between microservices:

  • Blocking: a participant that voted yes can't decide on its own. If the coordinator crashes, it holds its locks until the coordinator recovers.
  • Lock time: locks are held across every step's network call plus the prepare and commit round trips. On a hot row that caps throughput (the lab shows the numbers).
  • Availability: every participant must be up for any transaction to commit.
  • Support: every database and broker must support prepared transactions (XA); many don't, and Kafka doesn't join XA.

Where it does work: inside one distributed database, where the database runs it for you with replicated coordinators. Google Spanner runs 2PC across Paxos groups, and because the coordinator is itself a Paxos group, its decision survives a machine failure, which removes the classic blocking problem.

In a real system ✅ Seen · Postgres; Spanner

PostgreSQL supports the prepare phase as PREPARE TRANSACTION, and its docs are blunt: it "is not intended for use in applications or interactive sessions", it's for external transaction managers; a prepared transaction keeps its locks, and "it is unwise to leave transactions in the prepared state for a long time" (it also blocks VACUUM). The docs recommend setting max_prepared_transactions to zero if you don't use a transaction manager.

Spanner (OSDI 2012): each shard is a Paxos group; the coordinator logs its commit or abort decision through Paxos before telling participants, which is why a coordinator crash doesn't freeze them the way classic 2PC does.

Trade-offs
  • 2PC: all or nothing, no compensations to write, other readers never see half a transaction; but blocking, long lock times and every participant must be up.
  • Saga: each step commits locally and quickly, services stay independent; but you write compensations and other readers can see the in-between state.
Say it in the interview

Order, payment and inventory are separate services with their own databases, so I won't use 2PC: it would hold the inventory row lock across three network calls and block if the coordinator dies. If all three tables lived in one database, I'd use one local transaction; and in a distributed SQL database like Spanner, its built-in 2PC is fine.

Trap

"We'll use a distributed transaction" as a one-liner across microservices, a broker and a payment provider. A card network won't join your 2PC; name the blocking problem and propose a saga.

Sagas: local steps and compensations

A saga splits a business transaction into a sequence of local transactions, one per service; if a step fails, it runs compensating actions for the steps already done, in reverse. Compensations are new business actions (a refund), not an undo.

The story · remember it like this

The hall that cancelled

Arjun books the caterer (₹50,000 advance), then the decorator, then tries to confirm the function hall. The hall manager says sorry, the date was double-booked; the other family paid first.

Nothing can be rolled back like a database. The caterer was really booked and really paid. So Arjun works backwards: he cancels the decorator (free, it was only a phone call), then cancels the caterer, who refunds ₹40,000 and keeps ₹10,000 as a cancellation fee.

The family is back where it started, almost. The refund is a new payment, not the old one erased. The ₹10,000 is gone. And for two days, Priya's aunt told everyone the caterer was booked, because it was.

What it really is

A saga (Garcia-Molina and Salem, 1987) is a sequence of local transactions T1, T2, …, Tn. Each Ti has a compensating transaction Ci that semantically undoes it. If Tk fails, run Ck−1, …, C1. The saga either completes or is compensated; it's never left half done.

Two ways to coordinate it:

  • Choreography: each service listens for the previous step's event and publishes its own (OrderCreated → StockReserved → PaymentCaptured). No central part; but the flow lives in many services and is hard to follow, test and change.
  • Orchestration: one orchestrator (a service or a workflow engine) tells each participant what to do and records progress. The flow is in one place; the orchestrator is another component to run and must survive crashes. Most designs with more than three steps use this.

What a saga gives up is isolation: other requests can see the in-between state (stock reserved, payment not taken), and two sagas can interfere. Countermeasures:

  • Semantic lock: mark records as PENDING, so other flows treat them carefully.
  • Commutative updates: design steps so their order doesn't matter (add and subtract from a balance).
  • Reread before update: check the value hasn't changed, or restart the step.

Every step and every compensation must be idempotent, because the orchestrator retries them after crashes and timeouts. And compensations must eventually succeed: retry them, and alert a person if they keep failing.

In a real system ✅ Seen · paper; Azure

The original paper (Garcia-Molina and Salem, Princeton, 1987) was about long-lived transactions holding locks inside one database: write the long transaction as a sequence of transactions that can be interleaved with other transactions, and the system guarantees that either all of them finish or compensating transactions undo the partial work.

Chris Richardson's saga pattern (microservices.io) applies it across services and shows the semantic lock: the Order Service creates the order "in a PENDING state", the Customer Service tries to reserve credit, and the order is then approved or rejected. Microsoft's saga pattern guide lists the isolation anomalies (lost updates, dirty reads, fuzzy reads) and the countermeasures above.

Trade-offs
  • Choreography: no coordinator, good for 2–3 steps; but the flow is implicit, cyclic dependencies creep in, and debugging means reading several services' logs.
  • Orchestration: explicit flow, one place to see a saga's state and retry it; but one more service (or a workflow engine) to run and keep available.
Say it in the interview

Checkout is an orchestrated saga: reserve stock, book the courier, capture payment. The order sits in PENDING until the last step. If the courier booking fails, the orchestrator releases the stock; if payment fails, it cancels the courier and releases the stock. Each step and compensation is idempotent, keyed by order ID and step.

Trap

Calling a compensation a rollback. Other users already saw the reserved stock, the customer already saw the charge, and an email may have gone out. Say what each compensation does in business terms, and what the user sees in between.

Ordering the steps and keeping the saga alive

Put steps that are likely to fail and cheap to undo first, make the hard-to-undo step the pivot, and after it only steps that can be retried until they succeed; then run the saga on something that remembers its progress through crashes.

The story · remember it like this

Uncle's notebook

After the hall fiasco, Arjun's uncle, who has married off four daughters, sits him down.

"First, check the date with the pandit and put a refundable hold on the hall. Those fail most often, and cancelling them costs nothing. Then pay the caterer's non-refundable advance. Once that's paid, there's no going back, so everything after it must be something you can always get done eventually: printing cards, sending invites, booking the band. If the printer is busy, you try another printer. You never cancel the wedding because of the cards."

Then he hands Arjun a notebook. "Write down every step when you start it and when it's done. If you fall ill for a week, your sister can open this and carry on from the last line, without paying anyone twice."

What it really is

Three kinds of step (Microsoft's terms):

  • Compensable: can be undone by another action (release a stock hold, cancel a courier booking, void a card authorisation).
  • Pivot: the point of no return; once it succeeds the saga must finish (capture the payment, ship the parcel).
  • Retryable: after the pivot; idempotent, and retried until they succeed (send the receipt, update search).

Ordering rule: compensable steps first, ordered so the ones most likely to fail come earliest (they're cheap to abandon); then the pivot; then retryable steps. A payment is often split so it fits: authorise early (a hold, compensable by voiding it) and capture as the pivot. The lab shows how the order changes the number of refunds a day.

Keeping it alive through crashes: a saga can take seconds or days, and the orchestrator will crash during some of them. Its progress must be durable:

  • A saga table (saga_id, current step, status) updated in the same transaction as each step's outcome, with the outbox to send the next command; or
  • A durable workflow engine (Temporal, AWS Step Functions, Azure Durable Functions) that records every step's result in a history and resumes from it after a crash. Your steps still run at least once, so they still need idempotency keys.

Timeouts and stuck sagas: give every step a deadline. A saga stuck in PENDING past it is resumed or compensated by a sweeper, and one that can't be compensated goes to a person.

In a real system ✅ Seen · Azure; Temporal

Microsoft's saga guide defines the three kinds: pivot transactions are "the point of no return"; after one succeeds, "all subsequent actions must be completed", and retryable transactions "are idempotent and help ensure that the saga can reach its final state, even if temporary failures occur".

Temporal records every Activity's result in the workflow's event history and replays it after a Worker crash, but warns that an Activity "may be executed multiple times and may even partially complete more than once", so steps must be idempotent. AWS Step Functions Standard workflows run up to one year with exactly-once state transitions (unless you add Retry), which AWS recommends for non-idempotent actions like payments; Express workflows run up to five minutes.

Trade-offs
  • A workflow engine gives durable progress, retries, timers and visibility for free, but it's a platform to run (or pay for), and workflow code has rules (deterministic replay in Temporal).
  • A hand-rolled saga table and outbox needs no new platform, but you build retries, timeouts, sweepers and a status view yourself.
Say it in the interview

Steps run in this order: reserve stock and authorise the card (both compensable, and the likeliest to fail), then capture the payment (the pivot), then confirm the courier and send the receipt (retryable). The saga runs on Temporal, so a crash resumes it from history; every step passes saga_id plus step name to the service it calls as an idempotency key.

Trap

Putting the payment capture first "so we know the customer can pay". Every later failure becomes a refund the customer sees. Authorise first if you need to know; capture last.

Try it: Checkout across three services: 2PC or saga?

A checkout reserves stock, books a courier and captures the payment, each in its own service. Choose the step order and whether calls carry idempotency keys, then set the load, the network and the failure rates. Each row shows the arithmetic: how long the hot item's stock row stays locked under 2PC and under a saga, how many compensations and refunds the saga runs a day, and what retries do without keys.

Start from

An ordinary day: 50 checkouts a second, 10 of them for the most popular item. All three services sit in one zone (1 ms round trips). Payment is captured last, and every call carries an idempotency key kept for 24 hours.

Saga step order
Idempotency keys
What we're sizingNumberHow we got itSo we decide
1 · The hot item: how long its row stays locked
Hot item, most orders/sEvery order for one item queues on one lock. 2PC holds it across network round trips; a saga holds it only for its own local commit.2PC 61 · saga 250
2PC: the stock row is locked from the stock step (step 1) until the commit arrives = 3 steps × (1 + 4) ms + prepare round trip and commit message (1.5 × 1 ms) = 17 ms
saga: the stock step is one local transaction = 4.0 ms
one lock at a time: 1,000 ms ÷ 17 ms = 61/s (2PC) vs 1,000 ÷ 4.0 ms = 250/s (saga); you want 10/s
2PC coordinator crash after prepare: the row stays locked for 30 s → 300 hot-item orders stuck
2PC keeps up (16% busy), but a crashed coordinator would still freeze the row.
2 · What fails, and what the saga has to undo
Refunds a dayA compensation is a new action, not an undo: the customer sees the charge and then the refund. 2PC would roll all of this back invisibly, which is the one thing it does better.0
step 1, reserve stock: reached by 100% of orders, fails for 3%, nothing to undo
step 2, book courier: reached by 97% of orders, fails for 0.19%, then undo 1 step (release the stock)
step 3, capture payment: reached by 96.8% of orders, fails for 4.8%, then undo 2 steps (release the stock, cancel the courier)
compensations = 50/s × 86,400 × 0.0987 per order = 427K a day; orders that complete: 92%
refunds = orders that fail after the payment step (step 3) = 0 a day
The payment is the pivot: nothing after it can fail for a business reason, so nobody is refunded for a later failure.
3 · Retries after a timeout
Duplicates a dayA timeout doesn't say whether the step happened. Only the server can tell a retry from a new request, and only if the retry carries the same key.0
calls = 50/s × (1.000 + 0.970 + 0.968 steps reached) = 147/s
no answer: 147 × 0.1% = 0.15/s; of which already done: × 50% = 0.07/s → 6.3K repeats a day if retried blindly
payment step only: 50 × 0.968 × 0.1% × 50% × 86,400 = 2.1K double charges a day without keys
key store: 147/s × 24 h × 3,600 × 500 B = 6.3 GB; retries last 6.0 min vs keys kept 24 h
Keys cost 6.3 GB of storage and remove every repeat inside the 24 h window.
4 · Verdict for this checkout
What you getEither works here; a saga is still the usual choice2PC would lock the hot item's row for 17 ms per order (at most 61 a second, and you need 10), so it keeps up. But it ties three services' availability together, needs every database to support prepared transactions, and if the coordinator crashes after prepare, the hot row stays locked until it recovers: about 300 orders stuck at a 30 s recovery. If all three tables lived in one database, a plain local transaction would beat both.

Try: on One zone, raise the hottest item to 60 a second and watch 2PC fall behind while the saga doesn't notice. On Cross-region, set the round trip back to 1 ms and watch the 2PC lock drop from a third of a second to 16.5 ms. On Pay first, switch the order back. On No keys, set retries to run for 72 hours and turn keys on with a 24-hour window. The 2PC timing is a simple model (sequential calls, one prepare round trip, commit on arrival); real coordinators add log writes, and real card payments usually authorise first and capture last. All numbers are rounded teaching values.

Remember it

One line per idea. Read this the night before.

  1. A timeout has three outcomes: not done, done, still running. Never retry as if it's new; never report it as failed.
  2. Idempotent = twice leaves the same state as once. Set, don't add; client-chosen IDs; update only if still version 7.
  3. Idempotency key: one per intent, made by the client, reused on every retry; stored with a request hash and the result in the same transaction as the effect; kept longer than any retry.
  4. Consumers get messages at least once: insert the message ID and apply the effect in one transaction. Check-then-act is a race.
  5. Exactly-once delivery doesn't exist. Exactly-once processing holds inside one boundary; end to end, every external effect needs its own idempotency.
  6. 2PC: prepare, then commit. Correct, but locks across round trips and blocks if the coordinator dies. Fine inside Spanner, rare between services.
  7. Saga: local steps plus compensations in reverse. Compensations are business actions (refunds), not undo. No isolation: use PENDING states.
  8. Compensable steps first (likeliest to fail first), then the pivot, then retryable steps. Run it on something durable; every step still idempotent.

Check yourself

Answer out loud, then open.

Your payment service calls the card provider, and the call times out after 10 seconds. What do you do?

It's an unknown, not a failure: the charge may have gone through.

  • Keep the payment in PENDING; don't show "failed" and don't let the user pay again with a new key.
  • Retry with the same idempotency key you sent the first time; the provider returns the original result if it charged.
  • If retries keep timing out, stop and reconcile: a job asks the provider for the payment by your reference and settles it.
  • Show the user "processing", and notify them when it settles.

Say it A timeout gets a retry with the same key, or a lookup by our reference, never a fresh charge.

A user taps "Pay" twice quickly, and the second tap creates a second request. How do you stop a double charge?

The key must belong to the intent, not the tap or the HTTP attempt.

  • Generate the idempotency key when the pay screen loads (or when the order is created) and store it with the pending order on the device.
  • Both taps send the same key. The server inserts the key with a unique constraint, so the second request either gets the saved result or, if the first is still running, a 409 "in progress", and never runs the charge.
  • Disable the button after the first tap too, but that's UX, not the guarantee.
Why isn't "check Redis for the key, and if it's missing, process the request" enough?

Two problems:

  • Check-then-act race: two concurrent repeats both see "missing" and both process. You need an atomic insert (a unique constraint, or a conditional write).
  • Two stores, no transaction: if the key is in Redis and the effect is in Postgres, a crash between them either loses the request (key saved, no effect) or lets a repeat through (effect saved, no key).

Fix: insert the key row with the request hash, apply the effect and save the result in one database transaction. For an external effect, record "started" first, pass the key on to the provider, then record the result.

The interviewer says: "Just use Kafka's exactly-once and you don't need idempotency." How do you answer?

It's true inside Kafka and not beyond it.

  • Kafka transactions make "read from a topic, write to a topic, commit the offset" atomic, so Kafka-to-Kafka processing has exactly-once effect.
  • The moment the consumer writes to Postgres, sends an email or calls a payment API, that effect is outside the transaction. A crash after the effect and before the commit redelivers the message and repeats the effect.
  • So: at-least-once plus idempotent effects at each external boundary (a processed-IDs table in the same transaction, or the provider's idempotency key).

Say it Exactly-once holds inside the boundary that deduplicates; I make every effect outside it idempotent.

Checkout touches Order, Inventory and Payment services, each with its own database. Why not 2PC, and what do you do instead?

Why not 2PC:

  • Locks are held across every network call plus prepare and commit; on a hot item's stock row that caps orders per second (at 70 ms between regions, a few a second).
  • If the coordinator crashes after prepare, participants hold locks until it recovers.
  • Every service must be up, and the payment provider won't join your transaction.

Instead, an orchestrated saga: reserve stock, authorise payment, book the courier, then capture payment as the pivot, then send the receipt. Each step is a local transaction; failures run compensations in reverse (void the authorisation, release stock). The order sits in PENDING until the end, and every step is idempotent, keyed by order ID and step.

A compensation fails: the refund API is down. What now?

A compensation can't be skipped; it has to eventually succeed.

  • Retry it with backoff and the same idempotency key (so a retry after a timeout doesn't refund twice).
  • Keep the saga in COMPENSATING with the step recorded durably, so a crash of the orchestrator doesn't forget it.
  • After a deadline, alert a person and put it on a manual queue with everything they need.
  • Tell the user what's happening ("refund in progress").

This is why steps that are hard to compensate go late, ideally as the pivot.

Your saga reserves stock and then fails at payment. Between the two, another customer is told the item is out of stock. Is that a bug?

It's the saga's lack of isolation, and it's often acceptable, but say it out loud.

  • The reservation is real for a few seconds, so other readers see less stock. That's a semantic lock working as designed: the reservation is PENDING and expires.
  • If it matters, release holds quickly on failure, give holds a short expiry (a sweeper releases old ones), and show "few left" rather than "sold out" while holds are pending.
  • What would be a bug is the opposite: selling stock that a pending saga holds, which the semantic lock prevents.

Where you'll use this in the series

Sources

Checked October 2026. Definitions come from the papers and RFCs listed (Saltzer, Reed & Clark 1984, Garcia-Molina & Salem 1987, RFC 9110 in 2022) and the official Stripe, AWS (Builders' Library, DynamoDB, SQS, Step Functions), PostgreSQL, Temporal and Azure docs; company and project statements are as published on the dates shown (RBI 2019, Brandur Leach 2017, Flink 2018, AWS 2021) and may have changed since. The Idempotency-Key header is still an expired IETF draft, not an RFC. The lab's rates and timings are rounded teaching values; its 2PC timing is a simple model.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

You're reading this Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts