Skip to the page

Design building blocks · senior

Consistency, replica lag and CAP

Replicas are usually asynchronous, so a read right after a write can be old. Choose the consistency model per feature. CAP and PACELC say what you give up in a split and on a normal day.

The notes

What you must know

  • Cause of old data after saving: writes go to the primary and reads to asynchronous replicas, so the next read can miss the write. An uncleared cache looks the same.
  • The need is read-your-writes (session) consistency for the person who saved, not strong consistency for everyone.
  • Fixes: read from the primary for that user for a few seconds after a write; read from the primary on that one call; track the write log position and use a replica only after it caught up; or return the saved object in the save response.
  • Name the models: strong (linearizable), read-your-writes, monotonic reads, eventual. Pick one per feature. Monitor replica lag and route away from lagging replicas. Move heavy nightly jobs to their own replica.
  • CAP: when the network splits, a replicated store must choose consistency (refuse or wait) or availability (answer, maybe stale). Partitions will happen, so the choice is C or A during one.
  • PACELC (Abadi): if Partition, choose Availability or Consistency; Else, choose Latency or Consistency. Replication costs latency even on a normal day.
  • Examples: Cassandra and DynamoDB default to PA/EL and can be tuned; Spanner and CockroachDB are PC/EC; Postgres with a synchronous replica leans to consistency and pays in latency. Quorums (R plus W above N) give stronger reads.
  • A ledger needs consistency first: refusing a write beats a double spend. A likes counter wants availability and low latency.

The red pen

Common traps: mistake → fix

  • Mistake: Send all reads to the primary

    Fix: that moves the load and may overload it.

  • Mistake: MongoDB is CP so it is always consistent

    Fix: check the real settings.

  • Mistake: CAP consistency and ACID consistency are the same

    Fix: they are different ideas.

  • Mistake: Add a sleep

    Fix: it hides lag only sometimes.

Easy to hard

Questions interviewers ask, easy to hard

  1. Users see their old address right after saving. Why and how do you fix it?
  2. Explain CAP with an example.
  3. What does PACELC add?
  4. Which consistency for a ledger and for a likes counter?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview