Quick revision
The short answer
Two-phase commit gives true atomicity across shards but holds locks while it waits, blocks if the coordinator fails mid-protocol, and is poorly supported by many cloud setups and connection pools. A saga debits in one local transaction and credits in another, compensating with a refund on failure; it needs idempotent steps, an outbox for reliable events and visible intermediate states. Redesigning the data, either as a ledger where the transfer is one record and balances are derived, or by keeping both accounts on one shard, avoids the two-shard update altogether. For money, auditability and reconciliation matter as much as atomicity.
What to remember
In this answer, we compared ways to move money between accounts on different shards. Two-phase commit is atomic but blocking, lock-heavy and poorly supported in many cloud setups. A saga commits local steps with compensations and needs idempotent steps, an outbox and an honest pending state. A ledger records the transfer as one entry on one shard and derives balances, and co-locating accounts by customer turns many transfers into local transactions. For money, we choose designs with local atomic steps, and treat auditability and reconciliation as requirements.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Two-phase commit gives true atomicity across shards but holds locks while it waits, blocks if the coordinator fails mid-protocol, and is poorly supported by many cloud setups and connection pools. A saga debits in one local transaction and credits in another, compensating with a refund on failure; it needs idempotent steps, an outbox for reliable events and visible intermediate states. Redesigning the data, either as a ledger where the transfer is one record and balances are derived, or by keeping both accounts on one shard, avoids the two-shard update altogether. For money, auditability and reconciliation matter as much as atomicity.
Why this question is asked
Moving money between two accounts is the textbook example of a transaction, and sharding breaks the textbook: when the two accounts live on different shards, no single database can commit both changes atomically. Interviewers ask this comparison because it tests distributed transactions, failure handling and domain design at once, and because the money context forces us to think about audit and correctness, not just throughput. In this answer, we will state the problem, look at two-phase commit, walk through a saga with compensation and idempotency, then see how a ledger design or co-locating accounts changes the problem, and finish with how to choose.
1The Problem
We must subtract 100 from account A on shard 1 and add 100 to account B on shard 2. On one database, both updates run in one transaction and commit together. Across shards, each database can commit only its own part. If shard 1 commits the debit and shard 2 then fails before the credit, money has left A and never arrived at B. Every design below is a way to prevent that state, or to detect it and repair it, without losing track of a cent.
2Option 1: Two-Phase Commit
Two-phase commit (2PC), standardised for Java as XA through JTA, adds a coordinator. In phase one, the coordinator asks each shard to prepare: do the work, write it durably, hold its locks, and promise it can commit. In phase two, if every shard voted yes, the coordinator tells all of them to commit; if any voted no, it tells all to roll back. The result is genuinely atomic.
The costs are significant. Locks on both rows are held across network round trips and until the coordinator's decision, which lowers throughput on hot accounts. If the coordinator crashes after the shards prepared but before it sent the decision, the shards are stuck holding locks on in-doubt transactions until the coordinator recovers, which is why 2PC is called a blocking protocol. Operationally, many managed databases and proxies restrict or do not support prepared transactions (PostgreSQL needs max_prepared_transactions above zero, which is off by default), connection pools in transaction mode such as PgBouncer cannot carry them, and a JTA transaction manager such as Narayana or Atomikos becomes a critical component. Spring Boot's built-in JTA support has changed between versions, so check yours for the supported transaction managers.
7 messages in order. Play them, or step through them one at a time.
If the coordinator dies after the votes, both shards wait with locks held.
3Option 2: A Saga With Compensations
A saga breaks the transfer into local transactions, each committed on its own shard, and defines a compensating action for each step. Step one, on shard 1: debit A and record the transfer as DEBITED. Step two, on shard 2: credit B and record CREDITED. If step two fails permanently, for example because B is closed, the compensation runs on shard 1: refund A and mark the transfer FAILED. There is never a lock held across shards.
The steps are connected by reliable messages. In step one, the debit and an outbox row containing a TransferDebited event are written in the same local transaction, so they commit together; a relay or CDC process then publishes the event to Kafka. Shard 2's consumer performs the credit. Because messages can be delivered more than once, every step must be idempotent. And because each step commits separately, intermediate states are visible: for a moment, A has been debited and B not yet credited. The application must show that honestly, as 'transfer pending', and balances must account for it.
4Option 3: A Ledger Design
Instead of updating two balances, we record the transfer itself as a single fact. A ledger stores immutable entries: transfer T1 moves 100 from A to B. The entry is written once, on one shard, the shard that owns the transfer. Balances are derived by summing entries, or maintained as cached projections built from the entries. The atomic step is a single insert on a single shard, so there is nothing to coordinate.
The derived balances on each account's shard are updated asynchronously from the ledger, and a check such as 'enough funds' needs care, usually by reserving funds or by having the ledger shard own the balance of the accounts it debits. Ledgers fit money especially well, because they are append-only, every cent has a history, and reconciliation is a sum: debits and credits across the whole ledger must total zero.
5Option 4: Keep Both Accounts on One Shard
Often the simplest fix is in the shard key. If most transfers are between accounts of the same customer, such as moving savings to checking, sharding by customer_id rather than account_id puts both accounts on one shard, and those transfers become ordinary local transactions. Transfers between different customers still need one of the other options, but if they are 10 percent of the volume, the hard path is used much less often. This is worth checking with real data before building anything.
6Choosing for Money
For money, I would prefer designs where the atomic step is local: co-locate accounts where the domain allows, and use a ledger or a saga for the rest, with 2PC only in a controlled environment where the transaction manager, databases and network all support it well. Whatever the choice, auditability matters as much as atomicity: every transfer has an id, a state history and immutable records, and a daily reconciliation proves that debits equal credits and that no transfer is stuck in DEBITED. Regulators and finance teams ask 'show me where this money went', and the design must answer that easily.
| Option | Consistency | Main costs |
|---|---|---|
| Two-phase commit (XA) | Atomic | Locks across shards; blocks on coordinator failure; limited support |
| Saga with compensations | Eventually consistent; visible pending state | Idempotency, outbox, compensation logic |
| Ledger entry on one shard | Atomic fact; balances derived | Balance projections; funds checks need care |
| Co-locate accounts | Local transaction | Only for transfers within one customer |
7Follow-up questions
How do you make each saga step idempotent?
Each step is keyed by the transfer id. The credit consumer, in the same local transaction as the credit, inserts a row into a processed_steps table with a unique constraint on (transfer_id, step); if the insert fails on the constraint, the step already happened and the consumer acknowledges the message without crediting again. Alternatively shard 2 keeps its own table of incoming transfers keyed by transfer id, and the consumer inserts into it with ON CONFLICT DO NOTHING in the same transaction as the credit; when no row was inserted, the transfer was already credited and the credit is skipped. Compensations get the same treatment, so a refund can never be applied twice.
What if the compensation itself fails?
It is retried until it succeeds, because it is a local transaction on a shard we control and must eventually complete. Transfers stuck in an intermediate state longer than a threshold raise alerts and appear in the reconciliation report for manual handling.
Is 2PC ever the right choice?
Inside a single vendor's distributed database it is used internally and works well. Across independent databases, it can be acceptable for low volume in a controlled environment, but most teams find sagas or ledgers easier to operate.
8Conclusion
In this answer, we compared ways to move money between accounts on different shards. Two-phase commit is atomic but blocking, lock-heavy and poorly supported in many cloud setups. A saga commits local steps with compensations and needs idempotent steps, an outbox and an honest pending state. A ledger records the transfer as one entry on one shard and derives balances, and co-locating accounts by customer turns many transfers into local transactions. For money, we choose designs with local atomic steps, and treat auditability and reconciliation as requirements.
Open with
Two-phase commit, XA through a JTA transaction manager, gives real atomicity: the coordinator asks both shards to prepare, they lock and vote, then it tells both to commit.
Then, if they want more
But locks are held across network round trips, if the coordinator dies after the prepare the shards hold in-doubt transactions and locks until it recovers, and many managed databases, proxies and pools like PgBouncer in transaction mode don't support prepared transactions well.
A saga instead runs local transactions in steps: debit A on shard 1 and write an outbox event in the same transaction, then a consumer credits B on shard 2, and if the credit fails permanently, a compensation refunds A.
That needs every step to be idempotent, keyed by the transfer id with a unique constraint or a state check, an outbox so events are never lost, and an honest pending state that users and balances can see.
A third option is a ledger: record the transfer once as an immutable entry on the shard that owns it and derive balances from entries, so the atomic step is a single insert.
And often the simplest is to change placement: if most transfers are between one customer's accounts, sharding by customer puts both accounts on one shard and those become local transactions.
For money I would prefer local atomic steps, co-location plus a ledger or saga, and I'd make auditability and daily reconciliation part of the design, because being able to prove where every cent went matters as much as atomicity.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A money transfer must debit an account on shard A and credit an account on shard B....": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/0b69cb4db0/