Library / Papers
Megastore: Providing Scalable, Highly Available Storage (paper)
Synchronous replication across data centres with Paxos while keeping a transactional data model.
By Baker et al. · Google · Added 2026-10-12
All content belongs to Baker et al. / Google. We only link to it and give credit. Report a problem
Learn this paper
About 37 min left. Your work is saved as you go.
What you are about to study
Google wrote this paper. Read the abstract and headings first. It assumes you are comfortable with distributed systems.
Ideas you will meet
- Databases
- Schemas, indexes, query plans and choosing a store.
- Consensus
- Raft, Paxos and how replicas agree on one order.
- Replication
- Leader/follower, multi-leader and leaderless replication.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Databases Deep Dive · 12 minReplication topologies and multi-region databasesSingle-leader, multi-leader and leaderless replication, how they handle conflicts and lag, and what changes across regions.Read here
Why replicate
Replication keeps copies of data on several machines for three reasons: availability (survive a node failure), read scaling (serve reads from replicas) and latency (put data near users). The hard part is keeping copies consistent while writes continue. (Basics are in the replication and sharding lesson of the foundations course; this lesson compares the topologies.)
Single-leader (primary and replicas)
One node, the leader (primary or master), accepts writes and ships its changes to followers (replicas), which serve reads.
100%Figure SDA-DDV-04-1 · Single-leader replication · © forcsguy.com
- Synchronous replication waits for a follower before acknowledging: safer, slower, and a stalled follower can block writes. Asynchronous is faster but a failover can lose the latest writes. A common compromise: one synchronous follower, others asynchronous.
- Failover must detect failure, choose the most up-to-date replica, redirect clients and ensure the old leader does not come back believing it still leads (split brain).
- Replication lag causes stale reads. Techniques: read-your-writes (route a user's reads to the leader shortly after they write), monotonic reads (keep a user on one replica), and checking replica position.
Multi-leader
Several nodes accept writes (often one per region) and replicate to each other. Benefits: local write latency and continued operation if a region is cut off. Cost: write conflicts.
Conflict handling options:
- Avoid them: route all writes for one record to one leader (for example by user or region).
- Last write wins by timestamp: simple, but silently drops one of two concurrent updates and depends on clocks.
- Merge values (union of sets, counters) using mergeable data types (CRDTs; see the collaborative editing lesson).
- Custom resolution in application code, or ask the user.
Multi-leader also appears in offline-capable apps (each device is a leader) and collaborative editing.
Before: single leader
100%After: multi-leader across regions
100%What changed
- Users in each region write to a nearby database
- Concurrent edits to the same row need conflict handling
- More moving parts to run and monitor
Leaderless (Dynamo-style)
Any replica accepts writes; clients write to several replicas and read from several, using quorums (
W + R > N) to get fresh data (see the key-value store lesson). Background anti-entropy and read repair fix stale copies; versions or vector clocks detect conflicts. It favours availability and is typical of Cassandra and DynamoDB-style stores.100%Figure SDA-DDV-04-2 · Choosing a replication model · © forcsguy.com
Multi-region designs
- Active-passive: one region serves writes; another is a warm standby. Simple; failover loses a little data (the replication lag) and takes minutes.
- Active-active: several regions serve traffic. Requires either partitioning data by home region (each record has one home, cross-region reads are replicas) or true multi-leader conflict handling.
- Global databases use consensus across regions (see the consensus lesson) for strong consistency at the cost of cross-region write latency; some offer tunable consistency per query.
- Latency numbers matter: a cross-ocean round trip is around 100 ms or more, so synchronous cross-region replication adds that to every write.
- Data residency laws may require keeping certain users' data in a region.
Partitioning and replication together
Real systems shard data into partitions and replicate each partition (a leader per partition spreads write load across nodes). Rebalancing, hot partitions and cross-partition transactions are the new problems (see sharding and the consistent-hashing lesson).
Master/slave naming
You will see "master/slave", "primary/replica" and "leader/follower" for the same single-leader idea; most current documentation prefers the last two.
Checklist
- What happens to writes if the leader or a region is lost, and how long?
- How much data can we lose (RPO) and how long can we be down (RTO)?
- How do we handle stale reads from replicas?
- Who resolves conflicts, and how?
- Have we practised failover?
Real-world reading
Related reading
- Active-Active for Multi-Regional ResiliencyNetflix Engineering · NetflixCase Studies
- Designing Data-Intensive ApplicationsMartin Kleppmann · O'ReillyBooks
- Read Consistency with Database Replicas at ShopifyShopify engineers · ShopifyCase Studies
- Uber Schemaless: A Scalable MySQL DatastoreUber Engineering · UberCase Studies
Show 6 moreShow fewer
- Mitigating MySQL Replication Lag and Reducing Read Load at GithubGithub engineers · GithubCase Studies
- Cassandra architecture overviewApache Cassandra · Apache Software FoundationDocumentation
- How Discord Stores Trillions of MessagesBo Ingram · DiscordBlogs
- Spanner: Google's Globally Distributed Database (paper)Corbett et al. · GooglePapers
- Scaling Multitenant Architecture Across Multiple Data Centres at Shopify - Weingarten, Engineering Lead at ShopifyShopifyYouTube
- MIT 6.824: Distributed SystemsRobert Morris · MITCourses
Advanced Distributed Systems · 12 minConsensus: Raft and PaxosHow a group of machines agrees on one order of operations even when some crash or messages are delayed, and why a majority is the magic number.Read here
The problem consensus solves
Several machines must agree on one sequence of operations (who is the leader, what is the next log entry, who owns a lock) even though machines crash and messages are delayed or lost. Without a protocol, replicas drift apart and two nodes may both believe they are the leader.
Systems that rely on consensus include coordination services (etcd, ZooKeeper), many databases for their metadata or their data, and Kubernetes (through etcd).
Why a majority
A decision is valid when a majority (quorum) of nodes accepts it. Any two majorities share at least one node, so a later decision always meets someone who remembers the earlier one. A cluster of
nnodes toleratesfloor((n-1)/2)failures: 3 nodes tolerate 1, 5 nodes tolerate 2. That is why clusters have an odd number of nodes; a 4th node adds cost but no extra fault tolerance over 3.Raft in three parts
Raft splits the problem so it can be understood:
100%Figure SDA-ADS-01-1 · Raft roles and elections · © forcsguy.com
- Leader election. Time is divided into numbered terms. A node that hears nothing becomes a candidate and requests votes. A node votes at most once per term, and only for a candidate whose log is at least as up to date as its own. Randomised timeouts make split votes rare.
- Log replication. The leader appends a client command to its log and sends it to followers. When a majority has stored the entry, it is committed; the leader applies it and replies to the client. Followers apply committed entries in order, so every replica runs the same sequence.
- Safety. The vote rule guarantees that any new leader already has every committed entry, so committed entries are never lost or reordered.
100%Figure SDA-ADS-01-2 · Replicating one write · © forcsguy.com
Paxos, briefly
Paxos reaches the same guarantee with two phases (prepare/promise, then accept/accepted) over a majority. It is famous for being hard to implement and explain, and for being the basis of many systems. Multi-Paxos repeats it for a log of decisions. Raft is essentially a clearer arrangement of the same ideas with a strong leader, which is why most new systems choose it.
What consensus costs and what it does not give
- Latency: every committed write waits for a majority round trip, so cross-region clusters are slow. Keep consensus groups within a region or use few, small groups for metadata.
- Throughput: one leader handles all writes in a group. Large databases run many small groups (one per data range) to spread load.
- Availability under partition: the minority side cannot make progress. This is the CAP trade-off made concrete: consensus systems are consistent first.
- It does not remove all problems: slow nodes, clock assumptions, and reconfiguration (adding or removing nodes safely) need care.
Where you will meet it
Leader election for databases and queues, distributed locks and configuration stores, metadata for storage systems, and cluster state in Kubernetes. When a design needs "exactly one leader" or "all replicas agree on this order", you are describing consensus. See also the distributed-locks lesson in the core-concepts course.
Real-world reading
Related reading
- In Search of an Understandable Consensus Algorithm (Raft paper)Ongaro and Ousterhout · Stanford UniversityPapers
- The Raft Consensus Algorithm (site and visualisation)Diego Ongaro and community · raft.github.ioDocumentation
- ZippyDB: Facebook's key-value storeMeta Engineering · MetaCase Studies
- How Ringpop from Uber Engineering Helps Distribute Your ApplicationUber Engineering · UberCase Studies
Show 6 moreShow fewer
- etcd Raft libraryetcd · CNCF / etcdGitHub
- Google SRE Book: Managing Critical State (Distributed Consensus)Google SRE team · GoogleBlogs
- Paxos Made Simple (paper)Leslie Lamport · Microsoft ResearchPapers
- HashiCorp RaftHashiCorp · GitHubGitHub
- Distributed Systems (4th edition)Maarten van Steen and Andrew Tanenbaum · distributed-systems.netBooks
- Scaling Hadoop YARN cluster beyond 10,000 nodes at LinkedInLinkedIn engineers · LinkedInCase Studies
Advanced Distributed Systems · 12 minRedis: persistence, replication, Sentinel and ClusterWhat keeps an in-memory database from losing data and from being a single point of failure: snapshots, the append-only file, replicas, Sentinel and hash slots.Read here
Fast because it is in memory, durable because of logs
Redis keeps its dataset in RAM (the reason it is so fast; see the Redis and Memcached lesson). To survive a restart it offers two persistence mechanisms, which can be combined.
Snapshots (RDB)
Redis periodically writes a point-in-time snapshot of the whole dataset to disk, using a forked child process so the main process keeps serving. Snapshots are compact and quick to load, but anything written since the last snapshot is lost on a crash.
Append-only file (AOF)
Redis appends every write command to a log. On restart it replays the log. The fsync policy sets the loss window:
Policy Behaviour Risk alwaysFlush after every command Slowest, almost no loss everysecFlush once per second At most about a second lost (common default) noLet the OS decide Fastest, larger loss The AOF grows, so Redis periodically rewrites it into a compact form. Many deployments use AOF with
everysec, sometimes plus snapshots for fast backups.100%Figure SDA-ADS-04-1 · Redis persistence choices · © forcsguy.com
Replication and Sentinel
A Redis primary replicates to one or more replicas asynchronously. Replicas serve reads (possibly slightly stale) and can take over. Sentinel is a small set of monitor processes that:
- watch the primary and replicas,
- agree by quorum that the primary is down,
- promote a replica and tell clients where the new primary is.
100%Figure SDA-ADS-04-2 · Sentinel failover · © forcsguy.com
Because replication is asynchronous, a failover can lose the last few acknowledged writes. Redis offers settings to reduce this (for example requiring a minimum number of replicas to acknowledge), at the cost of availability.
Redis Cluster: sharding
When data or traffic outgrow one node, Redis Cluster shards the keyspace into 16,384 hash slots. A key's slot is a hash of the key modulo that number; each node owns a range of slots, and each primary has replicas. Clients learn the slot map and talk to the right node; a wrong guess gets a redirect.
- Resharding moves slots (and their keys) between nodes while the cluster runs.
- Multi-key operations only work when all keys are in the same slot. Hash tags (a
{tag}part of the key) force related keys into one slot. - Failover is built in: replicas of a failed primary are promoted by the cluster.
- This is the "fixed number of slots" cousin of consistent hashing (see the consistent-hashing lesson).
Which setup when
Need Choice Pure cache, loss acceptable Single node or replicas, little or no persistence Must survive restart AOF (everysec) and snapshots Must survive node loss Replica plus Sentinel Data larger than one node, or very high throughput Redis Cluster Also keep memory in mind: set a max memory and an eviction policy (see the caching lessons) so Redis behaves predictably when full, and watch for large keys and slow commands, which block a single-threaded executor.
Real-world reading
Related reading
- Redis DocumentationRedis · Redis Ltd.Documentation
- Redis persistenceRedis · Redis Ltd.Documentation
- Redis UniversityRedis · Redis Ltd.Courses
- Redis BlogRedis engineers · Redis Ltd.Blogs
Show 6 moreShow fewer
- Scale with Redis ClusterRedis · Redis Ltd.Documentation
- RedisRedis · Redis Ltd.GitHub
- Failover with Redis Sentinel at VintedVinted engineers · VintedCase Studies
- Memory Optimization in Redis at WattpadWattpad engineers · WattpadCase Studies
- Speeding Up Redis with Compression at DoorDashDoorDash engineers · DoorDashCase Studies
- Availability in Globally Distributed Storage Systems at GoogleGooglePapers
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Megastore: Providing Scalable, Highly Available Storage (paper).
Warm upGet the vocabulary first.
Books
Database Internals
How storage engines and distributed databases work, from B-trees and LSM-trees to consensus and replication.
O'ReillyAdvanced
Documentation
Cassandra architecture overview
The ring, replication, tunable consistency and the storage engine of Cassandra.
Apache Software FoundationIntermediate
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs
Cockroach Labs Blog
Distributed SQL internals: consensus, transactions and multi-region design.
Cockroach LabsAdvanced
Papers · Read here
Amazon Aurora: Design Considerations for High Throughput Cloud-Native Relational Databases (paper)
Why Aurora moves the redo log to a distributed storage layer, so replication and crash recovery become cheap.
Amazon Web ServicesAdvanced
See it in another companyThe same ideas, a different system.
Case Studies · Read here
ZippyDB: Facebook's key-value store
Facebook's strongly consistent key-value store built on RocksDB and Paxos, with data sharded and replicated.
MetaAdvanced
Case Studies · Read here
Building and Deploying MySQL Raft at Meta
We’re rolling out MySQL Raft with the aim to eventually replace our current MySQL semisynchronous databases. The biggest win of MySQL Raft was simplification of the operation and making MyS…
MetaAdvanced
Read the codeSee how it looks when it is real.
GitHub
CockroachDB
A distributed SQL database built on ranges, Raft and MVCC.
GitHubAdvanced
GitHub
Apache Cassandra
The source of the wide-column, leaderless database.
GitHubAdvanced
Keep learning
Loading community…