Skip to content

Choosing a Datastore and Replicating It ​

Pick a store from the access patterns, copy it across machines, and say exactly what a reader sees while the copies disagree.

In this chapter: access patterns before schemas · ACID and BASE · one owner per fact · leaders, lag and failover · routing reads

💡 The Core Idea ​

Every datastore is a set of trade-offs built into a product. Relational databases pay write cost for flexible queries and correctness. Key-value stores give up querying to win latency. Document stores give up joins to keep related data together. So the question is never "which is best". It is "which trade-offs match what this system does most often".

Once you have chosen, you copy the data to more than one machine. That is replication, and it buys two separate things. Durability means losing one machine does not lose the data. Read capacity means several machines can answer queries. It costs one thing: the copies are never identical at the same instant, so someone can read a value that is already out of date.

Relational is the default, and leaving it needs a reason one sentence long. "We might need to scale" is not that sentence.

How It Works ​

The families ​

FamilyStrong atWeak atExamples
RelationalJoins, transactions, ad-hoc queriesScaling writes across machinesPostgreSQL, MySQL
DocumentReading one aggregate in one hitJoins and consistency across documentsMongoDB
Key-valueSub-millisecond reads, huge throughputAny query that is not by keyRedis, DynamoDB
Wide-columnEnormous write volume, time-ordered rangesAd-hoc queries, joinsCassandra, ScyllaDB
GraphTraversals many hops deepReporting, bulk writesNeo4j

Access patterns before schemas ​

Relational modelling starts from the entities and lets the query planner do the rest. Every other family works the other way round. The primary key is the query plan, and a wrong key means a migration, not a new index.

A DynamoDB-style single-table key:

typescript
interface OrderItem {
  pk: string; // "USER#42" — everything for one user lives in one partition
  sk: string; // "ORDER#2026-09-02#8821" — sorted, so newest-first ranges are free
  status: "pending" | "shipped";
  total: number;
}

// "The last 20 orders for user 42" is one query against one partition.
// "All orders over £500 across all users" is a full scan. If you need it, this is the wrong store.

ACID and BASE ​

ACID (relational)BASE (most NoSQL)
WritesAtomic across rows and tablesAtomic within one document or partition
ReadsA consistent snapshotMay be stale
BuysCorrectness with no extra codeAvailability and write throughput
CostsCoordination, which limits writesCorrectness becomes your code's job

With BASE, the rules the database used to enforce move into your code. Uniqueness, foreign keys and "a balance cannot go negative" each become a race condition you must handle yourself.

One owner per fact ​

Normalise by default. Denormalise one read path only once it is measurably too slow, and name who keeps the copies in step.

⚠️ Denormalisation is a cache dressed as a schema. It fails the same way, with stale data, but it has no expiry. Give every duplicated field a rule for when it is refreshed.

Most real systems use two or three stores, each for what it does well.

Polyglot persistence in one system:

One store owns each fact; the others are derived from it and can be rebuilt.

If two stores both claim a fact, they drift apart and nothing tells you which is right. Write to one and derive the rest.

Leaders and topologies ​

TopologyWrites go toConflictsUse for
Single-leaderOne node, copied outwardsImpossibleAlmost everything — the default
Multi-leaderAny leader, in several regionsCertain, must be resolvedWrites in two regions, offline clients
LeaderlessSeveral replicas at once, by quorumLikely, resolved at readCassandra-style stores

Single-leader removes write conflicts, so it wins unless the requirements force otherwise.

Synchronous or asynchronous ​

SynchronousAsynchronous
Write latencyLeader plus the slowest replicaLeader only
Loss if the leader diesNone, for acknowledged writesEverything not yet shipped
AvailabilityA stalled replica blocks writesReplicas cannot block writes

Production usually runs semi-synchronous. One replica confirms each write, and the rest follow later. You get a safe second copy, and no single slow replica can stop the system.

Replica lag ​

Lag is the delay between a write committing on the leader and appearing on a replica. It is normally milliseconds, and minutes while a replica rebuilds. Users see it as three different bugs.

AnomalyWhat the user seesFix
Read-your-writes"I saved it and it did not save"Send that user to the leader briefly
Monotonic readsA value appears, then vanishes on refreshPin a session to one replica
Causal orderA reply shows before the comment it answersRead both from the same replica

