Part 11 of 12 · Databases

How do you keep two systems consistent without distributed transactions?

An order in one database, its payment in another, and a process that can die between them. Dual writes, two-phase commit, sagas and the outbox, each run 1,000 times with crashes injected: what goes wrong, what recovers, and what two-phase commit's in-doubt transactions block.

Two people shaking hands over euro banknotes, a deal both sides must keep

The verdict, which a thousand staged crashes will prove: you can’t make two separate systems commit at the same instant, so pick which kind of inconsistency you can live with, and make sure something always repairs it:

  • Writing to both one after the other (“dual write”) leaves a permanent mismatch every time the process dies in between.
  • Two-phase commit never shows a half-done state, but a crash leaves in-doubt transactions that hold locks until someone resolves them.
  • A saga commits each step on its own and undoes completed steps with compensating actions. You see intermediate states, and need a recovery job.
  • An outbox commits the change and “what must happen next” in one local transaction, then delivers it at least once, to a consumer that ignores duplicates. That’s the default I’d reach for.

The case looks like this: an order says confirmed, the payment system has never heard of it, and nobody can say when the two stopped agreeing. I find this one of the best problems in backend engineering, because the honest answer isn’t “make it impossible to fail”. It’s “accept that it will fail, and design the repair in from the start”. Let’s see how each suspect holds up when the crashes are real.

I ran each strategy 1,000 times with crashes injected. The code is in database-tradeoffs-lab (make twosys).

Case file

The case An order says confirmed, and the payment system has never heard of it
Suspects Dual write, two-phase commit, saga, outbox
Culprit A process that dies between two separate commits
The fix An outbox in one local transaction, delivered at least once to an idempotent consumer
Evidence 1,000 orders per strategy with crashes injected, make twosys

The four suspects, measured #

The setup: an order in one PostgreSQL database, its charge in another. For each of 1,000 orders:

  • a 5% chance of a crash at every point where a crash would hurt;
  • 5% of cards declined.

A “crash” stops the flow with nothing cleaned up, as if the process died.

Strategy Crashes Inconsistent before recovery Left behind Inconsistent after recovery Time
Dual write: commit the order, then the charge 47 47 - 47 (nothing repairs them) 1.6 s
Two-phase commit: prepare both, record the decision, commit both 139 0 223 in-doubt transactions holding locks 0 4.8 s
Saga: order pending → charge → confirmed; cancel on decline 96 47 96 orders stuck pending 0 2.5 s
Outbox: order + outbox row in one transaction; a relay charges, idempotently 51 (in the relay) all, until the relay runs 48 charges delivered twice, absorbed 0 2.7 s

“Inconsistent” means a confirmed order with no charge, or a charge for an order that isn’t confirmed. Crashes and declines come from fixed seeds, so the counts repeat.

Chart: Inconsistent orders after recovery, 1,000 orders eachChart: Inconsistent orders after recovery, 1,000 orders each
Diagram source
xychart-beta
  title "Inconsistent orders after recovery, 1,000 orders each"
  x-axis ["Dual write", "Two-phase commit", "Saga", "Outbox"]
  y-axis "inconsistent orders" 0 --> 47
  bar [47 , 0 , 0 , 0]

Suspect 1, dual write: the bug everyone writes first #

It’s worth starting here, because it looks so reasonable.

INSERT order (confirmed)   -- commit
    -- crash here = an order nobody paid for
INSERT charge              -- commit

Every crash between the two commits left a confirmed, unpaid order: 47 crashes, 47 permanent inconsistencies. Nothing in the design ever notices. Swapping the order of the writes is a false lead: it only swaps the bug, giving you a charge for an order that doesn’t exist.

Suspect 2, two-phase commit: consistent, and stuck when it fails #

Two-phase commit is a careful protocol, and its failure mode is instructive.

Each database first prepares: it does all the work and promises it can commit, holding its locks. Then a coordinator records its decision durably and tells both to commit. PostgreSQL supports this with PREPARE TRANSACTION and COMMIT PREPARED. It’s disabled by default (max_prepared_transactions = 0).

  • No half-done state was ever visible: zero inconsistencies before recovery. On that evidence alone, it looks innocent.
  • But every crash after a prepare left an in-doubt transaction: 223 of them by the end. The databases can’t decide on their own, because the coordinator may have told the other side to commit. A recovery process read the recorded decisions and finished them all: commit if a decision was recorded, abort if not.
  • In-doubt transactions hold their locks. Another session trying to update an order held by one waited until its lock_timeout (2 s) and failed. It would have waited for as long as the transaction stayed in doubt: minutes, if your coordinator is down. Prepared transactions also survive server restarts, and they hold back VACUUM’s cleanup like any old transaction.
  • They can stop 2PC entirely. In my first run, the limit was 50. In-doubt transactions used it up, and at order 207 PostgreSQL refused to start any new two-phase commit: “maximum number of prepared transactions reached”.
  • It was the slowest: two extra round trips per database, plus the decision write. Across real networks, the gap grows.

