Hook: Interviewers love this because it tests whether you know the difference between “my transaction succeeded” and “the whole business action succeeded across systems.”
Question: What is a distributed transaction in SQL, and why is it harder than a normal transaction?
Answer: A distributed transaction is one logical transaction that touches more than one database or resource manager, but still needs to behave like one all-or-nothing unit. The hard part is making sure every participant either commits or rolls back together, even if a network link fails or a server crashes. SQL systems usually solve this with two-phase commit, which is reliable but slower and can block during failures.
Interview-Ready Answer: I’d say a distributed transaction is a single business operation that spans multiple databases or services, but still needs atomicity, meaning either everything commits or nothing does. The classic SQL solution is two-phase commit: a coordinator asks each participant to prepare, then only commits if everyone votes yes. It gives strong consistency, but it adds extra network round trips, holds locks longer, and can block if a node crashes at the wrong time, so I only use it when I truly need hard all-or-nothing guarantees across systems.
A distributed transaction is a transaction that spans multiple participants or resource managers (a database, queue, or other system that owns data and locks). The goal is still ACID atomicity: either every participant commits the change, or every participant rolls it back. This is much harder than a local SQL transaction because the coordinator cannot trust one server’s word alone; it has to coordinate and verify every node.
PREPARE. Each participant writes a durable log record saying, “I am ready to commit if asked.” Durable means written to disk so the decision survives a crash.COMMIT to everyone. If any vote is no, it sends ROLLBACK instead.The classic protocol is two-phase commit, or 2PC. It is strong, but it has a blocking problem: if a participant has prepared and then the coordinator disappears before sending the final decision, that participant may have to wait, holding locks, until recovery tells it what to do. That is why distributed transactions are safe but operationally expensive.
| Approach | Atomic? | Failure style | Best for |
|---|---|---|---|
| Local transaction | Yes | Simple rollback | One database |
| Distributed transaction | Yes | Can block | Strict all-or-nothing |
| Saga | No | Compensate later | Microservices |
| Outbox pattern | Per DB only | Retry safely | Reliable events |
Use a distributed transaction when correctness matters more than latency, and when losing atomicity would create money loss, duplicate inventory, or legal inconsistency. Avoid it for chat messages, analytics, or loosely coupled workflows where eventual consistency is acceptable.
2PC is usually O(n) in the number of participants: each participant adds coordination, log flushes, and lock time. In practice, even on a fast LAN, a single extra durable round trip per node can turn a tiny write into tens of milliseconds; across regions, it can become 100 ms or more. That matters because locks stay held while the transaction is prepared, which can reduce throughput and create queueing. In PostgreSQL, two-phase commit exists, but prepared transactions are disabled unless max_prepared_transactions is set above zero; many teams leave it off because dangling prepared transactions are an operational hazard.
Memory model: “Prepare first, decide once, release last.” If you can replay those three ideas, you can reconstruct 2PC under pressure.
Real-World Example: Imagine a checkout service where the orders database lives in one SQL cluster and the inventory database lives in another. A customer clicks “Buy Now,” and the system must create the order row, reserve stock, and record payment state as one business action. If the order commits but inventory fails, the store can oversell. If inventory reserves but the order rolls back, stock gets stuck and nobody can buy it. In production, a misunderstanding here often shows up as “pending” orders that never finish, locks on hot SKU rows, and logs with repeated prepare/timeout messages. Users complain that they were charged but never got confirmation, or that the last few items in stock disappear and never come back until an operator manually cleans up prepared work.
-- Distributed transaction idea, simulated with two logical participants in one SQL session.
-- In a real system these could be two different databases or services coordinated by 2PC.
DROP TABLE IF EXISTS order_service;
DROP TABLE IF EXISTS inventory_reservations;
CREATE TABLE order_service (
order_id INTEGER PRIMARY KEY,
customer VARCHAR(50) NOT NULL,
status VARCHAR(20) NOT NULL
);
CREATE TABLE inventory_reservations (
reservation_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL,
sku VARCHAR(20) NOT NULL,
qty INTEGER NOT NULL CHECK (qty > 0)
);
-- Success path: both logical writes happen together and are committed together.
BEGIN TRANSACTION;
INSERT INTO order_service (order_id, customer, status)
VALUES (1, 'Ava', 'CREATED');
INSERT INTO inventory_reservations (reservation_id, order_id, sku, qty)
VALUES (101, 1, 'SKU-RED-1', 2);
COMMIT;
-- Failure path: if the business decides the unit must not complete,
-- rolling back the whole transaction leaves no partial order behind.
BEGIN TRANSACTION;
INSERT INTO order_service (order_id, customer, status)
VALUES (2, 'Ben', 'CREATED');
INSERT INTO inventory_reservations (reservation_id, order_id, sku, qty)
VALUES (102, 2, 'SKU-BLUE-7', 1);
ROLLBACK;
-- Checkpoint: only the committed work remains.
SELECT * FROM order_service ORDER BY order_id;
SELECT * FROM inventory_reservations ORDER BY reservation_id;Follow-up & Tricky Questions:
COMMIT on each database separately? No, because a failure between the two commits creates split-brain data. That is exactly the bug distributed transactions are meant to avoid.Common Mistakes:
Memory Hook: “Prepare, vote, decide.” Picture a choir: everyone practices first, the conductor asks for a yes, and only then does the whole choir perform. If one singer says no, nobody goes on stage.
Cheat Sheet:
Practice Tasks: