Highlights

Contents

Part X
10

Distributed databases

Copies and shards add new state boundaries. Their protocol determines when another node can expose or own a change. Distinguish replication, distributed commitment, and permitted observations.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Database model2Keys and ER3Algebra and SQL4Dependencies5Storage and indexes6Query execution7Transactions8Concurrency control9Recovery and engines10Distributed databases11Application design12The complete query

#Section 49Replication, lag and promotion

Asha’s booking commits at the primary before a replica shows it. Copies have separate visibility events, so immediate read-after-write needs an explicit policy.

Leader-follower replication gives one leader responsibility for ordering writes and followers responsibility for applying that history. A follower can receive, persist and apply the history at different moments. Replication lag measures the distance between named positions or events, so always say whether the measurement concerns received bytes, durable records or visible changes.

A read between primary visibility and follower application can return old state after a successful write. The figure illustrates that lag, not a fleet-wide constant.

A PRIMARY ORDERS WRITES; REPLICAS FOLLOW ITS HISTORYprimaryreplica Areplica Bcommit acknowledgement depends on the chosen wait policy
Figure 1.57The primary orders reservation writes while followers apply its history. Orange marks the write owner; a follower’s visible version can lag that owner’s commit.

Synchronous and asynchronous acknowledgement

Synchronous replication delays acknowledgement until the configured replica condition is met. That condition may mean receipt, durable flush or replay; those are distinct promises. Asynchronous replication can acknowledge before the follower reaches the required point, reducing waiting while leaving a possible loss boundary under primary failure.

Acknowledgement latency depends on which persistence events the policy requires. Independent completion times share one origin; do not add them as if they were sequential.

ASYNC ACKS AT 5 MS AFTER LOCAL DISK; SYNC WAITS FOR THE REPLICA UNTIL 12 MSASYNC ACKS AT 5 MS AFTER LOCAL DISK; SYNC WAITS FOR THE REPLICA UNTIL 12 MSprimaryreplica012345678910111213mslocal fsyncship, replica fsyncasync ack 5 mssync ack 12 ms12 − 5 = 7 ms extra wait
Figure 1.58Illustrative persistence times. Orange marks the synchronous wait for the last required acknowledgement at 12 milliseconds; the local-only boundary is 5.

Read replicas and failover

For read-your-writes, Asha can read the leader, carry a committed position and wait for a follower to reach it, or receive a stated temporary failure. Blindly round-robin reading across copies supplies no such guarantee. Promotion also needs a follower whose history meets the durability promise and a way to exclude the old writer. A network partition does not prove the old process stopped.

PostgreSQL 18’s standby documentation describes streaming replication and its acknowledgement choices. Keep that concrete engine contract separate from the toy timing arithmetic. A replica is also not a backup against every failure; an unwanted deletion can propagate faithfully to all copies.

#Section 50Partitioning, sharding and resharding

One popular festival can dominate Heron’s writes. Replicas do not divide write ownership; sharding independent records can.

Vertical partitioning splits columns or related tables, often separating frequently read seat state from larger descriptive fields. Horizontal partitioning splits rows by a rule. Sharding places such subsets under separately managed storage owners. A table partition inside one database and a shard on another machine can use similar row rules while having different transaction boundaries.

Range, hash and directory-based sharding

A range shard owns a key interval, making ordered scans local when the query follows that interval. A hash shard owns keys selected by a hash mapping, trading ordered locality for spread under the hash model. Directory-based sharding keeps an explicit key-to-owner lookup, allowing controlled placement at the cost of maintaining that directory. Consistent hashing limits which hash ranges change owner when membership changes; it does not perform the data transfer by itself.

Evenly distributed rows need not imply evenly distributed requests. A popular show can overload its owning shard despite a balanced row-count plan.

EQUAL ROW COUNTS AND A HOT-SHARD DISTRIBUTION HAVE DIFFERENT SHAPESEQUAL ROW COUNTS AND A HOT-SHARD DISTRIBUTION HAVE DIFFERENT SHAPESequal distributionP0: 200P1: 200P2: 200P3: 200skewed workloadP0: 650P1: 50P2: 50P3: 50total 800 rowseach dot represents 10 rows; both distributions total 800 rows
Figure 1.59Illustrative equal and skewed distributions of the same 800 rows. Orange marks the first shard, whose 650-row skew differs from the 200-row equal share.

Hot shards, cross-shard queries and joins

Choose a key from the operations that must stay together. A show-based key keeps one show’s seat reservation local but concentrates a popular show. A country key may concentrate most users in one country. A query across shows needs fan-out and result merging, while a cross-shard join may transfer rows or maintain another read model. Neither cost appears in a single-shard index lookup.

Resharding transfers data while requests continue under a defined ownership version. Copy a snapshot, catch up intervening changes, establish the handoff boundary and route new operations to the new owner. Fence stale writers and retain a recovery path until the handoff is durable. Updating the route before catching up can expose missing rows; copying without capturing new writes can lose changes.

