Library

Volume 1 · Microservices, APIs & Event-Driven Architecture

Notebook
Sign in

Section 11

Data Consistency in Distributed Systems

1,251 words · about 6 min

11.1 Two-Phase Commit (2PC) vs Saga

Two-Phase Commit (2PC) Saga
Consistency Strong (atomic across all participants) Eventual
Availability Low — blocks all participants until commit/abort resolves High — no global lock held
Performance Slow — coordination overhead, holds locks throughout Good — each local transaction commits immediately
Failure handling Rollback (built into the protocol) Compensating transactions (application-defined)
Complexity Needs a transaction coordinator that all participants trust and support (XA) Business logic must define compensation for every step
Coordinator SPOF Yes — coordinator crash mid-commit can leave participants blocked (“in doubt”) No single coordinator required (choreography) or coordinator is just orchestration, not a distributed lock holder
Recommendation Within a single database / tightly coupled systems only Standard choice for microservices

2PC works in two phases: Prepare (coordinator asks all participants “can you commit?”, each locks resources and replies yes/no) and Commit (if all said yes, coordinator tells everyone to commit; if any said no, everyone rolls back). The blocking nature and requirement that every participant support XA transactions makes it a poor fit for microservices with heterogeneous datastores and message brokers — hence Saga’s dominance in that world.

11.2 Change Data Capture (CDC)

CDC captures row-level changes from a database’s transaction log (WAL in Postgres, binlog in MySQL) and streams them as events, without requiring the application to explicitly publish anything.

┌─────────────┐   WAL/binlog   ┌───────────┐   Kafka topic   ┌─────────────┐
│  PostgreSQL  │───────────────▶│ Debezium   │─────────────────▶│  Consumers   │
│  (Orders tbl)│  tail the log  │ connector  │  per-table topic  │ (search idx, │
└─────────────┘                └───────────┘                    │  cache, etc) │
                                                                  └─────────────┘

Use cases: implementing the transactional outbox with lower latency than polling; keeping a search index (Elasticsearch) or cache in sync with the source-of-truth DB without dual writes; feeding a data lake/warehouse incrementally; building event streams out of legacy systems that can’t be modified to publish events themselves.

# Debezium connector config (captures Orders table changes into Kafka)
{
  "name": "orders-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "postgres",
    "database.dbname": "ordersdb",
    "table.include.list": "public.orders,public.outbox_messages",
    "topic.prefix": "orders",
    "plugin.name": "pgoutput"
  }
}

11.3 CRDTs (Conflict-Free Replicated Data Types)

CRDTs are data structures designed so that concurrent updates made on different replicas — with no coordination — can always be merged deterministically into the same final state, without conflicts and without a coordinator. They trade a constrained API (only certain operations are allowed) for the ability to accept writes on any replica during a partition and still converge.

Type Guarantee Example
G-Counter (grow-only counter) Merge = element-wise max of per-replica counts Distributed “like” counter
PN-Counter (increment/decrement counter) Two G-Counters (positive/negative), merge each Distributed inventory delta counter
LWW-Register (last-write-wins) Merge = keep value with the higher timestamp Simple “current value” field, accepting last-write-wins semantics
OR-Set (observed-remove set) Adds/removes tagged with unique IDs; merge is deterministic even with concurrent add+remove Shopping cart items across offline devices
RGA / sequence CRDTs Ordered list merges preserving intention Collaborative text editing (e.g., Google Docs-style)

CRDTs power systems like Redis’ (enterprise) CRDT-based active-active replication, Riak, and collaborative editors. They matter architecturally when you need multi-region active-active writes with no cross-region coordination latency and can tolerate the constrained data model.

11.4 Eventual Consistency Patterns

