Buildfest Learn System DesignRead and experiment freely · Chapter activities stay in this tab
Practice librarySystem DesignReplication sharding and consistency

LESSON 08 • SYSTEM DESIGN

Replication sharding and consistencyPut data on more machines.
Keep its promises clear.

Replication sharding and consistency. Learn the concepts, explore a model and defend your design.

DEFINITION

Replication copies data across nodes; sharding divides ownership across nodes. Consistency is a contract about which operation histories readers may observe. During network failure, disconnected nodes may need different accept/reject behavior to preserve the required invariant. These are separate decisions that must be explained for the actual operation.

Replication copies; sharding divides
  1. CONCEPTReplicationA B C -> A B C
  2. CONCEPTShardingA B on one; C D on another
  3. CONCEPTCombined designEach shard can have replicas

These solve different problems and can be used together.

CONCEPT 1

Replication makes copies of the same data

Why keep another copy

A replica holds a copy of data so a system may recover from selected failures or serve suitable reads elsewhere. A common arrangement has a primary accepting writes and replicas receiving changes. A copy is useful only under a clear rule about what is copied, when it becomes visible and which node may become the next writer.

Synchronous and asynchronous copying

With asynchronous replication, a write may be acknowledged before a replica has received it. That can keep the write path short but leave a data-loss or stale-read window under particular failures. A synchronous arrangement waits for a configured replication condition before reporting success. It trades latency and write availability against a specific durability contract, not an unlimited promise that no failure can ever lose data.

Reading your own new answer

Riya saves an exam answer on the primary, then reads from a replica that has not caught up. The old answer appears, which feels like data loss even if the primary has the new value. Read-your-writes behavior can route that session to the primary or wait for an appropriate version. Choose the user-visible promise before load-balancing reads across copies.

CONCEPT 2

Sharding splits ownership instead of copying it

A useful distinction

Replication makes copies of overlapping data. Sharding splits a dataset so different instances own different parts. Think of several libraries each storing different groups of books, versus several branches holding copies of the same collection. In-table partitioning can help manage and query data without necessarily introducing independent database servers. State which kind of partitioning you mean.

Choose the key carefully

A shard key determines where a record belongs. Using user_id may keep one user's records together. Using time ranges may make time-based scans convenient. Hashing many varied keys can spread ownership, but makes range scans less direct. The key influences joins, transactions, uniqueness and the work needed to move data later.

A hot shard changes the average

Suppose 100 shards handle 1 million requests per second. An even split suggests 10,000 requests per shard. If one celebrity user attracts 20 percent of all requests and that user's key lives on one shard, that shard gets at least 200,000 requests per second. Adding more shards does not automatically divide a single hot key. You may need caching, a different key or a special path for that workload.

A partition key routes data ownership
  1. STEP 1Record keystudent_id = 42
  2. STEP 2Routing functionChoose the owning shard
  3. STEP 3Shard ownerProcess that key under a policy

Hot keys and uneven key distributions can overload one shard despite spare capacity elsewhere.

CONCEPT 3

Consistency describes what users can observe

One word with several contracts

If Riya changes her profile photo, how quickly must everyone see the new photo? If two users buy the final ticket, can both be told yes? These operations may need different consistency rules. Stronger consistency often requires more coordination. Eventual consistency allows temporary differences under a rule for convergence; the product must decide which temporary differences are acceptable.

Linearizability and causal order

Linearizability makes operations appear to take effect one at a time in an order that respects real time. If one write completed before a later read began, the read must fit that contract. Causal consistency preserves relevant cause-and-effect relationships, such as a reply not appearing without the action it depends on. These definitions are different from simply observing fast responses or having several copies.

Resolve conflicts intentionally

Two disconnected users might edit the same description. Last-writer-wins can choose one update according to an ordering rule, but may discard meaningful work. Merging fields or asking the user to resolve conflict may be better. A physical clock is not a perfect record of cause and effect. The solution depends on the type of data and the invariant you need.

Replica lag changes the reading experience
  1. STEP 1WritePrimary accepts new profile
  2. STEP 2Immediate readLagging replica shows old value
  3. STEP 3Later readReplica catches up

Choose a documented read policy when a user must immediately observe their own accepted update.

CONCEPT 4

CAP and consensus without the slogan

A partition is a communication failure

Imagine three replicas. Two can talk to each other, while one is isolated by a network failure. The isolated machine might still answer clients. Should it accept a purchase if it cannot coordinate with the other side? If both sides independently sell the same final ticket, they can violate the business rule.

What CAP is saying

Under specific formal definitions, a partition creates a conflict between linearizable consistency and availability in the sense that every request to a non-failing node gets a response. It is not a universal instruction to pick any two words for every application. A design can choose different behavior for different operations. Refusing an uncertain purchase may protect correctness, while an approximate view counter can tolerate temporary differences.

How agreement helps

Consensus protocols help nodes agree under stated assumptions. A majority-based system may continue on the two-node side while rejecting writes on the isolated side. Safe leadership changes still need a protocol; a timeout alone cannot prove the old leader stopped. Read/write quorum overlap is a useful idea, but by itself does not prove linearizability or safe concurrent updates. For application work, rely on reviewed implementations instead of inventing a new consensus algorithm casually.

A network split creates a coordination decision
  1. CONCEPTGroup ACannot hear group B
  2. CONCEPTDecisionCoordinate or limit some operations
  3. CONCEPTGroup BCannot hear group A

For a single final-seat invariant, independently accepting both sides can break correctness. CAP concerns behavior during a partition.

Key learning points

  • A replica can lag, and failover must establish a safe authority.
  • A shard key determines locality, skew and migration cost.
  • A hot key can overload one shard despite an even record distribution.
  • Choose observation guarantees per operation, not from a universal database slogan.
  • A backup preserves recoverable history; a current replica may copy an accidental deletion.

Compare the important ideas

Replication sharding and consistency: concepts and trade-offs
ConceptMain questionImportant consequence
Asynchronous replicationCan acknowledgment precede copying?Lag and recent-write loss exposure may exist
Synchronous conditionWhich copies must acknowledge?Latency and availability depend on that condition
ShardingWhich node owns this key?Routing, hotspots and rebalancing need design
LinearizabilityDo histories respect atomic real-time order?Coordination and availability choices matter
Eventual convergenceHow do temporary differences reconcile?Conflict policy and product semantics must be explicit
CAP partition caseWhat happens when nodes cannot communicate?Specify which operations reject or continue

WORKED EXAMPLE

Protect the final ticket during a partition

Three replicas split into a connected pair and one isolated node. A reviewed majority-based authority may allow the connected pair to continue selected writes while the isolated node refuses them. Allowing both sides to independently sell the final ticket can violate the invariant. An approximate view counter may use a weaker contract. Mere read/write quorum overlap does not by itself prove safe failover or linearizability.

Further reading

Original teaching explanations by Buildfest Learn. Check these primary references for the underlying concepts and implementation details.