MOVING A SHARD: COPY THE DATA, CATCH UP, FENCE THE OLD OWNER, THEN SWITCH THE ROUTEMOVING A SHARD: COPY THE DATA, CATCH UP, FENCE THE OLD OWNER, THEN SWITCH THE ROUTEold shardnew shardrouter1 snapshot copy at a recorded log position2-3 stream later changes until caught up4 fence: old generation rejected,only the new owner may write5 new writes6 retire the old copy only after its obligations are done
Figure 1.60A snapshot copy is followed by change catch-up and a fenced ownership handoff. Orange marks the fencing step that excludes the old writer before the new owner accepts writes.

#Section 51Distributed transactions and two-phase commit

Inventory and credit on separate shards cannot be committed together by a transaction local to one shard. A partial distributed outcome needs another protocol.

Two-phase commit, or 2PC, asks participants to prepare durably before one coordinator decision. A YES voter cannot unilaterally discard its promise because the coordinator disappears; it needs the durable commit or abort outcome.

TWO-PHASE COMMIT: VOTES THEN ONE DURABLE DECISIONcoordinatorDB ADB Bpreparepreparedurable YESdurable YESlog COMMITafter YES, a participant cannot guess an outcome alone
Figure 1.61Prepare establishes durable participant promises before the coordinator records COMMIT. Orange marks protocol actions; a participant with a YES vote must recover the authoritative decision rather than guess.

Coordinator failure and blocking

Suppose both participants vote YES and the coordinator disappears before either learns the outcome. The coordinator may have logged COMMIT and sent it to only one participant. A participant that guesses ABORT could disagree with that committed outcome. Prepared state can therefore remain blocked, retaining locks and resources until the decision is recovered through the protocol.

2PC coordinates atomic commitment; two-phase locking controls concurrent access. A system can use both, and a blocked prepared transaction can retain costly locks.

Sagas, transactional outbox and eventual consistency

A saga divides a business workflow into locally committed steps with specified compensating actions when later steps fail. A compensation is a new business operation, not a time machine that erases every externally observed action. Refunding a payment does not make its original notification disappear.

A transactional outbox writes publication intent in the same local commit as the booking. A relay later sends the event and may repeat it after a lost acknowledgement. The consumer needs stable identity and duplicate-safe effects. This closes the local database-to-message gap while downstream completion may remain eventual.

THE OUTBOX: THE SEAT CHANGE AND THE EVENT COMMIT TOGETHER; DELIVERY HAPPENS LATER, MAYBE TWICETHE OUTBOX: THE SEAT CHANGE AND THE EVENT COMMIT TOGETHER; DELIVERY HAPPENS LATER, MAYBE TWICEone local transactionseatsoutboxA7 = heldevt 91COMMITpublisherbrokerconsumerseen ids89 90 919191publisher crashed after sending: 91 arrives twice, the consumer skips it
Figure 1.62Reservation state and publication intent share one commit. Orange marks that local boundary; later delivery can repeat and requires consumer deduplication.

For Heron, keep the seat claim and booking record in one transaction when they share a database. Introduce distributed commit only when atomicity truly spans separate participants. An external payment API may instead require a durable pending state, a stable payment operation identity and reconciliation. Naming the desired business outcome comes before choosing a commit protocol.

#Section 52Consistency models and quorums

Asha sees a held seat on one replica and free on another. A consistency contract must describe observations across operations, not simply replica count.

Linearizability makes each operation appear to take effect at one point between its call and return, respecting real-time order. This is the strong single-operation meaning used here. Eventual consistency requires replicas to converge under the stated assumptions once new changes stop. Causal consistency preserves the order of causally dependent operations. Read-your-writes prevents a session from missing its own acknowledged changes, while monotonic reads prevent that session from returning to an older observed state.

Quorum intersection

A quorum requires a set of responses. Intersecting read and write sets ensure some shared replica, while ordering and conflict rules still come from the protocol.

Read this as the minimum overlap between a read set of size R and a write set of size W inside the same N-member replica set. If R+W>NR+W>N, disjoint sets would require more distinct members than exist. The inequality is a counting fact; it does not specify how a reader resolves versions or how concurrent writes are ordered.

N = 3, W = 2, R = 2: ANY WRITE SET AND READ SET SHARE AT LEAST 1 REPLICAN = 3, W = 2, R = 2: ANY WRITE SET AND READ SET SHARE AT LEAST 1 REPLICAreplica Areplica Breplica Cwrite set {A, B}read set {B, C}R + W − N = 2 + 2 − 3 = 1overlap guarantees the read sees the write; versions pick the newest value
Figure 1.63Illustrative write set A,B and read set B,C intersect at B. Orange marks the shared replica; version and protocol rules are still required to select the right value.

Sloppy replacement sets, changing membership or responses that omit the durable version can break the assumed intersection. Even fixed intersecting sets need a correct ordering and read protocol to claim linearizability. A quorum reader that picks the first response can ignore the newer value from the shared replica. Multi-operation serializability is another guarantee and cannot be obtained by quoting this inequality.

For Asha, carry the observed reservation version when selecting a replica and define whether to wait, route elsewhere or fail when it is unavailable. The contract names which observation is permitted. Replica count then supports that contract through a concrete protocol rather than supplying a universal consistency adjective.