Kyle Kingsbury's Jepsen tests partitioned a MongoDB 2.4 replica set while clients kept writing. For a while the isolated primary went on accepting writes, until it noticed it had lost the majority and stepped down; when the partition healed, those writes were rolled back. With the "safe" write concern of the time, 2,208 of 5,900 acknowledged writes were lost — 37 %; with the majority write concern, 2 of 5,700. What survives depends on how you write.
Scaling out MongoDB: shards, chunks, mongos and the CAP corner
After this lesson you will name the parts of a sharded MongoDB cluster and what each one knows, follow a chunk from its first split to its migration, choose range, hash or tag-aware sharding for a workload, and say why the slides put MongoDB on the CP edge — with the slides' dated numbers corrected.
A hospital's heating systems send a reading every minute — { deviceId, timestamp, kwh } — and the collection has outgrown its server. The team shards it over three servers and, since every report asks for a time window, picks the timestamp as the shard key. MongoDB does the rest: the collection starts as one chunk, a chunk is cut in two when it grows too big, and the pieces travel to emptier servers while the application keeps writing.
A week later the three servers hold the same number of chunks each. Yet at any moment all new readings land on a single server, and the other two receive none. Nothing is broken: every part does exactly its job. How can the data be balanced and the writes not — and which one choice would have spread them?
Keep a second question for the end: when the busy server dies, what happens to the readings it holds?
Sharding: partitioning that runs by itself
Lesson 3 met sharding as horizontal partitioning: whole rows spread over several machines. The MongoDB deck calls it "A new word: Sharding" (p. 287), "Essentially Data Partitioning", and lists what is "Different in NoSQL": "Fully automatic", "Configurable", "Transparent", "BASE principles" — "See for example MongoDB".
Read them as a division of labour: the database cuts, moves and routes by itself (automatic); a human chooses what to cut on, and how — the key and the strategy of section 4 (configurable); the application sees one database (transparent). "BASE principles" places it in the family of lesson 5; for MongoDB the deck's CAP slide is more precise (section 5).
The running example: the hospital heating system of the exam of 30 Jan 2026, plus what its ER diagram lacks — the readings each Heating System sends, one document each in a readings collection, the heater's Heater_Sys_ID stored as deviceId as on the slides. Readings grow without end, so they get their own collection (lesson 13's stop sign of unbounded growth).
Four reasons to shard
Page 288 lists them, and p. 335 comes back to all four. "Sharding is a means of partitioning data across servers to enable":
- "Scale: needed by Modern applications to support massive workloads and data volume." Each server stores and serves only its part.
- "Geo-Locality: to support geographically distributed deployments to support optimal UX for customers across vast geographies." Milan's readings on a server in Milan, Palermo's in Palermo.
- "Hardware Optimizations: on Performance vs. Cost". This month's readings on fast SSD servers, last year's on cheap disks.
- "Lower Recovery Times: to make 'Recovery Time Objectives' (RTO) feasible." The RTO is the longest outage the business accepts; three small shards restore in parallel, far faster than one big database.
Shard key, chunk, shard
"Sharding involves a shard key defined by a data modeler that describes the partition space of a data set. Data is partitioned into data chunks by the shard key, and these chunks are distributed evenly across shards that reside across many physical servers" (p. 289). And the picture to keep (p. 324): "Key space is like points on a line", "Range is a segment of that line".
Shard key — the field, or fields, whose value decides where a document lives; "User defines shard key for partitioning" (p. 324).
Chunk — a contiguous range of shard-key values, a segment of the key line, together with every document whose key falls in it; the unit that is split and moved.
Shard — "a node of the cluster" (p. 327) that holds some of the chunks.
deviceId. Two cuts make three chunks; each chunk includes its start and excludes its end. Shard 1 holds two chunks that are not neighbours: a shard owns a set of segments, and the record of which segment lives where is the chunk map of section 2. The two ends of the line are MongoDB's special values MinKey and MaxKey, which sort below and above everything; p. 331 draws them as −∞ and ∞, p. 334 names them."Fully automatic (p. 287) means nothing to decide." The same deck says "User defines shard key" (p. 324): cutting, moving and routing are automatic, the key is yours — and no automation repairs a bad one.
Sharding cuts the shard-key line into chunks and spreads the chunks over shards: you choose the key, MongoDB cuts, moves and routes.
Who is who: mongod, mongos and the config servers
Three kinds of process run a sharded cluster: "Mongod – Database instance", "Mongos - Sharding processes" (p. 321) and the config servers (p. 326). The third program of p. 321, "Mongo", is the shell of lesson 14.
mongod, and what a shard is
mongod — the "main daemon" (p. 329) — stores documents and answers queries. A shard "is a node of the cluster" and "can be a single mongod or a replica set" (p. 327). A replica set is a group of mongod processes holding the same data: one primary, which receives every write, and secondaries, which copy those writes and can take its place — the slide draws a "Primary" box over two "Secondary" boxes.
Fig. 2 redraws the deck's picture of the cluster, the third panel of "MongoDB is fast and scalable" (p. 295). Down a column, "Replication /HA": the same data on three servers, which survive one failure. Along the row, "Horizontal Scaling": different data in each column, so another column adds capacity. A column is a replica set; the row is the set of shards.
The middle panel, "In-Memory Caching", draws memory cells feeding disks: the data in use stays in RAM, written to disk behind the scenes — "Operates at in-memory speed wherever possible" (p. 294). The first panel, data locality, is lesson 13's.
mongos, the router
Applications do not talk to the shards: they talk to mongos, "Analogous to a database router", which "Processes all requests", "Decides how many and which mongod should receive the query" and "Collates the results, and sends it back to the client" (p. 321). "How many and which" is the key phrase:
// targeted: has the shard key
db.readings.find(
{ "deviceId": 512 }
)
// broadcast: no shard key
db.readings.find(
{ "kwh": { "$gt": 5 } }
)
The first filter contains the shard key: mongos looks 512 up in the chunk map and asks the one shard holding it — a targeted query. The second does not, so mongos asks every shard and merges the answers — a broadcast (scatter-gather) query, which costs every shard work. Both names are the manual's; the slides say "routed to specific shards" (p. 326). A filter on the leading field of a composite key is targeted too. Fig. 3 follows both queries.
Targeted: the filter names the shard key
Broadcast: the filter does not
mongos "Acts as a router / balancer", has "No local data (persists to config database)" and "Can have 1 or many" (p. 329): "one mongos for the whole system", or "one local mongos for every client if you wanted to minimize network latency" (p. 321) — the two layouts at the bottom of p. 329. A local mongos saves a network hop; a crashed one loses nothing and reloads the map.
The config servers, keepers of the map
The map lives on the config servers, which "Stores cluster chunk ranges and locations" (p. 326): each chunk's range and its shard. mongos caches it. As the one source of truth about where data lives — p. 329 joins "Config Server", "Mongos" and "Mongod" with two-way arrows — the config servers need the protection the data has.
mongod stores, mongos routes, the config servers remember where every chunk is.
The life of a chunk: split, then migrate
"Distribution" (p. 325) tells the story in three lines: "Initially 1 chunk", "Default max chunk size: 64mb", "MongoDB automatically splits & migrates chunks when max reached". Its picture catches the middle: "Shard 1" with three chunks, "Shard 2" with one.
Two events hide in "splits & migrates". A split cuts a chunk's range in two at a shard-key value: both halves stay put, only the chunk map changes, no document moves. A migration moves one whole chunk to another shard: its documents are copied, the map updated, the old copy deleted. Migrations are the balancer's decision: "MongoDB balances cluster", "MongoDB migrates data to new nodes" (p. 326).
A split is cheap, a change of the map; a migration copies megabytes across the network, so the balancer moves as little as it can. And no chunk is on two shards: sharding divides, replication copies — which is why the failure switch hurts only a single-mongod shard.
Auto-sharding in two steps
"Auto-sharding" (p. 328) promises "Minimal effort required" in "Two steps": "Enable Sharding for a database" and "Shard collection within database". In the shell (command names from the MongoDB manual; the slides give only the steps):
// step 1: the database
sh.enableSharding("hospital")
// step 2: the collection, on
// the composite key of p. 331
sh.shardCollection(
"hospital.readings",
{
"deviceId": 1,
"timestamp": 1
}
)
Everything after step 2 happens without you; the key is the one decision MongoDB cannot take for you.
A split only redraws the map; a migration moves a whole chunk; the balancer migrates until the shards are even.
Range, hash or tag: three ways to cut the line
"MongoDB Sharding Strategies" (p. 330) names three: "Ranged", "Hashed", "Tag-aware". All cut the key line into chunks; they differ in what places a document on the line, and in who decides which shards hold a stretch of it. (The slide's drawing labels mongos "Query Router".)
Range sharding
Range sharding "Splits shards based on sub-range of a key (or also multiple keys combined)" (p. 331) — read "splits the data". The slide gives a "Simple Shard Key: {deviceId}" and a "Composite Shard Key: {deviceId, timestamp}" (the manual says compound): pairs ordered by deviceId, then by timestamp within a device, like a phone book sorted by surname, then first name. Its two chunks (Fig. 4) split inside device 1000's readings, between two consecutive seconds.
A range key keeps neighbours together: a query for a stretch of keys — device 1000 last week — reaches one shard or a few. That is also its weakness. When the key only grows, like a timestamp, every new document lands in the last chunk, the one ending at MaxKey: one chunk, one shard, all the writes — a hot spot. The slides do not discuss it; the MongoDB manual warns about it.
Hash sharding
Hash sharding is "A subset of Range Sharding": "MongoDB apples a MD5 hash on the key when a hash shard key is used" (read "applies"), which "Ensures data is distributed randomly within the range of MD5 values" (p. 332). The slide's one formula:
- MD5
- a hash function: the same input always gives the same output, while neighbouring inputs give unrelated outputs
"Subset" means the cutting is still by ranges — of hash values. Consecutive keys get unrelated hashes and scatter over all the chunks, so inserts spread evenly even when the key only grows. The price is the same scrambling: a range query on the key is broadcast to every shard. An equality query stays targeted, since mongos can hash the one value asked for.
| Shard key | Writes | Last 10 min | Device 1003, last 10 min | One exact second |
|---|---|---|---|---|
| timestamp, ranged | 0 · 0 · 180 | shard 3 | shard 3 | shard 3 |
| timestamp, hashed | 62 · 63 · 55 | all 3 | all 3 | shard 3 |
| deviceId + timestamp, ranged | 60 · 60 · 60 | all 3 | shard 2 | all 3 |
Row by row: the timestamp makes time windows cheap and sends every insert to one shard; its hash spreads inserts and broadcasts every window; the composite key spreads inserts and keeps "one device, one window" on one shard.
Tag-aware sharding
The third strategy decides which shards may hold a stretch of the line: "Tag-aware sharding allows subset of shards to be tagged, and assigned to a sub-range of the shard-key" (p. 333). The example: users from 100 "regions", "Collection: Users, Shard Key: {uId, regionCode}", "Tag based on macro regions". Page 334 tags "Shard1" and "Shard2" West, "Shard3" and "Shard4" East, and assigns key ranges with the first row of the table below; the balancer keeps each range on its tagged shards. Since version 3.4 MongoDB calls tags zones; keep the slide's word at the exam.
| Shard key | West: Shard1, Shard2 | East: Shard3, Shard4 | |
|---|---|---|---|
| As printed | {uId, regionCode} | MinKey, MinKey → MaxKey,50 | MinKey, 50 → MaxKey, MaxKey |
| Corrected | {regionCode, uId} | (MinKey, MinKey) → (51, MinKey) | (51, MinKey) → (MaxKey, MaxKey) |
As printed (p. 334): {uId, regionCode}
Corrected: {regionCode, uId}
Which sharding to use?
Page 335 closes the loop with the four reasons of p. 288 (the third column is ours).
| Usage | Required Strategy | Why |
|---|---|---|
| Scale | Range or Hash | more shards hold and serve more data; any cut of the line spreads the volume |
| Geo-Locality | Tag-aware | a region's stretch of the line must live on that region's shards |
| Hardware Optimization | Tag-aware | hot ranges on fast shards, cold ones on cheap shards: a placement decision |
| Lower Recovery Times | Range or Hash | smaller shards restore faster, whatever the cut |
The rule: spreading volume (scale, recovery) needs any cut; putting particular data on particular machines (regions, hardware tiers) needs tags.
Range keeps neighbours together, hash scatters them, tags pin ranges to chosen shards.
The CAP corner
The deck's last content slide, "CAP Theorem and Mongo" (p. 336), lays the MongoDB logo along the C–P edge of the triangle, next to the heading "Focus on Consistency and Partition tolerance". Its definitions: "Consistency – all replicas contain the same version of the data", "Availability – system remains operational on failing nodes", and "Partition tolarence" (read "tolerance") — "multiple entry points", "system remains operational on system split". The course notes agree: MongoDB is "built using a CP architecture".
p. 336: MongoDB on the C–P edge
Why: one primary, chosen by a majority
Why CP? Because of the replica set. Only its primary accepts writes. If a partition splits a replica set, only the side that still sees a majority of the members may have a primary: it keeps it, or elects one among its secondaries. A primary left on the minority side steps down as soon as it notices, and refuses writes. Its clients get errors — availability is given up — but only the majority side's writes survive, so the data stays consistent: the CP line of lesson 5, "a timeout error or an error, otherwise". (Elections by majority are background; the slides do not describe them.)
"Partition tolerance means multiple entry points." That line under P (p. 336) is no part of the definition: partition tolerance means the system keeps working when the network between nodes splits (p. 195, lesson 5). Quote the line as what the slide prints, not as the definition. And read "all replicas contain the same version" as a promise about reads through the primary: secondaries may lag a little.
"CP" describes the default path through the primary; each operation may choose otherwise — lesson 5's "It's at operation level!" (p. 198). In the manual's terms (background): a write can wait until a majority has it, the write concern "majority", or only for the primary; a read can go to a secondary, closer but possibly stale.
MongoDB is CP because each replica set has a single primary, and the side of a partition without a majority stops accepting writes.
Back to the busy server
The hook's cluster did everything the slides promise: one chunk, splits, migrations until every shard held the same number. But the key was the timestamp, and a timestamp only grows: every new reading falls into the chunk ending at MaxKey — on one shard. The balancer evens out what is stored, not where the next write goes: it balanced the past while the present landed in one place.
The one choice that would have spread the writes is the key. A hashed timestamp spreads them but broadcasts every time-window report; the slide's composite key {deviceId, timestamp} spreads them over the heaters and keeps "one heater, one window" on one shard — the highlighted row of the table.
And the second question: a single-mongod shard dies with its chunks — the hole in the first widget — while a replica-set shard elects a new primary and carries on. That is why every shard must be one today.
Exam-style questions
True/false, multiple choice and short open answers, as in the theory part, where a wrong tick may cost points. No past paper has a sharding exercise.
True or false: with a hashed shard key, documents with consecutive shard-key values are stored in the same chunk, so a range query on the shard key is routed to a single shard.
Show model answer
False. Hash sharding applies an MD5 hash to the shard key and partitions the data by ranges of hash values. Consecutive key values have unrelated hashes, so they are spread over different chunks and shards, and a range query on the key has to be broadcast to all shards. It is range sharding that keeps neighbouring values in the same chunk.
The statement tests the price of hashing. The mirror statement — range sharding keeps neighbours together — is what makes range queries cheap and an always-growing key dangerous.
Which of the following statements about a sharded MongoDB cluster agree with the lecture? Select all that apply.
Show model answer
The first, second and fourth statements.
A select-all question in which a wrong tick may cost points. The two false options are the classic traps: mongos holds no data, and split and migrate are two different events.
Describe the roles of mongod, mongos and the config servers in a sharded MongoDB cluster. Explain the difference between a targeted and a broadcast query, and why a cluster can run several mongos instances.
Show model answer
mongod is the database instance, the main daemon that stores the documents and executes queries on them. A shard is a node of the cluster: according to the slides a single mongod or a replica set of mongod processes (one primary and secondaries); current versions require a replica set. mongos is the router: it processes all client requests, decides how many and which shards must receive each query, and collates their results before answering the client. The config servers store the cluster metadata: the chunk ranges of the shard key and the shard that holds each chunk; mongos reads and caches this map to route requests. A query whose filter contains the shard key (or a prefix of a composite shard key) is targeted to the shards owning the matching chunks; a query without it is broadcast to all shards and the partial results are merged (scatter-gather). mongos keeps no local data, since its state persists in the config database, so it can be replicated freely: one shared mongos, or one local mongos per application server to save a network hop.
A complete answer covers four roles: who stores (mongod and the shard), who routes (mongos: "how many and which", then collates), who remembers (config servers: chunk ranges and locations), and why many mongos (no local data). The slide's "1 or 3" config servers is the dated detail: today they form a replica set.
Define shard key and chunk. Describe what MongoDB does as a sharded collection grows, and when a new shard is added to the cluster.
Show model answer
The shard key is the field, or combination of fields, chosen by the data modeler that defines the partition space of the collection: its values are ordered like points on a line, from MinKey to MaxKey. A chunk is a contiguous range of shard-key values, a segment of that line, together with the documents whose key falls in it. A newly sharded collection starts as a single chunk. When a chunk exceeds the maximum chunk size — 64 MB by default according to the slides, 128 MB in current versions — MongoDB splits it at a shard-key value into two chunks; a split only changes the metadata on the config servers and moves no data. The balancer then migrates whole chunks from the shards that hold more to the shards that hold fewer, so that the chunks are distributed evenly; when a new shard is added, chunks are migrated to it. The application keeps working throughout, because mongos routes with the updated chunk map.
A complete answer keeps the two mechanisms apart — split (metadata only) and migration (data moves) — and gives the number. Give the slide's 64 MB, and mention the current 128 MB in one clause.
A hospital heating management system stores one document per sensor reading, { deviceId, timestamp, kwh }, in a sharded MongoDB collection. Readings arrive continuously from many devices; most queries ask for the readings of one device in a time window. Compare a ranged shard key on timestamp, a hashed shard key on timestamp, and the composite shard key { deviceId, timestamp }. Which would you choose, and why?
Show model answer
A ranged key on timestamp keeps time windows together, so a time-window query is targeted, but timestamps grow monotonically: every new reading falls into the last chunk, the one bounded by MaxKey, so all inserts hit a single shard — a hot spot — and adding shards does not increase write throughput. A hashed key on timestamp applies MD5 to the value: inserts are spread evenly over chunks and shards, but neighbouring timestamps are scattered, so every time-window query must be broadcast to all shards; only an equality on one exact timestamp is targeted. The composite key { deviceId, timestamp } orders documents by device first and by time within a device: inserts from many devices spread over many chunks, and a query for one device in a time window covers one contiguous range of the key, so mongos targets one shard or a few. I would choose { deviceId, timestamp }; a query on time alone, without deviceId, would be broadcast, which is acceptable if it is rare.
This is the hook of the lesson as an exam question, and the composite key is the slide's own (p. 331). For each key name three effects — where the inserts go, which queries are targeted, which are broadcast — and the comparison writes itself.
According to the lecture, which two CAP properties does MongoDB focus on? Explain how a MongoDB replica set behaves during a network partition, and which property it gives up.
Show model answer
The lecture places MongoDB on the C–P edge of the CAP triangle: it focuses on Consistency and Partition tolerance, and the course notes call it a CP architecture. Each replica set has a single primary that accepts all writes, while the secondaries replicate them. If a network partition splits a replica set, only the side that can reach a majority of the members keeps or elects a primary; a primary left on the minority side steps down and refuses writes. Clients that can reach only the minority side receive errors, so availability is sacrificed there. In exchange, only the majority side's writes survive: whatever the old primary accepted before stepping down is rolled back when the partition heals, so the data stays consistent, and the system keeps operating on the majority side despite the partition. What survives a failover therefore depends on the write concern: writes acknowledged by a majority are not lost.
Give the slide's classification first (C and P, p. 336), then the mechanism. The single primary and the majority rule are background, not slide text — they are the "why" behind the slide's label.
Check yourself
Shard 1 holds a 70 MB chunk, above the slide's 64 MB maximum, and MongoDB splits it. Before the balancer acts, how much data has moved to other shards?
Each of your two app servers runs its own mongos. One mongos crashes and restarts. What is lost?
The readings collection is sharded on { deviceId: 1, timestamp: 1 }. Which filter can mongos send to a single shard?
According to "Which Sharding to use?" (p. 335), which goals require tag-aware sharding? Select all that apply.
The rule: tags when a range must live on particular machines; range or hash when it only has to be spread.
A replica set has three members, and a network partition separates the primary from the two secondaries. What happens?
Why does a hashed shard key spread an ever-growing timestamp evenly over the shards?
Why can't the ranges of the slide's tag example select regions, with the shard key {uId, regionCode}?
Key take-aways
- Sharding is data partitioning run by the database — "Fully automatic", "Configurable", "Transparent" (p. 287) — for four reasons: scale, geo-locality, hardware optimization and lower recovery times (p. 288).
- The shard key, chosen by the data modeler, orders the documents on a line from MinKey to MaxKey; a chunk is a segment of that line, and a shard is a node of the cluster holding some chunks (pp. 289, 324).
- mongod stores; mongos routes, decides "how many and which" shards get a query, collates, and keeps no local data, so there can be one or many; the config servers store the chunk ranges and their locations. The slides allow a shard to be a single mongod and 1 or 3 config servers; today both are replica sets.
- A collection starts as one chunk; past the maximum size (64 MB on the slide, 128 MB today) a chunk is split, which changes only the map, and the balancer migrates whole chunks until the shards are even, also onto new shards. Auto-sharding takes two steps: enable sharding for the database, shard the collection.
- Range keeps neighbours together: range queries are targeted, but an always-growing key sends every insert to one shard. Hash is range over MD5 values: even writes, broadcast range queries, targeted equality. Tag-aware pins key ranges to tagged shards, and the tag field must lead the key.
- The slide puts MongoDB on the C–P edge (p. 336): each replica set has one primary, and the side of a partition without a majority refuses writes — availability given up, consistency kept.
What to watch and read
-
Distributed Systems in One Lesson
Tim Berglund, Devoxx Poland
A coffee shop outgrows one machine: why "buy a bigger box" stops working, then sharding, replication and the choice between waiting and answering stale — the whole background of this lesson told as one story.
-
Sharding
MongoDB manual
The vendor's own pictures of a sharded cluster (shards as replica sets, mongos, config servers) and of ranged against hashed sharding. Read it next to Fig. 2 and the second widget; remember that its numbers are today's, not the slides'.
-
The Secret Lives of Data: Raft
thesecretlivesofdata.com
Click through a leader election and a network partition: the minority side's writes are rolled back when the network heals. Raft is the family MongoDB's replica-set protocol comes from — the mechanism of Fig. 6, animated.
-
Call me maybe: MongoDB
Kyle Kingsbury (Jepsen), 2013
The test behind the 2013 story: a partitioned replica set, the rollback, and the write concerns compared. What "CP" means in practice once the network really breaks.
-
Please stop calling databases CP or AP
Martin Kleppmann, 2015
By the author of the course textbook: why a single-leader system such as MongoDB fits neither corner cleanly, and how to say per operation what is guaranteed. Give the slide's "CP" at the exam; read this to know its limits.