Lesson 05

Transactions Across Partitions

Building block

In one database, a transfer that debits one row and credits another is one transaction, and nobody sees half of it. Partition the accounts, and the two rows can sit on two machines, with no commit that covers both.

An interviewer who has pushed you to shard pushes here next. There are three answers: keep the rows together, make the machines vote, or split the work into steps that can be compensated. Each has a price you say out loud.

First, Keep Them Together

Choose the partition key so that a transaction's rows share a partition, the method of Chapter 3's last lesson. Partition orders by customer, and an order travels with its items. Partition a hotel's nights by hotel, as Chapter 23 does, and a booking of several nights is one local transaction.

A transaction across partitions is a cost paid on every request that needs one, so the first move is to need fewer of them. What remains is the transfer between two users' accounts, which no key puts together. A third design for that case, one writer per account fed by a log, is the digital wallet's deep dive in Chapter 25.

Two-Phase Commit

A coordinator asks every participant to prepare: write its changes durably, keep its locks, and vote yes or no. If every vote is yes, the coordinator records the decision and tells them all to commit. Otherwise it tells them to abort.

A participant that voted yes may not decide alone. So a coordinator that dies between the phases leaves it in doubt, holding its locks until the decision is known. PostgreSQL Deep Dive shows the database side of that: a prepared transaction forgotten by its coordinator, holding back vacuum for as long as nobody notices.

The locks are held for at least two round trips. Between US east and US west, a round trip is about 70 milliseconds, so the locks last at least 140 milliseconds, and every other transaction that wants those rows waits. The fix for the blocking is a coordinator that is not one machine. Spanner runs two-phase commit between Paxos groups and keeps each transaction's state in a group, so the decision outlives any one server.

Two-phase commit, and the in-doubt window
Prepareeach participant writes and keeps its locks
→
Every vote is yesthe in-doubt window opens: locks held, no decision
→
The decision is recordedthe in-doubt window closes
→
Commitevery participant applies it and releases its locks

Sagas

A saga runs a long transaction as a sequence of local transactions, each with a compensation; Garcia-Molina and Salem named the idea in 1987. The one-service saga, with its state column and its forward and backward recovery, is Backend Deep Dive's lesson on sagas. This lesson owns the saga across services and partitions.

A saga has no isolation. Other requests see the states between the steps: money debited and not yet credited. Three countermeasures contain it. A pending state that other requests respect. The step that cannot be compensated, placed last. And steps and compensations that are safe to repeat. A compensation restores an acceptable state, not the old one.

A transfer as a saga: each step and its compensation
The stepa local transaction
1. Debit the sender and hold the amount as pending, in one local transaction.
2. Credit the receiver.
Its compensationif a later step fails for good
1. Release the hold back to the sender: the refund.
2. None: the last step, retried until it succeeds.

Orchestration or Choreography

Backend Deep Dive kept one driver inside one service, and handed choreography to this course. An orchestrator holds the saga's state. It answers "where is this transfer" in one read, and it changes the flow in one place. It is also one more service to run.

In choreography, each service reacts to the event of the step before it. No service is in charge, and the flow lives in no one place, so changing its order touches several teams. Orchestrate when the flow must be audited and changed as a whole, as payments must be in Chapter 24. Choreograph when each step is one team's reaction to a fact that other teams may also want, and the flow is short.

The Outbox Between Services

Every saga step changes its own database and must tell the next step. Done as two writes, a crash between them loses a step, or announces one that never happened.

The outbox writes the message in the same local transaction as the change. A relay publishes it at least once, and the receiver deduplicates by the message's ID; delivery semantics are the second lesson of Chapter 6, and the relay itself is Backend Deep Dive's lesson on the outbox. Across services, each service owns its outbox, and an orchestrator's commands travel the same way.

How a change across partitions commits, by requirement
The rows can share a partition→One local transaction
No one may see half a change, and one store holds both sides→Two-phase commit, with a replicated coordinator
The steps cross services or outside parties→A saga, with an outbox
Two-Phase Commit vs Saga

