Skip to content

Consistency Patterns

With multiple copies of the same data, we must choose how to synchronize them so clients have a consistent view. (Recall: consistency = every read receives the most recent write or an error.)

There are three main patterns, ranging from strongest to weakest.

Weak Consistency

  • After a write, reads may or may not see it. A best-effort approach is taken.
  • Seen in systems like memcached.
  • Works well for real-time use cases: VoIP, video chat, real-time multiplayer games.

  • Example: on a phone call, if you lose reception for a few seconds, you don't hear what was said during the gap when you reconnect.

Eventual Consistency

  • After a write, reads will eventually see it (typically within milliseconds).
  • Data is replicated asynchronously.
  • Seen in systems like DNS and email.
  • Works well in highly available systems (pairs with the AP choice in CAP).

Strong Consistency

  • After a write, reads will immediately see it.
  • Data is replicated synchronously.
  • Seen in file systems and RDBMSes.
  • Works well in systems that need transactions.

Summary table

Pattern Read-after-write Replication Typical systems Best for
Weak Maybe Best-effort Memcached Real-time, lossy media
Eventual Eventually (ms) Async DNS, email High availability
Strong Immediately Sync RDBMS, file systems Transactions

Common Interview Questions

Design a key-value store (choose a consistency model)

Why it's asked here: the interviewer wants you to pick weak/eventual/strong consistency for a concrete system and justify it.

Key points to discuss:

  • Map the model to the use case: strong for money, eventual for caches/feeds, weak for lossy real-time.

  • Explain read-after-write behavior for each pattern.

  • Sync vs async replication and how it determines the consistency level.
  • Discuss how to upgrade consistency when needed (e.g., quorum reads).
flowchart LR
    W[Write] --> M[Master]
    M -->|synchronous| R[Replica]
    R -->|strong| C[Read sees write]
    M -.asynchronous.-> R2[Replica 2]
    R2 -->|eventual| E[Read may lag]
Design Google Docs (real-time collaboration)

Why it's asked here: concurrent edits are a consistency problem — how do multiple replicas converge?

Key points to discuss:

  • Operational transforms (OT) or CRDTs to merge concurrent edits.
  • Eventual consistency across collaborators, with convergence guarantees.
  • Conflict resolution strategy and why strong consistency would hurt latency.
  • Tie back to weak/eventual consistency being appropriate for real-time editing.
flowchart LR
    A[User A edit] --> S[Sync server]
    B[User B edit] --> S
    S -->|OT / CRDT merge| D[Converged document]
    D --> A
    D --> B

Further reading


Design a Key-Value Store with Tunable Consistency

To design a key-value store correctly, start by defining the workload and the required consistency behavior. Suppose the system must support 50 million daily clients, 100,000 reads per second and 10,000 writes per second at peak, with values averaging 10 KB and about 2 billion keys. The resulting dataset on the order of 20 TB means the store must be partitioned across many storage nodes. The functional requirements are a simple get, put, and delete API, while the non-functional requirements are high availability, low-latency access, tunable strong or eventual consistency, durability for acknowledged writes, and horizontal scalability without taking the entire system offline.

The high-level architecture consists of stateless coordinator nodes in front of a partitioned and replicated storage tier. Clients connect through a load balancer, which spreads API requests across multiple coordinator processes. Each coordinator uses cluster metadata, maintained by a service such as ZooKeeper or etcd, to learn which storage nodes own which key ranges. The key space is divided into partitions with consistent hashing, and every partition is replicated to several storage nodes. A coordinator sends each write to enough replicas to satisfy the requested consistency level and sends each read to a quorum or to the nearest replica depending on the level selected. This arrangement keeps routing logic in the stateless tier and lets storage nodes handle durability and replication.