Routing a read by lag tolerance:

typescript
interface ReplicaHealth { name: string; lagMs: number }

function pickReplica(replicas: ReplicaHealth[], toleranceMs: number): string | null {
  const fresh = replicas.filter((r: ReplicaHealth) => r.lagMs <= toleranceMs);
  if (fresh.length === 0) return null; // fall back to the leader rather than serve stale data
  return fresh[Math.floor(Math.random() * fresh.length)].name;
}

Default every read to a replica, and mark the few endpoints that need the leader: a user's own recent write, and anything about money, stock or permissions. The opposite default never gets cleaned up.

Failover and split brain ​

When the leader dies, you promote a replica. You detect the failure with a heartbeat timeout, pick the replica with the newest log position, and point clients at it. Then you make sure the old leader cannot come back as a leader.

⚠️ That last step is the one people forget. If the old leader recovers and still thinks it is primary, two nodes accept writes and the data splits. This is split brain. Fencing prevents it: a rising term number that storage checks on every write. Automatic failover without fencing loses data.

With asynchronous replication, failover also loses every write the old leader confirmed but had not shipped. So "does failover lose data?" has an honest answer: yes, up to the replication lag.

When to Use It ​

RequirementChoiceWhy
Transactions across entities, money, stockRelationalACID without writing it yourself
Reads by key at very low latencyKey-valueNothing else is in the same range
Millions of time-ordered writes a secondWide-columnBuilt for exactly this write pattern
Ranked full-text searchSearch engine, derived from the main storeInverted index and relevance scoring
One database, uptime mattersOne leader plus a sync replica in another zoneSurvives a zone without losing writes
Writes genuinely needed in two regionsMulti-leader with a conflict ruleThe only option, so own its cost

Common Mistakes ​

❌ Choosing NoSQL for scale you do not have

"We picked Cassandra because we might get big."

One PostgreSQL instance handles tens of thousands of transactions a second and terabytes of data. Most products never leave that range, and the ones that do can afford to migrate.

✅ Choosing for the access pattern you actually have

"Writes are 400 a second and every query is by user ID with a date range. One Postgres with a composite index is right, and I will revisit if writes pass 5,000."

❌ Treating replicas as a backup

Replication copies mistakes perfectly. A DELETE without a WHERE reaches every replica in milliseconds.

✅ Replicas for availability, backups for recovery

Replicas cover a machine or zone dying. Point-in-time backups cover bad data, and a scheduled restore proves they work.

🔑 Key Takeaways ​

  • Start from the access patterns, because in every non-relational store the primary key is the query plan.
  • Relational is the default, and leaving it needs a specific reason about access shape or write volume.
  • Exactly one store owns each fact, and every other copy is a projection you can rebuild.
  • Replication buys durability and read capacity, and it charges staleness for both.
  • Asynchronous failover loses every write not yet shipped, and failover without fencing risks split brain.

Interview Questions ​

Q: SQL or NoSQL for this system — how do you answer without hedging?

Name the access patterns first, then the consistency requirement, then pick. Varied queries, related data and money point to relational. Every query by a known key, huge write volume and self-contained records point to key-value or wide-column. State the write volume at which you would revisit.

Q: What do you actually lose by moving from PostgreSQL to DynamoDB?

Joins, ad-hoc queries and general multi-entity transactions. You gain predictable low-latency reads and near-unlimited write scaling. The real cost is that a new query pattern may need a new index or a data migration, because the key encodes the queries you thought of at the start.

Q: Your primary dies. What is lost?

With asynchronous replication, you lose every write the leader confirmed but had not shipped. That is usually under a second, more if the replica was lagging. With a synchronous replica, you lose nothing that was confirmed. Semi-synchronous replication exists to balance exactly that trade.

Q: A user says their profile update "did not save". Diagnose it.

Almost certainly replica lag. The write went to the leader, and the next read hit a replica that had not applied it yet. Confirm by checking lag at that time, then fix it with read-your-writes routing, not by changing the consistency of the whole system.

Q: When would you accept multi-leader replication?

Only when writes must succeed in more than one region and cross-region latency is unacceptable, or when clients write offline and sync later. Conflicts then become certain, so I would require a resolution rule the domain accepts. That could be a CRDT (a data type built to merge on its own) or a business merge rule. Last-write-wins on data that matters is not that rule.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.