Two-phase commit makes the change atomic and invisible until it is whole, and holds locks on every participant for at least two round trips. Use it inside one store that replicates its coordinator, when no one may ever see half a change.

A saga commits each step on its own and compensates on failure, so the steps in between are visible. Use it when the steps cross services or outside parties that will never join a protocol, and the product can show a pending state.

How Interviewers Probe This

The first probe is "Accounts are sharded, and a transfer moves money between two accounts on different shards. How?" A good answer first asks whether the two can share a partition. When they cannot, it chooses between two-phase commit in a store that replicates its coordinator and a saga that debits the sender into a pending hold and then credits the receiver, with a refund as the compensation. It names the cost of each: locks for two round trips, or a visible state in between.

The second is "The coordinator crashes after every participant has prepared. What happens to those rows?" A good answer says the participants are in doubt and keep their locks, so the rows block until the decision is known, and removes the cause: a decision recorded through consensus.

The third is "The credit step of your saga fails after the debit committed. What does the user see?" A good answer separates a failure that will pass, where the credit is retried because it is idempotent, from one that will not, where the debit is refunded. It says the user saw a pending transfer, never a lost one, and keeps the total of the money unchanged at every step. You might say: "The money sits in pending, so the books balance at every step. I retry the credit, and if the receiver's account is closed, I refund the sender."

Misconceptions
  • "Two-phase commit gives one effect across all my services." It covers only participants that speak the protocol. A card processor or an email provider does not, and stays outside it.
  • "A saga is a distributed transaction." It is atomic per step, not as a whole, and other requests see the states between the steps.
  • "A compensation undoes the step." It restores an acceptable state. A refund leaves a charge and a refund on the statement, and the debited balance was visible in between.
  • "A participant that voted yes can time out and abort." It promised to commit if told to, and another participant may already have committed, so it must wait for the decision.
  • "Publishing the event right after the commit is good enough." A crash between the commit and the publish loses the step for good. The outbox makes them one write.
Why It Matters
  • Choose the partition key so that the transactions the product needs stay on one partition, and name the one that cannot.
  • Use two-phase commit only inside a store that replicates its coordinator, and say how long it holds locks.
  • Write the compensation for every saga step before the first step ships, and put the step that cannot be compensated last.
  • Send every saga message through an outbox, and make every receiver deduplicate by message ID.
RelatedBackend Deep Dive one service's saga, the outbox relay, idempotency keysPostgreSQL Deep Dive prepared transactions left behindPicking the Partition Key keeping rows togetherDelivery Semantics at Scale at least once, deduplicated

Knowledge Check

Orders and their items must be written together. What removes the need for a transaction across partitions?

  • Partition orders and their items by customer, so they share a partition
  • Partition items by their own ID, so that writes spread over every node
  • Write the items first and the order after, so a crash leaves no order
  • Put a cache in front of both tables, so the two writes appear together

In two-phase commit, why can a participant that voted yes not simply abort when the coordinator goes quiet?

  • Because its locks were released at the vote and cannot be taken again
  • Because another participant may already have been told to commit
  • Because the coordinator retries the prepare until every vote arrives
  • Because the protocol forbids any abort once the prepare has started

A saga debits the sender, then credits the receiver. What does it expose, and how is that contained?

  • Nothing, because each step commits in a transaction that hides the rest
  • A lost transfer, contained by a lock on both accounts for the whole saga
  • The state between steps, contained by a pending hold that others respect
  • A double credit, contained by putting the credit before the debit

A payment flow's order must be audited and changed in one place. Which saga style fits?

  • Choreography, because no single service then becomes a bottleneck
  • Neither, because a saga cannot be audited once its steps have committed
  • Choreography with a shared log, so every service sees every event
  • Orchestration, with one service that holds the saga's state

A saga step commits to its database, then publishes an event. Why replace that with an outbox?

  • Because publishing first and committing second is the safer order
  • Because a crash between the commit and the publish loses the step
  • Because a broker cannot deliver an event more than once per message
  • Because the outbox makes the whole saga atomic across all services

You got correct