Implementing Distributed Transactions

1. Understanding ACID Properties in Distributed Systems

PropertyDistributed Challenge
AtomicityCross-node commit requires coordination (2PC)
ConsistencyInvariants across shards may need sagas
IsolationSnapshot/serializable expensive cross-shard
DurabilityReplicated WAL with quorum

2. Implementing Two-Phase Commit (2PC)

2PC Protocol

  1. Prepare: Coordinator asks all participants "can you commit?"
  2. Participants write to WAL, vote YES/NO
  3. Commit/Abort: Coordinator decides based on votes
  4. Participants apply decision and ACK
PropertyValue
BlockingIf coordinator fails after prepare, participants stuck
Latency2 RTTs minimum
Used byXA transactions, MSDTC

3. Implementing Three-Phase Commit (3PC)

PhaseAction
CanCommitVoting phase
PreCommitCoordinator broadcasts intent; non-blocking unblock point
DoCommitFinal commit
LimitationAssumes synchronous network; vulnerable to partitions

4. Understanding Distributed Deadlocks

DetectionMechanism
Wait-for graphCentralized cycle detection
Edge chasingProbe messages around graph
Timeout-basedAbort long-waiting txns (most DBs)
Wound-wait / wait-diePriority by timestamp prevents cycles

5. Implementing Saga Pattern (choreography)

PropertyDetail
MechanismEach service emits events; others react
No central coordinatorLoose coupling
RiskImplicit flow hard to trace; cyclic dependencies
CompensationOn failure, reverse-direction events

6. Implementing Saga Pattern (orchestration)

Example: Orchestrated saga (pseudo-code)

public class OrderSaga {
    public void execute(Order o) {
        try {
            paymentSvc.charge(o);
            inventorySvc.reserve(o);
            shippingSvc.schedule(o);
        } catch (Exception e) {
            // Compensating transactions in reverse order
            try { shippingSvc.cancelIfScheduled(o); } catch (Exception ignored) {}
            try { inventorySvc.release(o); } catch (Exception ignored) {}
            try { paymentSvc.refund(o); } catch (Exception ignored) {}
            throw e;
        }
    }
}
PropertyDetail
Central coordinatorExplicit state machine
ToolsCamunda, Temporal, AWS Step Functions, Netflix Conductor
ProsVisible, testable, easier debugging

7. Implementing Compensating Transactions

ActionCompensation
Reserve seatRelease seat
Charge cardRefund
Send emailSend retraction email
Decrement stockIncrement stock
Note: Compensations must be idempotent and able to handle partial original execution.

8. Understanding Isolation Levels

LevelAnomalies Prevented
Read UncommittedNone
Read CommittedDirty reads
Repeatable Read+ Non-repeatable reads
Snapshot Isolation+ Most anomalies; allows write skew
SerializableAll anomalies
Strict SerializableSerializable + linearizable real-time order

9. Implementing Optimistic Concurrency Control

Example: Version-based OCC

UPDATE accounts
SET balance = balance - 100, version = version + 1
WHERE id = 42 AND version = 7;
-- Affected rows = 0 means concurrent update; retry
Best forAvoid for
Low contentionHigh contention (retry storms)
Short txnsLong txns
Read-heavy workloadsWrite-heavy hotspots

10. Implementing Pessimistic Locking

Lock TypeUse
Shared (S)Multiple readers
Exclusive (X)Single writer
Intent (IS, IX)Hierarchical locking
SELECT ... FOR UPDATERow-level X lock
Two-phase locking (2PL)Acquire growing phase, release shrinking phase

11. Understanding Transaction Coordinators

SystemRole
Spanner TrueTimeGlobally consistent timestamps
Percolator (Bigtable)Snapshot isolation via timestamps
CockroachDBSerializable snapshot via HLC
YugabyteDBHLC + Raft groups