Two-phase commit works inside a system built around it: a database’s own distributed transactions, or XA within one vendor’s stack. Between your services and third parties it’s rarely available, and a payment provider won’t prepare a transaction for you.

Suspect 3, saga: steps, and compensations #

Each step commits on its own. If a later step fails, earlier ones are undone by compensating actions, which are new actions, not rollbacks: cancel the order, refund the charge. The pattern goes back to Garcia-Molina and Salem (1987), and the nearly forty-year-old idea is still the cleanest way to think about long business processes.

  • Intermediate states are visible. Every order existed as pending for a while, so readers and other services must understand pending.
  • Crashes leave sagas half-way: 96 orders stuck pending, 47 of them already charged. A recovery job looked at each stale pending order and asked the payment system what had happened. If it was charged, the job confirmed the order; if not, it cancelled it. After that, all 1,000 were consistent.
  • Every step must be safe to retry, because recovery may repeat a step that actually succeeded. Here the charge was idempotent on the order ID, the way a payment provider’s idempotency key works (Stripe’s Idempotency-Key header, for example).

Suspect 4, the outbox: one local transaction, delivered at least once #

The order and an outbox row (“charge order 42 for 37”) commit in the same local transaction, so they exist together or not at all. This is the reveal, and it’s a beautiful sleight of hand: it turns a distributed problem back into a local one, which the database already solves. A relay reads unsent outbox rows, performs the charge, and marks the row sent.

Sequence diagramSequence diagram
Diagram source
sequenceDiagram
  participant App
  participant DB as Orders database
  participant Relay
  participant Pay as Payment system
  App->>DB: one transaction: order + outbox row
  Relay->>DB: read unsent outbox rows
  Relay->>Pay: charge, idempotent on the order ID
  Relay->>DB: mark the row sent
  Note over Relay,Pay: A crash before marking means a second delivery, which the charge absorbs
  • Before the relay runs, nothing is charged. That’s by design: the system is eventually consistent, and “eventually” is how far behind the relay is.
  • The relay crashed 51 times, often after charging but before marking the row sent. The next run delivered those rows again: 48 duplicate deliveries, all absorbed because the charge is idempotent on the order ID. The end state: 0 inconsistencies.
  • The rules: the consumer must be idempotent; alert on the age of the oldest unsent row; and if events must stay in order per order, the relay must keep that order.

My event-driven reference runs this pattern for real, with SQS, SKIP LOCKED relays and a deduplication table on the consumer. The queue post measures its throughput.

Here’s how that plays out in three pairings you’ll meet sooner or later.

Case 1: order + payment #

What I’d use: an outbox, or a saga with an orchestrator, and always an idempotency key on the payment call. Show the user “processing” until the charge confirms. If the card is declined, cancel the order (the compensation). Run a reconciliation job that compares orders with the provider’s records daily, because something will eventually slip through. The payments post is the next case to read.

Case 2: order + confirmation email #

What I’d use: an outbox. The email must be sent if and only if the order committed. Sending it from the request handler before the commit sends emails for orders that roll back; sending it after the commit loses emails when the process dies. A duplicate email is annoying but harmless, so at-least-once delivery is fine. Pass the order ID as the provider’s idempotency key where it supports one.

Case 3: order + search index (or cache, or analytics) #

What I’d use: an outbox, or change data capture (for example Debezium reading PostgreSQL’s write-ahead log) feeding the indexer. The index is a derived copy, so it can lag by seconds and be rebuilt from the database at any time. Never update the index inside the request as a “second write”: that’s the dual-write bug again, in disguise. The cache post shows the same problem with Redis.

Remember this

  • Dual write: every crash in between is a permanent mismatch.
  • Two-phase commit hides half-done states, but in-doubt transactions hold locks.
  • The outbox turns a distributed problem into a local one: deliver at least once, deduplicate by ID.

What to do on Monday #

  1. Keep things that must change together in one database, and use a local transaction. Most “distributed transaction” problems disappear when the data that must agree lives in one place.
  2. Across systems, use an outbox (or CDC) with idempotent consumers. Deliver at least once, and deduplicate by a stable ID.
  3. Use a saga when a business process spans services and needs compensation (book, charge, ship). Make every step idempotent, and run a recovery job for stuck instances.
  4. Avoid two-phase commit across services. If you do use it within one database cluster, monitor pg_prepared_xacts and have an automated recovery path for in-doubt transactions.
  5. Reconcile. A periodic job comparing the two systems is the safety net under every design here.

What I appreciate most about the outbox and the saga is their humility. They don’t pretend crashes won’t happen; they make sure that when one does, the system already knows how to finish the job.

Measured Nov 2026 on PostgreSQL 17.11 in Docker (both databases on one server), 1,000 orders per strategy, crashes and declines from fixed seeds. Code and full results: database-tradeoffs-lab/10-two-systems.

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.