In this lesson, you will learn how to implement linearizability to ensure that every read operation in a distributed cluster returns the most recent successful write.
The Linearizability Guarantee
In a distributed system, maintaining a single global state is challenging because nodes communicate over networks that suffer from latency and partitions. If you write a value to a database, you want to ensure that any subsequent read—regardless of which node performs the operation—sees that new value. This is the essence of Linearizability, the strictest consistency model.
When a system is linearizable, operations appear to happen instantaneously at some point between their invocation and their completion. This effectively makes the distributed database behave as if it were a single-node system.
Achieving Linearizability
To implement linearizability, the system must coordinate across nodes to establish a strict ordering of operations. A common approach is using a Consensus Protocol (like Raft or Paxos) or a Primary-Secondary model with strict read/write quorums.
Consider a simple SQL-like abstraction where we force a read to synchronize with the current leader:
-- Standard read might be stale due to replication lag
SELECT balance FROM accounts WHERE id = 101;
-- Linearizable read ensures we sync with the commit index
SELECT balance FROM accounts WHERE id = 101
USING CONSISTENCY 'LINEARIZABLE';
In the background, USING CONSISTENCY 'LINEARIZABLE' triggers a "Read Index" or "Lease" mechanism. The database ensures that the node serving the read has the latest state by confirming its leadership status with a majority of the cluster before returning the result. This prevents "stale reads" where a user might see an old account balance simply because they queried a follower node that hasn't processed the latest transaction log yet.
The Trade-off
While this provides the strongest safety guarantees, it comes at a cost. Linearizable systems prioritize consistency over availability during network partitions (as dictated by the CAP Theorem). Because every read must coordinate with the majority of nodes, latency will increase compared to "eventual consistency" models, and the system may become unresponsive if a quorum cannot be reached.
Key Takeaway: Linearizability forces distributed nodes to reach consensus on the state of data, ensuring that reads always reflect the latest write at the expense of higher latency and reduced partition tolerance.