Pattern Description
Read-your-writes A client always sees its own prior writes, even if the rest of the system hasn’t converged yet (e.g., route the client’s reads to the replica it wrote to, or use a session token)
Monotonic reads Once a client has seen a value, it never sees an older value on a subsequent read
Consistent prefix Reads never observe writes out of the order they were made
Bounded staleness Replicas lag the primary by at most K versions or T seconds — a middle ground between strong and full eventual consistency (used by Cosmos DB)

CAP Theorem and PACELC

           Consistency
              /\
             /  \
            / CP \     CP systems: MongoDB (primary reads), Cosmos DB (Strong),
           /______\    single-node SQL Server/PostgreSQL
          /        \
         /    CA    \  CA systems: theoretically only single-node (no partition possible)
        /____________\
       /              \
      /       AP       \  AP systems: Cassandra, DynamoDB, Cosmos DB (Eventual)
     /__________________\

PACELC extends CAP for the normal (non-partitioned) case: “if there’s a Partition, choose A or C; Else, choose Latency or Consistency.”

System Under Partition (P) Normal Operation (E)
Single-node SQL Server/PostgreSQL N/A Consistent
Cosmos DB (Strong) Chooses C Higher latency
Cosmos DB (Eventual) Chooses A Lower latency
Cassandra Chooses A Chooses L (fast reads)
MongoDB Chooses C Chooses C (reads from primary)

Practical takeaway: for financial transactions, choose CP components. For product catalogs, activity feeds, and analytics, AP with eventual consistency is normally an acceptable and much cheaper trade.

11.5 Interview Q&A

Q1: Why do microservices generally avoid 2PC and use Saga instead?

2PC requires a transaction coordinator and every participant to hold locks from the “prepare” phase until “commit” resolves — that’s a blocking protocol, so throughput and availability suffer, and a coordinator crash mid-protocol can leave participants “in doubt,” holding locks indefinitely. It also requires every participant (databases, message brokers) to support XA transactions, which most modern brokers don’t. Saga avoids all of this: each step commits its local transaction immediately and independently, and failures are handled by explicit compensating actions rather than a blocking rollback. The cost is that Saga is only eventually consistent and compensation logic has to be designed deliberately (and isn’t always possible to make perfectly symmetric, e.g., “un-sending” an email) — but for microservices with heterogeneous datastores, it’s the practical choice.

Q2: How would you keep a search index in sync with your primary database without dual writes?

Change Data Capture. Instead of the application writing to Postgres and then separately calling the search service (a dual-write with the same atomicity problem as messaging), I’d use Debezium to tail Postgres’s write-ahead log and stream row changes to a Kafka topic, then have a consumer project those changes into Elasticsearch. This removes the possibility of the two stores diverging due to a failed second write, and it works even for legacy write paths I can’t modify to add an explicit event publish, since it operates purely off the transaction log.

Q3: What’s a CRDT and when would you actually reach for one?

A CRDT is a data structure engineered so that any two replicas’ independent, uncoordinated updates can always be merged deterministically without conflict — e.g., a PN-Counter merges by combining independent increment/decrement counts, an OR-Set resolves concurrent add/remove without ambiguity. I’d reach for one specifically when I need multi-region active-active writes with no cross-region coordination latency and the data model fits the constrained CRDT operations — a good example is a distributed shopping cart or a collaborative editing feature. It’s not a general-purpose consistency tool; most business domains (financial ledgers, anything needing arbitrary invariants) don’t fit the CRDT operation set and need Saga/CP instead.

Q4: Explain the CAP theorem and how it shapes your database choices.

During a network partition, a distributed system must choose between Consistency (every read sees the latest write) and Availability (every request gets a response) — it can’t have both. Single-node SQL databases are “CA” only in the degenerate sense that they can’t experience an internal partition. MongoDB with a replica set is CP-leaning — primary election causes a brief unavailability window rather than serving stale data. Cassandra and DynamoDB are AP — always respond, but a read may be stale. Practically: for financial transactions I choose CP components; for product catalogs, activity feeds, and most analytics, AP with eventual consistency is an acceptable and cheaper trade.