The data model is intentionally simple. Each record is a key, a value, and version metadata used to detect and resolve conflicts. A durable record contains the key, the serialized value, a timestamp, and a vector clock describing which replicas have observed which writes. If the value is small, it can be stored inline in a log-structured merge-tree; if the value is larger than a threshold, the LSM value can point to object storage. The key-value store uses dedicated storage nodes with local LSM or log-structured engines because this engine provides fast append-heavy writes, acceptable point reads, compaction, and persistence. A relational database is not used because the access pattern requires only primary-key lookups and horizontal partitioning, not multi-row joins or rich queries.

The core mechanism is quorum-based replication. For any given piece of data, the system replicates it to N replicas, accepts a write only when W replicas acknowledge it, and serves a read by consulting R replicas. Strong consistency is achieved by choosing W and R so that W plus R is greater than N, which guarantees that every read set intersects every write set and can observe the newest acknowledged value. Eventual consistency is achieved by writing asynchronously or by using smaller quorums such as W equals one, which lets clients observe stale values while replicas converge. When different replicas observe writes in different orders, the system resolves conflicts with vector clocks or last-write-wins rules. In practice many stores allow clients to pass a consistency parameter on each operation, so the same cluster can serve strong reads for money-like data and eventually consistent reads for caches, sessions, or feeds.

Scaling and availability depend on partitioning, replication, and careful failure handling. Consistent hashing maps keys to partitions and minimizes the amount of data moved when nodes are added or removed. Each partition has primary and secondary replicas, so the failure of one node does not destroy data. A write coordinator may use sloppy quorum and hinted handoff: if the intended replicas are unreachable, it temporarily writes to other healthy nodes, which later forward the data back to the original replicas. Read repair compares values returned by multiple replicas and pushes the newest one to lagging nodes. Anti-entropy background processes continuously compare replicas using Merkle trees to find and fix inconsistencies. Multiple coordinators behind the load balancer are stateless and can be added freely, while the cluster metadata service itself is a small replicated service outside the main data path.

The most important trade-off is consistency versus availability and latency. Strong consistency makes read-after-write behavior immediate, but it requires synchronous replication and can reject operations during a partition because a quorum is unavailable. Eventual consistency improves availability, lowers write latency, and supports multi-region replication, but clients can read stale data and conflicts may need repair. The tunable quorum design gives the application control over this trade-off on a per-operation basis. Another trade-off is consistent hashing with virtual nodes for balance versus the complexity of membership state. Vector clocks provide more accurate causality than simple timestamps but make values larger and conflict resolution more complex. Durability can also be relaxed by acknowledging writes before they hit disk, which improves speed at the risk of losing recent writes if many nodes fail at once.

flowchart LR
    C[Client] --> LB[Load Balancer]
    LB --> A1[Coordinator 1]
    LB --> A2[Coordinator 2]
    A1 & A2 --> M[(Cluster Metadata / etcd)]
    A1 --> N1[(Storage Node 1 - Partition P1)]
    A1 --> N2[(Storage Node 2 - Replica P1)]
    A2 --> N3[(Storage Node 3 - Partition P2)]
    A2 --> N4[(Storage Node 4 - Replica P2)]
    N1 <-->|quorum or async replication| N2
    N3 <-->|quorum or async replication| N4
    N1 --> S1[(LSM Store)]
    N2 --> S2[(LSM Store)]
    N3 --> S3[(LSM Store)]
    N4 --> S4[(LSM Store)]

Google Docs Real-Time Collaboration Full Design

Google Docs must allow multiple users to edit the same document concurrently from different devices and locations. The functional requirements include opening a document, applying local edits immediately, broadcasting remote edits in near real time, supporting comments and presence, and recovering correctly after a client reconnects. The non-functional requirements are low propagation latency, convergence despite simultaneous edits, high availability, durable history, and horizontal scalability. For planning, assume 100 million monthly active users and roughly 1 million active document sessions at peak. If each active session sends one operation every few seconds, the system must handle hundreds of thousands of operations per second at peak. Storage is dominated by operation history and document snapshots, while document metadata is comparatively small.

