Library
12 min read

Distributed transactions

A travel app sells a trip as one purchase: a sleeper berth, a hotel room, paid from the app's wallet. Three services, three databases. The wallet debits ₹4,200. The berth is held. Then the hotel says it has no rooms left. The customer has been charged for a trip that does not exist, and there is no ROLLBACK that reaches across three databases.

Inside one database this problem was solved decades ago. Across several, you pick one of two very different answers, and each costs something the other does not.

Your answer

Wallet, seats and hotel are separate services with separate databases. The wallet has debited and the seat is held when the hotel refuses. How would you get the customer's money back and free the seat? What could go wrong while you do?

One action, several databases#

A transaction gives you all or nothing, but only inside one database, because only that database's log decides what committed. Once an action spans several databases, or several services that each own one, you need a protocol on top.

Before picking a protocol, ask the cheaper question: does this data need to be in separate databases? If the wallet and the bookings always change together, putting them in one Postgres turns this whole chapter into BEGIN ... COMMIT. A lot of distributed transaction pain is a service boundary drawn in the wrong place, which the monolith vs microservices article covers.

When they really must be separate, you have two options.