Replication, read replicas and the CAP trade-off
Copy data to more machines for reads and for survival, then decide what happens when the copies cannot talk to each other.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
A primary takes every write and streams changes to replicas, which serve reads. Replication is usually asynchronous, so a replica can briefly return old data. When the network splits the nodes, a system must either stop accepting some requests to stay consistent, or keep answering and reconcile later: that choice is the CAP trade-off.
Code
// Writes go to the primary; reads that can be slightly stale go to a replica.
async Task PlaceOrder(Order o) => await _primary.SaveAsync(o);
async Task<Order> MyOrderJustNow(Guid id) => await _primary.GetAsync(id);
async Task<List<Order>> History(int user) => await _replica.ListAsync(user);
// Replication to the replicas is asynchronous: they lag by milliseconds.
// During a network partition, choose: refuse writes (C) or accept them (A).Tips
- Read-your-writes: after a user changes something, read it back from the primary for a short time so they never see the old value.
- CAP is only about behaviour during a partition. PACELC adds the everyday trade-off: latency versus consistency.
- Banking balances lean to consistency; likes, feeds and view counts lean to availability.
In the .NET library
Azure SQL readable secondaries and Cosmos DB consistency levels (strong, bounded staleness, session, consistent prefix, eventual) are this trade-off as settings.