The high-level architecture uses a persistent WebSocket connection from each client to a connection gateway. The gateway authenticates the user and routes traffic to the collaboration server responsible for that document. A collaboration server maintains the authoritative in-memory state for an active document, applies incoming operations, orders them, transforms conflicting operations, and broadcasts the resulting operations to all participants. The document service reads snapshots from object storage and replays missing operations from an append-only operation log. Redis stores short-lived presence and pub/sub channels so participants know who is online and so collaboration servers can subscribe to document events. The request flow is: a client sends an edit operation with its base version, the collaboration server assigns a server version, transforms the edit against any simultaneous operations, appends it to the durable log, and broadcasts the transformed operation to the other participants.

The data model separates document metadata, operations, and snapshots. Document metadata lives in a relational database with fields such as doc_id, owner_id, permissions, and latest_version because metadata requires indexed lookups and access-control checks. Operations live in an append-heavy store keyed by doc_id with fields such as op_id, doc_id, user_id, base_version, server_version, operation_type, and payload. This store is chosen because it must handle high write throughput and replay by document. Snapshots are stored in object storage such as S3, keyed by doc_id and snapshot_version, because document contents can be large and are read much more often than they are rewritten. Redis holds active session presence, participant lists, and pub/sub routing state with TTLs, which is acceptable because presence is eventually consistent and cheap to recreate.

The core mechanism is conflict-free merging of concurrent edits using operational transforms, CRDTs, or a combination of both. When two users edit different parts of the same document at the same time, the collaboration server orders the operations by a monotonic server version. If an operation was based on an older document version, the server transforms the remote operation against operations that happened since that base version so that every client converges to the same final document. CRDTs achieve a similar result by assigning unique IDs to characters or elements and defining merge operations that are commutative and associative. The system does not wait for synchronous acknowledgment from every user before accepting an edit, because that would make editing unusably slow. Instead, edits are applied locally first, then accepted by the server, then propagated to remote users with eventual convergence.

Scaling and availability come from sharding active document sessions across many collaboration servers. A consistent-hash or directory service maps doc_id to the current owner server, and the connection gateway routes each document operation to that owner. If a collaboration server fails, clients reconnect and the document session is reassigned to a new server, which rebuilds in-memory state from the latest snapshot and the operation log. Acknowledging an edit only after it is appended to a replicated operation log prevents data loss when a server fails. The operation log and snapshot storage are replicated, while Redis presence is sharded and replicated to avoid a single point of failure. For very large or busy documents, the system batches versions, limits active editors, or splits documents into independently mergeable sections to prevent one hot document from overwhelming a single server. Backpressure and per-document rate limits protect the collaboration tier when users generate bursts of edits.

The main trade-offs are latency versus strict consistency and central coordination versus peer-to-peer complexity. Centralized ordering by a collaboration server is simpler to debug and gives a clear authoritative version order, but it introduces a single coordinator for each document and can become a bottleneck. Peer-to-peer CRDT propagation avoids that coordinator but makes conflict resolution and access control harder. Persisting every operation before acknowledgment improves durability but increases write load and latency; batching or periodic snapshots lowers cost but increases the work needed during recovery. Strong consistency would simplify the programming model but would add unacceptable latency for real-time collaboration, so the design intentionally accepts eventual consistency and convergence. Finally, keeping all active documents in memory improves editing speed but limits how many active documents a server can host, so the system must balance memory, snapshot frequency, and recovery time.

flowchart LR
    U[User clients] -->|WebSocket| GW[Connection Gateway]
    GW -->|route by docId| CS1[Collab Server 1]
    GW -->|route by docId| CS2[Collab Server 2]
    CS1 <-->|presence/pubsub| P[(Redis Presence & Channels)]
    CS1 -->|durable append| OL[(Operation Log sharded by docId)]
    CS2 --> OL
    CS1 -->|snapshot read/write| S[(Snapshot Object Storage)]
    CS2 --> S
    CS1 -->|metadata| MD[(Metadata DB)]
    CS2 --> MD