Distributed transactions, two-phase commit and sagas
What to do when one business action touches two databases or services. Two-phase commit and its blocking problem, sagas and compensation, the outbox and inbox that make messages reliable, and why exactly-once is really effectively-once.
ConceptCore29 min readUpdated
- 2 sequence flows
- 6 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page13 sectionsHLDLLDSenior depth
Read first: Transactions and isolation levels, Consensus, leader election and distributed locks
- Explain why atomicity across two systems is hard, and what two-phase commit guarantees, costs and where it blocks.
- Design a saga with compensations, choosing orchestration or choreography, and handle the lack of isolation.
- Use a transactional outbox and an idempotent inbox to publish and consume messages reliably, and explain effectively-once.
- Choose between a local transaction, 2PC, a saga and a redesigned boundary for a given business action.
6 code samples (286 lines), collapsed so the explanation stays in focus.
Inside one database a transaction is a solved problem: the log and the locks give you all-or-nothing and isolation, as the transactions lesson showed. The trouble starts when one business action touches two places: charge a card and reserve stock, debit one bank and credit another, create an order and tell the warehouse. If the first step succeeds and the second fails, or the process dies between them, money or stock is wrong and nobody has noticed. There are three families of answers. Make the whole thing atomic across the systems (two-phase commit). Break it into local steps that can be undone (a saga). Or make sure the message that triggers the next step can never be lost (the outbox).
Send "commit" to another system and hear nothing back. Was the request lost? Did the system crash before applying it, or after, and was the reply the thing that got lost? You cannot tell. The classic two generals problem shows that no protocol over an unreliable channel lets both sides be certain they agree on an action. What a protocol can do is guarantee safety, that the outcome is never mixed, and accept that it may sometimes have to wait. It is the same trade as in consensus.
Atomic commit is not quite consensus. In atomic commit every participant must commit or every participant must abort, and any one of them can veto: commit is possible only if all vote yes. In consensus a majority is enough and nobody has a veto. Fault-tolerant atomic commit is built on top of consensus, which is how Spanner does it.
The costs of making two systems commit together are concrete:
each service is up 99.9% of the time:
all of 3 needed: 0.999^3 = 99.70% (26 hours down a year)
all of 5 needed: 0.999^5 = 99.50% (44 hours down a year)
lock held 20 ms across the network: ~50 updates a second on a hot rowAvailability multiplies, because every participant must be up. Latency grows by message rounds and forced disk writes. And locks are held across the network for the whole protocol, which limits throughput on contended rows (the hot-row rule from the transactions lesson).
Two-phase commit (2PC) has a coordinator and several participants, each a database or service that holds part of the data.
Phase 1, prepare. The coordinator asks every participant whether it can commit. A participant that can do its part writes a prepared record to its log, forced to disk, keeps its locks and answers yes. A participant that cannot answers no and rolls back.
Phase 2, decide. If every vote was yes, the coordinator writes commit to its own log, forced to disk, and only then tells the participants. If any vote was no (or missing), it writes abort and tells them. Participants apply the decision, release their locks and acknowledge.
Two rules make this safe. A participant that has voted yes has made a promise: it must be able to commit even after a crash, so the prepared record survives, and it may not release its locks or change its mind until it hears the outcome. And the coordinator's decision is durable before anyone is told, so there is a single commit point; once it is written, the outcome is final whatever crashes next.
| Failure | What happens |
|---|---|
| A participant votes no, or times out in phase 1 | The coordinator decides abort; everyone who prepared rolls back |
| A participant crashes before voting | It counts as a no vote: abort |
| A participant crashes after voting yes | On restart it finds prepared in its log and asks the coordinator for the outcome; it cannot decide alone |
| The coordinator crashes before logging a decision | Nothing was committed anywhere; on restart it aborts (called presumed abort). Prepared participants wait until then |
| The coordinator crashes after logging the decision | On restart it sends the decision again to everyone who has not acknowledged |
| The coordinator stays down | Every participant that voted yes is blocked, holding its locks, until it returns |
The last row is the weakness of 2PC. The sample models the protocol with a durable log on each participant and on the coordinator, and then tries every combination of three votes with a coordinator crash at every one of the seven steps (three prepares, the decision, three announcements), followed by a recovery.
C# · Outcome, Participant, Coordinator, …
using System;
using System.Collections.Generic;
public enum Outcome { None, Commit, Abort }
// A participant in a distributed transaction: one database or service that must commit or abort together with the others.
public sealed class Participant
{
public readonly string Name;
private readonly bool canCommit; // can it do its part (enough stock, enough funds)?
public readonly List<string> Log = new List<string>(); // durable: "prepared", "commit" or "abort"
public Participant(string name, bool canCommit) { Name = name; this.canCommit = canCommit; }
public Outcome Result => Log.Contains("commit") ? Outcome.Commit : Log.Contains("abort") ? Outcome.Abort : Outcome.None;
// Voted yes, holds its locks, and cannot decide alone: only the coordinator knows the outcome.
public bool InDoubt => Log.Contains("prepared") && Result == Outcome.None;
public bool Prepare() // phase 1: promise to commit if told to, then vote
{
if (Result != Outcome.None) return Result == Outcome.Commit;
if (!canCommit) { Log.Add("abort"); return false; } // a "no" vote can abort at once: nothing was promised
if (!Log.Contains("prepared")) Log.Add("prepared"); // a "yes" vote is a promise, so it is forced to disk first
return true;
}
public void Decide(Outcome outcome) // phase 2: carry out the coordinator's decision
{
if (Result == Outcome.None) Log.Add(outcome == Outcome.Commit ? "commit" : "abort");
}
}
public sealed class Coordinator
{
public readonly List<string> Log = new List<string>(); // durable: the decision, written before anyone is told
public Outcome Decision => Log.Contains("commit") ? Outcome.Commit : Log.Contains("abort") ? Outcome.Abort : Outcome.None;
}
public static class TwoPhaseCommit
{
// Runs the protocol one step at a time and stops (the coordinator crashes) once `crashAfter` steps have happened.
// A step is one message to one participant, or the write of the decision. Returns true if the protocol finished.
public static bool Run(Coordinator c, Participant[] participants, int crashAfter)
{
int steps = 0;
bool crashed() => ++steps > crashAfter;
bool allYes = true;
foreach (var p in participants) // phase 1: "can you commit?"
{
if (crashed()) return false;
if (!p.Prepare()) allYes = false;
}
if (crashed()) return false;
if (c.Decision == Outcome.None) c.Log.Add(allYes ? "commit" : "abort"); // the commit point: one durable write
foreach (var p in participants) // phase 2: "commit" or "abort"
{
if (crashed()) return false;
p.Decide(c.Decision);
}
return true;
}
// After a restart the coordinator finishes from its log. With no decision on record the transaction cannot have
// committed anywhere, so it aborts (this is called presumed abort).
public static void Recover(Coordinator c, Participant[] participants)
{
if (c.Decision == Outcome.None) c.Log.Add("abort");
foreach (var p in participants) p.Decide(c.Decision);
}
}C# · Every combination of votes, and a coordinator crash at every possible point.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// Every combination of votes, and a coordinator crash at every possible point.
var blockedWhenAllVoteYes = new List<int>();
for (int votes = 0; votes < 8; votes++) // bit i set: participant i can commit
{
for (int crashAfter = 0; crashAfter <= 7; crashAfter++) // 7 steps in all: 3 prepares, the decision, 3 announcements
{
var coordinator = new Coordinator();
var participants = Enumerable.Range(0, 3).Select(i => new Participant("P" + i, (votes & (1 << i)) != 0)).ToArray();
TwoPhaseCommit.Run(coordinator, participants, crashAfter);
int blocked = participants.Count(p => p.InDoubt); // right now the coordinator is down
if (votes == 7) blockedWhenAllVoteYes.Add(blocked);
TwoPhaseCommit.Recover(coordinator, participants);
var results = participants.Select(p => p.Result).Distinct().ToList();
Debug.Assert(results.Count == 1 && results[0] != Outcome.None, "all participants must reach the same decision");
if (votes != 7) Debug.Assert(results[0] == Outcome.Abort, "one no vote means abort");
}
}
// With all three voting yes, how many are stuck holding locks if the coordinator dies after step k?
Debug.Assert(string.Join(",", blockedWhenAllVoteYes) == "0,1,2,3,3,2,1,0");In all 64 runs the participants ended with the same outcome, never a mix of commit and abort, and any no vote produced abort. The interesting number is how many participants were stuck while the coordinator was down, when all three voted yes:
| Coordinator crashes after step | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Participants blocked | 0 | 1 | 2 | 3 | 3 | 2 | 1 | 0 |
The blocked window runs from the first yes vote to the moment each participant hears the decision, and it is widest between the last vote and the decision. During it a participant holds its locks and cannot help anyone, and in practice an outage there lasts as long as it takes the coordinator to restart. Operators of XA systems sometimes force a heuristic decision on a stuck participant (guess commit or abort by hand), which risks the mixed outcome the protocol exists to prevent.
Ways to live with it:
- Replicate the coordinator's state with consensus, so a single machine failure is not a blocking event. This is what Spanner does: each participant and the coordinator is itself a replicated group.
- Keep transactions short and few: the window is the lock-holding time.
- Three-phase commit adds a step to avoid blocking, but only under strong timing assumptions that a network partition breaks, so it is almost never used.
- Avoid it where you can: the next sections.
You meet 2PC in the XA standard (Java's JTA, Microsoft's MSDTC), in database features such as PostgreSQL's PREPARE TRANSACTION and COMMIT PREPARED, and inside distributed databases. Most message brokers, HTTP APIs and SaaS services do not take part in it at all, which rules it out for many real flows. It is a reasonable tool for a few participants of the same kind in one data center with short transactions.
Databases that span machines still need atomic commit across shards, and they have found ways around the textbook costs.
- Spanner runs 2PC across Paxos groups. Each participant, and the coordinator, is a replicated group, so no single machine failure blocks a transaction, and commit timestamps come from TrueTime (see time, clocks and ordering). The price is the cross-group round trips and the commit wait.
- CockroachDB uses parallel commits: the coordinator writes a staging transaction record in parallel with the writes, and the transaction is considered committed as soon as all of them exist, so the client waits for one round of replication instead of two.
- Percolator (Google, and TiDB's model) lets the client drive 2PC through locks stored in the data. One key is the primary: whether the transaction committed is decided by that one key, and anyone who finds a stale secondary lock can look at the primary and finish or roll back the transaction, so no coordinator needs to survive.
All three keep the single-shard case fast: a transaction that touches one shard does not need 2PC at all, which is one more reason to choose a shard key that keeps related data together.
A saga (Garcia-Molina and Salem, 1987) replaces one big transaction with a sequence of local transactions, each committed on its own, and for each step except the last a compensation that semantically undoes it. If step k fails, the saga runs the compensations of steps k-1 down to 1, newest first.
The properties differ from a transaction in important ways. A saga is atomic only in the sense that it eventually ends either fully done or fully compensated. Its intermediate states are visible to everyone, so it has no isolation. And a compensation is a new business action, not a rollback: refunding a charge is not the same as the charge never having happened (the customer sees both on a statement), and some steps cannot be undone at all (an email sent, a parcel shipped).
Designing the steps.
- Make every step and every compensation idempotent. Orchestrators crash and messages repeat, so any of them may run twice.
- Make compensations retriable until they succeed. A compensation that can fail for good leaves the system half undone.
- Find the pivot. Order the steps so that the ones that can fail and need compensating come first, then one step (the pivot) after which the saga cannot be rolled back, then steps that cannot fail and are simply retried until they succeed. Put the irreversible actions, such as shipping or sending the email, after the pivot.
Orchestration or choreography.
| Orchestration | Choreography | |
|---|---|---|
| How it flows | A central orchestrator (a durable state machine) tells each service what to do next | Each service reacts to events and emits its own |
| Visibility | One place shows where each saga is | The flow is spread across services and hard to see |
| Coupling | Services know the orchestrator | Services know each other's events, and cycles creep in |
| Best for | Business-critical flows with several steps | Two or three services and a simple flow |
| Tools | Temporal, AWS Step Functions, Azure Durable Functions, MassTransit and NServiceBus sagas in .NET | Events on a message broker |
The sample is a checkout saga with four steps (create order, reserve stock, charge, confirm). Every operation is idempotent: reserving stock for an order that already holds a reservation does nothing. The orchestrator logs each completed step, and the test kills it at every checkpoint, before and after every action, then restarts it and lets it finish from its log.
C# · The three services a checkout touches, reduced to the state that matters. Every…
using System;
using System.Collections.Generic;
using System.Linq;
// The three services a checkout touches, reduced to the state that matters. Every operation is idempotent: doing it twice
// has the effect of doing it once, which is what lets a saga retry a step after a crash.
public sealed class Shop
{
public int Stock;
public readonly HashSet<string> Reservations = new HashSet<string>();
public readonly HashSet<string> Charges = new HashSet<string>();
public readonly Dictionary<string, string> Orders = new Dictionary<string, string>();
public bool CardDeclines;
public bool CreateOrder(string id) { Orders[id] = "pending"; return true; }
public void CancelOrder(string id) { Orders[id] = "cancelled"; }
public bool ReserveStock(string id)
{
if (Reservations.Contains(id)) return true; // already done before a crash
if (Stock < 1) return false;
Stock--;
Reservations.Add(id);
return true;
}
public void ReleaseStock(string id) { if (Reservations.Remove(id)) Stock++; }
public bool Charge(string id) { if (CardDeclines) return false; Charges.Add(id); return true; }
public void Refund(string id) { Charges.Remove(id); }
public bool ConfirmOrder(string id) { Orders[id] = "confirmed"; return true; }
}
public sealed class SagaStep
{
public readonly string Name;
public readonly Func<bool> Do; // false means the step cannot be done (declined, out of stock)
public readonly Action Undo; // the compensation: safe to call twice, and if Do never ran
public SagaStep(string name, Func<bool> doIt, Action undo) { Name = name; Do = doIt; Undo = undo; }
}
public sealed class CrashException : Exception { }
public static class Saga
{
// Progress is written to `log` after every step, so a restarted runner picks up where the last one stopped.
// `checkpoint` is called around every action; a test makes it throw to simulate the orchestrator dying right there.
public static void Run(IReadOnlyList<SagaStep> steps, List<string> log, Action checkpoint)
{
if (!log.Contains("failed"))
{
foreach (var step in steps) // forward: do each step once
{
if (log.Contains("done:" + step.Name)) continue;
checkpoint();
bool ok = step.Do();
checkpoint(); // the effect happened but is not yet logged: a retry repeats it
if (!ok) { log.Add("failed"); break; }
log.Add("done:" + step.Name);
}
}
if (log.Contains("failed")) // backward: compensate, newest first
{
int reached = steps.TakeWhile(s => log.Contains("done:" + s.Name)).Count(); // steps that completed...
for (int i = Math.Min(reached, steps.Count - 1); i >= 0; i--) // ...and the one that failed
{
if (log.Contains("undone:" + steps[i].Name)) continue;
checkpoint();
steps[i].Undo();
checkpoint();
log.Add("undone:" + steps[i].Name);
}
}
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
List<SagaStep> CheckoutSteps(Shop shop, string order) => new List<SagaStep>
{
new SagaStep("order", () => shop.CreateOrder(order), () => shop.CancelOrder(order)),
new SagaStep("stock", () => shop.ReserveStock(order), () => shop.ReleaseStock(order)),
new SagaStep("payment", () => shop.Charge(order), () => shop.Refund(order)),
new SagaStep("confirm", () => shop.ConfirmOrder(order), () => { }),
};
// Three situations, and for each of them an orchestrator crash at every one of its checkpoints.
var situations = new (string Name, int Stock, bool Declines, string Order, int Left, bool Charged)[]
{
("everything works", 1, false, "confirmed", 0, true),
("card is declined", 1, true, "cancelled", 1, false),
("out of stock", 0, false, "cancelled", 0, false),
};
foreach (var s in situations)
{
int checkpointsInARun = 0;
for (int crashAt = 0; crashAt <= 40; crashAt++) // far more crash points than a run has: the later ones never fire
{
var shop = new Shop { Stock = s.Stock, CardDeclines = s.Declines };
var log = new List<string>();
int count = 0;
try { Saga.Run(CheckoutSteps(shop, "o1"), log, () => { if (count++ == crashAt) throw new CrashException(); }); }
catch (CrashException) { }
Saga.Run(CheckoutSteps(shop, "o1"), log, () => { }); // the orchestrator restarts and finishes from its log
if (count > checkpointsInARun) checkpointsInARun = count;
Debug.Assert(shop.Orders["o1"] == s.Order, $"{s.Name}, crash at {crashAt}: order is {shop.Orders["o1"]}");
Debug.Assert(shop.Stock == s.Left, $"{s.Name}, crash at {crashAt}: stock is {shop.Stock}");
Debug.Assert(shop.Charges.Contains("o1") == s.Charged && shop.Reservations.Contains("o1") == (s.Order == "confirmed"));
}
Debug.Assert(checkpointsInARun >= 8);
}There were 8 checkpoints in the happy path, 12 when the card is declined (the compensations add four) and 8 when the item is out of stock: 28 distinct crash points. In every one the final state was either fully done (order confirmed, one item gone, one charge) or fully undone (order cancelled, stock restored, no charge, no reservation). The cases that matter are the crash between a step's effect and its log entry, which repeats the step, and the crash in the middle of the compensations, which resumes them. Both are safe only because the operations are idempotent.
No isolation. Between the steps, other transactions can see and act on half-finished work: the item is reserved but the order is not yet paid for, so a second customer is told it is out of stock and then it comes back. The countermeasures:
| Problem | Countermeasure |
|---|---|
| Others read the saga's intermediate state | A semantic lock: a visible status ("pending") that readers treat as "may change" |
| Two sagas update the same value | Commutative updates: decrement a counter rather than overwrite a value, so order does not matter |
| A compensation would be expensive or impossible | Reorder the steps: do the risky or irreversible one as late as possible |
| A saga overwrites what another changed | Reread and check a version before the write, and fail the step if it moved |
Every saga step has the same shape: change my data, then tell the next service. Two writes to two systems cannot be atomic. Write the database first and crash before publishing, and the event is lost. Publish first and the database write fails, and you announced something that never happened. (The queues lesson introduces the dual-write problem.)
The transactional outbox removes it. In the same local transaction as the state change, insert a row describing the event into an outbox table. A separate relay reads unsent rows and publishes them, then marks them sent. Either a poller does that, or, with less delay and no polling load, a change-data-capture tool reads the database's own log (Debezium has an outbox event router for this; the logs, streams and Kafka lesson covers change data capture). Messages for one entity stay in order if the relay publishes them in id order and the broker partitions by the entity's key.
The relay can crash between publishing and marking, so after a restart it publishes the same row again: delivery is at least once, never zero. The receiving side needs an inbox: a table of the ids of messages already handled, written in the same local transaction as the effect, so a duplicate finds its id and does nothing.
C# · The service that changes its own data and must tell others. The order row and the outbox…
using System;
using System.Collections.Generic;
// The service that changes its own data and must tell others. The order row and the outbox row are written in one local
// transaction, so either both exist or neither does.
public sealed class OrderService
{
public readonly List<int> Orders = new List<int>();
public readonly List<(long Id, int Order, bool Sent)> Outbox = new List<(long Id, int Order, bool Sent)>();
private long nextId = 1;
public void PlaceOrder(int order)
{
Orders.Add(order); // the state change...
Outbox.Add((nextId++, order, false)); // ...and the message about it, in the same transaction
}
}
public sealed class Broker
{
public readonly List<(long Id, int Order)> Delivered = new List<(long Id, int Order)>(); // at-least-once: duplicates are possible
}
public sealed class Relay
{
// Publishes unsent outbox rows, then marks them sent. A crash between the two steps leaves a row published but unmarked,
// so it is published again after the restart: that is the duplicate the consumer must tolerate.
public static void Pump(OrderService service, Broker broker, Func<bool> crashNow)
{
for (int i = 0; i < service.Outbox.Count; i++)
{
var row = service.Outbox[i];
if (row.Sent) continue;
broker.Delivered.Add((row.Id, row.Order));
if (crashNow()) return; // died after publishing, before marking
service.Outbox[i] = (row.Id, row.Order, true);
}
}
}
public sealed class Shipping
{
public readonly Dictionary<int, int> Shipments = new Dictionary<int, int>(); // order -> how many times we shipped it
private readonly HashSet<long> inbox = new HashSet<long>(); // ids of messages already handled
public void Handle((long Id, int Order) message, bool useInbox)
{
if (useInbox && !inbox.Add(message.Id)) return; // the inbox row and the effect commit together
Shipments[message.Order] = Shipments.GetValueOrDefault(message.Order) + 1;
}
}C#
using System;
using System.Diagnostics;
using System.Linq;
var randomCrash = new Random(77);
var orderService = new OrderService();
var broker = new Broker();
for (int order = 1; order <= 500; order++) orderService.PlaceOrder(order);
int restarts = 0;
while (orderService.Outbox.Any(row => !row.Sent))
{
Relay.Pump(orderService, broker, () => randomCrash.Next(5) == 0); // the relay dies after one publish in five
restarts++;
}
var withInbox = new Shipping();
var withoutInbox = new Shipping();
foreach (var message in broker.Delivered) { withInbox.Handle(message, true); withoutInbox.Handle(message, false); }
Debug.Assert(broker.Delivered.Count > 500); // the relay produced duplicates...
Debug.Assert(Enumerable.Range(1, 500).All(o => withInbox.Shipments.GetValueOrDefault(o) == 1)); // ...and with an inbox none of them shipped twice
Debug.Assert(withoutInbox.Shipments.Values.Any(count => count > 1)); // without one, some orders ship twice
Debug.Assert(orderService.Orders.Count == 500 && broker.Delivered.Select(d => d.Order).Distinct().Count() == 500); // and none was lostThe test places 500 orders and runs a relay that dies after one publish in five. It took 135 relay runs and delivered 634 messages for 500 orders. Without an inbox, 99 orders were shipped twice. With one, every order shipped exactly once, and no order was lost. At-least-once delivery plus an idempotent receiver is the real meaning of exactly-once in practice: exactly-once delivery over an unreliable network is impossible, and what you build is exactly-once effect. Kafka's "exactly-once" feature, for instance, covers a read-process-write loop inside Kafka; a side effect outside it, such as a payment or an email, still needs an idempotency key or an inbox of your own.
A pattern that appears in booking and payments is try, confirm, cancel (TCC): first reserve the resource, with an expiry, then confirm it once everything else succeeded, or cancel, and if nobody does either, let the reservation expire. It is a saga in which the intermediate state is explicit and self-healing. Card payments work this way (authorise, then capture, and uncaptured authorisations lapse), and so does the stock hold with an expiry in the Amazon system design guide. Confirm and cancel must be idempotent, and the expiry should be longer than the slowest legitimate flow.
| Situation | Reach for |
|---|---|
| The data can live in one database | A normal local transaction. Redraw the boundary to make this true: one aggregate, one transaction |
| Two or three participants of the same kind, short, one data center | 2PC, if every participant supports it |
| A business process across services that takes seconds to days | A saga, orchestrated if it is critical |
| Tell other services about a change you made | A transactional outbox, with an inbox on the receiving side |
| Reserve something scarce that may not be used | A hold with an expiry (TCC) |
| Read data owned by several services | Do not join across them at read time: keep a read model fed by events |
Pat Helland's 2007 paper argues the first row hardest: design entities so that every transaction touches only one, and connect entities with messages that may arrive more than once.
| Situation | What happens | Defence |
|---|---|---|
| A compensation fails | The saga is stuck half undone | Retry with backoff, alert, a manual queue, and keep compensations simple |
| A step times out | It may or may not have happened | Ask again with the same idempotency key, or query the status; never assume failure |
| The orchestrator crashes | Sagas in flight stop | Durable saga state; resume from the log (tested above) |
| A message is delivered twice | A double charge or shipment | Idempotency keys and an inbox |
| Messages arrive out of order | "Cancel" arrives before "create" | State machines that reject impossible transitions; per-entity ordering |
| A reader sees intermediate state | An item looks out of stock, or an order looks paid | Semantic locks and status fields |
| A poison message blocks the relay | The outbox backs up | Dead-letter handling, skip and alert |
| The coordinator of a 2PC stays down | Participants hold locks | Replicate the coordinator; keep the window short; avoid manual heuristic decisions |
| The outbox table grows without bound | Slow polling and queries | Delete or archive sent rows on a schedule |
Interviewer follow-upL5Why can't you just call two services inside one transaction?How to answer
A transaction is a promise by one system's log and locks. A call to another service is a network request that can be lost, repeated or applied without you hearing back, and the other service does not take part in your transaction. If the first call succeeds and the second fails, nothing rolls the first back. You need a protocol that makes them agree (two-phase commit), or steps with explicit compensation (a saga), or a redesign that keeps the action inside one database.
Interviewer follow-upL5Explain two-phase commit and its main weakness.How to answer
The coordinator asks every participant to prepare; each that can commit logs a promise, keeps its locks and votes yes. If all voted yes the coordinator durably logs commit and tells everyone; otherwise it aborts. It guarantees no mixed outcome. Its weakness is blocking: if the coordinator crashes after participants voted yes and before they hear the decision, they hold their locks and cannot decide until it recovers. It also needs every participant up and holds locks across the network.
Interviewer follow-upL62PC or a saga: how do you choose?How to answer
2PC gives atomicity and isolation but needs every participant to support it, holds locks over the network, multiplies unavailability and can block. A saga is available and works across anything that exposes an API, but gives up isolation and needs compensations that you must design and make idempotent. Use 2PC for a few cooperating databases with short transactions, a saga for business processes across services, and try first to keep the data in one database.
Interviewer follow-upL6Design a booking flow for a flight, a hotel and a payment as a saga.How to answer
Order the steps by how hard they are to undo: hold the seat (with an expiry), hold the room (with an expiry), authorise the payment, then confirm both holds and capture the payment. If the authorisation fails, cancel both holds. If a confirmation fails after payment, refund and cancel the other. The pivot is the capture, after which the confirmations are retried until they succeed. Each step is idempotent, keyed by the booking id, the orchestrator persists its state, and what cannot be compensated (a non-refundable fare) is placed after the pivot or handled by a human queue.
Interviewer follow-upL6How do you make sure an event is published if, and only if, the database change commits?How to answer
Use a transactional outbox: write the event as a row in the same local transaction as the change, and have a relay publish unsent rows and mark them sent, by polling or by reading the database log. That guarantees the event is never lost, and the relay can repeat a publish after a crash, so delivery is at least once. The consumer records each handled message id in an inbox in the same transaction as its effect, which turns the duplicates into no-ops.
Interviewer follow-upL6A payment call times out. What do you do?How to answer
A timeout means unknown, not failed. Do not release the stock and cancel the order on the strength of it. Retry the same call with the same idempotency key, which returns the original result if it went through and charges once if it did not, or query the payment's status, and keep the order pending until you know. A reconciliation job that asks the provider about pending payments covers the cases where nothing retries.
Interviewer follow-upL7Sagas have no isolation. What goes wrong, and how do you cope?How to answer
Other transactions can read or overwrite the saga's intermediate effects: a stock count that is temporarily low, an order shown as paid that is later cancelled, two sagas changing one value. Cope with semantic locks (a visible "pending" state that readers handle), commutative updates, ordering the steps so risky ones come early or late, and re-reading a version before writing. Accept that some anomalies remain and decide, per business rule, whether the cost of a rare wrong view is lower than the cost of a lock.
Interviewer follow-upL7How do Spanner and CockroachDB differ from textbook 2PC?How to answer
They remove the blocking and some of the latency. In Spanner each participant and the coordinator is a replicated Paxos group, so a machine failure does not block a transaction, and a single-group transaction skips 2PC. CockroachDB's parallel commits write a staging record in parallel with the writes, so the transaction is committed once all exist and the client waits one replication round, and Percolator-style systems let any client resolve a stuck transaction through the primary lock. The common idea: make the coordinator's state durable and recoverable by anyone.
Interviewer follow-upL7What does "exactly-once" mean, and can you have it?How to answer
Exactly-once delivery over an unreliable network is impossible: after a timeout you cannot know whether the message arrived. What you can have is at-least-once delivery combined with an idempotent receiver, so the effect happens once: an idempotency key or an inbox written atomically with the effect. Systems that advertise exactly-once, such as Kafka's transactions, cover a bounded scope (reading and writing Kafka topics); an external side effect still needs the receiver to deduplicate.
When a design needs two systems to change together, say first whether they have to. Try to keep them in one database; if not, say which tool you use and what it costs: "an orchestrated saga with idempotent steps and compensations, an outbox so no step's event is lost, and an inbox so duplicates are harmless; the pivot is the payment capture". Name the failure you accept, such as users briefly seeing a pending order, and the one you do not, such as charging twice.
Atomic commit across systems cannot be free, because after a lost message you cannot tell whether the other side acted. Two-phase commit makes participants promise and a coordinator decide at a durable commit point; it never produces a mixed outcome, but a coordinator crash blocks prepared participants, and it multiplies unavailability and holds locks across the network. Distributed databases avoid the blocking by replicating the coordinator. A saga splits the action into local transactions with idempotent compensations, ends fully done or fully undone, has no isolation, and needs a pivot and countermeasures such as semantic locks. A transactional outbox makes a state change and its message atomic, the relay delivers at least once, and an inbox makes the receiver idempotent: effectively-once. Choose a local transaction first, then a saga, and reserve 2PC for a few cooperating participants.
Try answering out loud before you reveal each answer.
QuestionIn two-phase commit, the coordinator crashes after all participants voted yes but before sending the decision. What state are the participants in, and what does each need before it can act?Reveal answer
They are in doubt: each logged a prepared record, holds its locks and promised to commit if told to, but none knows the outcome and none may decide alone, because another participant may have voted differently or the coordinator may have decided either way. Each waits until the coordinator recovers and tells them, which is the blocking problem.
QuestionA saga's orchestrator crashes just after a step's effect was applied but before it logged the step as done. What happens on restart and what makes it safe?Reveal answer
The orchestrator finds no record of the step, so it runs it again. That is safe only because every step is idempotent: reserving stock for an order that already holds a reservation does nothing, so the effect still happens once. Compensations have the same requirement, since they may be repeated after a crash.
QuestionWhy is checking whether an order exists before inserting it not a substitute for an inbox or an idempotency key?Reveal answer
The check and the effect are two separate operations, so two copies of a message handled at the same time can both pass the check, and a crash between the check and the effect leaves it undone or repeated. An inbox row written in the same local transaction as the effect, with a unique constraint on the message id, makes the duplicate fail atomically.
QuestionThe outbox relay crashes after publishing a message but before marking it sent. What does the consumer see, and what does it need?Reveal answer
After the restart the relay publishes the same message again, so the consumer sees it twice. It needs to be idempotent: record the message id in an inbox in the same transaction as the effect, so the second copy is recognised and skipped. In the simulation 634 messages were delivered for 500 orders, and the inbox kept every order to one shipment.
- Hector Garcia-Molina and Kenneth Salem, Sagas (opens in a new tab) (SIGMOD 1987): the original saga and compensation idea.
- Pat Helland, Life beyond Distributed Transactions: an Apostate's Opinion (opens in a new tab) (CIDR 2007), with an updated version in ACM Queue (opens in a new tab): design entities so a transaction touches only one.
- Chris Richardson, Saga (opens in a new tab) and Transactional outbox (opens in a new tab): the patterns and their countermeasures.
- Microsoft Azure Architecture Center, Saga distributed transactions pattern (opens in a new tab) and Compensating Transaction pattern (opens in a new tab).
- Debezium, Outbox Event Router (opens in a new tab): change-data-capture for an outbox.
- James Corbett et al., Spanner: Google's Globally-Distributed Database (opens in a new tab) (OSDI 2012): two-phase commit across Paxos groups.
- Daniel Peng and Frank Dabek, Large-scale Incremental Processing Using Distributed Transactions and Notifications (opens in a new tab) (OSDI 2010): Percolator.
- Cockroach Labs, Parallel Commits (opens in a new tab): how a distributed commit is cut to one round.
- PostgreSQL documentation, PREPARE TRANSACTION (opens in a new tab): the participant side of two-phase commit.
- Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab), the sections on distributed transactions and on exactly-once processing.