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":

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.

[MinKey, 250) [250, 600) [600, MaxKey) MinKey 250 600 MaxKey on shard 1 on shard 2 on shard 1 deviceId 560 → chunk [250, 600) → shard 2
Fig. 1. "Key space is like points on a line", "Range is a segment of that line" (p. 324), drawn for the shard key 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.

mongos shard 1 shard 2 shard 3 1 2 1 2 1 2 3 4 3 4 3 4 5 6 5 6 5 6 primary secondary replication / HA horizontal scaling
Fig. 2. The third panel of "MongoDB is fast and scalable" (p. 295), redrawn with chunks in the boxes. Down a column — "Replication /HA" — the same chunks are copied: a primary (solid squares) and two secondaries (dashed squares), one replica set. Along the row — "Horizontal Scaling" — each column holds different chunks: these are the shards. The slide too draws the top server of each column in a colour of its own.

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.

client 1 4 mongos map config server 2 3 shard 1 shard 2 shard 3 one shard find({ deviceId: 512 })

Targeted: the filter names the shard key

client 1 4 mongos map config server 2 3 shard 1 shard 2 shard 3 collates find({ kwh: { $gt: 5 } })

Broadcast: the filter does not

Fig. 3. The routing slide (p. 326) drawn twice. Left, its numbered path: ① the client's request reaches mongos, ② mongos sends it to the one shard whose chunk holds deviceId 512 — it knows which from the chunk map of the config server — ③ that shard answers, ④ mongos answers the client. Right, a filter without the shard key: every shard must look, and mongos "Collates the results" (p. 321) before answering.

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).

Split, migrate, balance: a collection that grows

The readings collection, sharded on deviceId (0 to 999) over three shards. Each lane is a shard; each chunk is drawn across the keys it covers, filled to its size (full = the slide's 64 MB). Insert adds 40 MB of readings with random deviceIds, and a chunk above 64 MB is split at its middle document. The balancer, when running, moves one chunk at a time from the shard with the most chunks to the one with the fewest, until no two shards differ by two chunks or more — the rule of the slides' era. The slider asks mongos where a deviceId lives. The one thing to see: every chunk lives on exactly one shard — a split cuts chunks, the balancer moves them, and neither copies them.

  1. Press Insert once: one chunk of 40 MB on shard 1. Before pressing again, predict how many chunks there will be at 80 MB, and on which shards.
    What you should see

    Two. The chunk [MinKey, MaxKey) passes 64 MB and is split at deviceId 496 into two chunks of 40 MB, both still on shard 1 — a split moves nothing. The balancer then sees 2 – 0 – 0 and moves [MinKey, 496) to shard 2; with 1 – 1 – 0 no two shards differ by two, so it stops.

  2. Press Start over, switch the balancer off and insert six times. Predict where the 240 MB are. Then switch the balancer on.
    What you should see

    Four chunks, all on shard 1: splits only redraw the map. With the balancer on, two migrations follow — [MinKey, 260) to shard 2, [260, 496) to shard 3 — leaving 2 – 1 – 1 chunks, 124 – 58 – 58 MB. Splitting keeps chunks small; only migrating spreads the data.

  3. Start over with the balancer on, insert six times and read the readouts. Then press Add a shard: predict how many chunks the new shard receives.
    What you should see

    After six inserts the shards hold 1 – 2 – 1 chunks but 63 – 116 – 61 MB: a chunk-counting balancer calls that balanced. The new, empty shard 4 gets one chunk, [MinKey, 260) from shard 2, and the counts become 1 – 1 – 1 – 1 — "MongoDB migrates data to new nodes" (p. 326). Counting megabytes instead of chunks is exactly what MongoDB changed in version 6.0.

  4. Press Start over, insert six times, choose "a single mongod", switch on the failure of shard 2 and set the deviceId to 300. Predict mongos's answer, then press Insert. Finally choose "a replica set" again.
    What you should see

    deviceId 300 lies in [260, 496), a chunk of shard 2, so the lookup fails, and the next insert has 19 of its 40 MB refused: shard 2 held the deviceIds 0 to 495, about half the key space, and nobody else has a copy. With a replica set, a secondary of shard 2 becomes primary and nothing is lost — sharding divides, replication copies, and a shard needs both.

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.

−∞ (1000, 1418244824) (1000, 1418244825) ∞ chunk 1 chunk 2 the cut falls inside device 1000
Fig. 4. The two chunks drawn on p. 331, printed there as "-∞ …1000,1418244824" and "…1000,1418244825 ∞". The timestamp is a Unix time: 1418244824 is 10 December 2014, 20:53:44 UTC (computed). Chunk 1 holds every device below 1000 and device 1000 up to that second; chunk 2 holds device 1000 from the next second on, and every device above it.

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:

\[ \begin{aligned} &\text{Hash Shard Key}(\mathit{deviceId}) \\ &\quad = \text{MD5}(\mathit{deviceId}) \end{aligned} \]
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.

One stream of readings, three shard keys

Six heaters, deviceIds 1000 to 1005, send one reading a minute each from the slide's timestamp 1418244825. Run inserts half an hour of readings (dots) into three shards of one chunk each. Switch the shard key at any time: the same readings are placed again, as if sharded that way from the start. Pick a query to see which shards mongos asks (orange outline) and which readings match (rings); the hash is a simple stand-in for MD5 with the same effect. The one thing to see: the shard key decides at once where every write lands and which queries reach a single shard.

  1. Keep { timestamp: 1 }, the ranged key of the hook. Before pressing Run, predict how the 180 readings of half an hour divide among the three shards.
    What you should see

    0 – 0 – 180: shard 3 takes all of them. Every new timestamp is larger than all the earlier ones, so every reading falls into the chunk that ends at MaxKey — the hot spot. Yet the time-window query is cheap: mongos sends it to shard 3 only.

  2. Switch to { timestamp: "hashed" }. Predict the share of the busiest shard, and how many shards mongos must ask for "the last 10 minutes".
    What you should see

    62 – 63 – 55: the busiest shard takes 35 %, close to a third. But the 60 readings of the last 10 minutes lie on all three shards, so the query is broadcast. Now pick "one exact second": mongos hashes 1418244825 and asks shard 3 alone — equality on a hashed key stays targeted.

  3. Switch to the slide's composite key { deviceId: 1, timestamp: 1 }. Predict the writes, then the routing of "device 1003, last 10 minutes" and of "the last 10 minutes".
    What you should see

    60 – 60 – 60: two devices per shard. Device 1003's window is one stretch of the line, inside the chunk of shard 2: targeted, 10 readings. Without a deviceId, the plain time window has no prefix of the key and is broadcast. This key spreads the writes and keeps the everyday query on one shard.

What the widget shows after half an hour (180 readings, 6 heaters, 3 shards): the writes on shards 1 · 2 · 3, and the shards mongos asks for each query — one shard means targeted, all 3 means broadcast.
Shard keyWritesLast 10 minDevice 1003, last 10 minOne exact second
timestamp, ranged0 · 0 · 180shard 3shard 3shard 3
timestamp, hashed62 · 63 · 55all 3all 3shard 3
deviceId + timestamp, ranged60 · 60 · 60all 3shard 2all 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.

"Tag Sharding Example" (p. 334): the ranges as printed, with the callouts "Assign Regions 1-50 to the West" and "Assign Regions 51-100 to the East" — and the corrected version (red pen below). A range includes its start and excludes its end.
Shard keyWest: Shard1, Shard2East: Shard3, Shard4
As printed{uId, regionCode}MinKey, MinKey → MaxKey,50MinKey, 50 → MaxKey, MaxKey
Corrected{regionCode, uId}(MinKey, MinKey) → (51, MinKey)(51, MinKey) → (MaxKey, MaxKey)
u1, 12 u2, 63 u3, 7 u4, 88 u5, 31 u6, 51 MinKey MaxKey West ends at (MaxKey, 50) East starts at (MinKey, 50) both cover all six users

As printed (p. 334): {uId, regionCode}

7, u3 12, u1 31, u5 51, u6 63, u2 88, u4 MinKey (51, MinKey) MaxKey West: regions 1–50 East: 51–100 one cut separates them

Corrected: {regionCode, uId}

Fig. 5. Six users of the slide's example in shard-key order. Circles: users of regions 1–50, which the slide assigns to the West; squares: regions 51–100, the East. Left, with uId first, the users sit in uId order and the regions alternate: no single stretch of the line holds the West users, and both printed ranges run from before the first user to after the last. Right, with regionCode first, all West users come before all East users, and one cut separates them.

Which sharding to use?

Page 335 closes the loop with the four reasons of p. 288 (the third column is ours).

"Which Sharding to use?" (p. 335), with the reasons added.
UsageRequired StrategyWhy
ScaleRange or Hashmore shards hold and serve more data; any cut of the line spreads the volume
Geo-LocalityTag-awarea region's stretch of the line must live on that region's shards
Hardware OptimizationTag-awarehot ranges on fast shards, cold ones on cheap shards: a placement decision
Lower Recovery TimesRange or Hashsmaller 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".

C A P MongoDB Focus on Consistency and Partition tolerance

p. 336: MongoDB on the C–P edge

partition refused steps down 1 of 3 accepted new primary secondary 2 of 3: a majority one version survives

Why: one primary, chosen by a majority

Fig. 6. Left, the slide's picture (p. 336): the MongoDB logo lies along the edge between C and P; the lightning in the middle is the partition. Right, the mechanism behind it (background, not on the slide): a partition cuts a three-member replica set into one member and two. Only the side with a majority can keep a primary: the two elect one and keep accepting writes, while the lone old primary steps down as soon as it notices and its clients get errors. Availability is lost on the small side; whatever the old primary accepted in those seconds is rolled back, so only one version of the data survives.

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.

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.

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.

  • True The MD5 hash scrambles the order: consecutive values get unrelated hashes, so they scatter over the chunks (p. 332).
  • False Hash sharding distributes data "randomly within the range of MD5 values" (p. 332), so a range query on the key must be broadcast to all shards; only an equality query stays targeted.
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.

  • Sharding spreads different chunks of the data over different shards to scale, while replication keeps copies of the same data for high availability. p. 295: "Horizontal Scaling" along the row of shards, "Replication /HA" down each column.
  • The config servers store the chunk ranges of the cluster and their locations. p. 326: "Stores cluster chunk ranges and locations".
  • mongos stores a copy of the documents it routes, so adding mongos instances adds storage capacity. mongos has "No local data (persists to config database)" (p. 329); capacity grows by adding shards.
  • Geo-locality and hardware optimization require tag-aware sharding. p. 335; scale and lower recovery times take "Range or Hash".
  • A chunk that exceeds the maximum chunk size is moved, whole, to the shard with the fewest chunks. It is first split (p. 325); moving chunks is the balancer's separate decision, taken when shards are uneven.
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?

  • Half of the chunk, about 35 MB, to the emptiest shard That would be a migration — a separate step, decided later by the balancer.
  • None: both halves stay on shard 1, and only the chunk map on the config servers changes A split cuts a range at a key value; no document leaves the shard.
  • The whole 70 MB chunk, to the shard with the fewest chunks Chunks are moved whole, but only by the balancer, and only when the shards are uneven.
  • A copy of each half to every other shard, for safety Sharding never keeps a chunk on two shards; copies are the replica set's job.

Each of your two app servers runs its own mongos. One mongos crashes and restarts. What is lost?

  • Nothing: mongos keeps no data of its own and reads the chunk map from the config servers again "No local data (persists to config database)" (p. 329).
  • The documents written through it in the last minutes Writes are stored by the shards' mongod processes, not by the router.
  • The chunk map, so the collection must be sharded again The map lives on the config servers; mongos only caches it.
  • The chunks routed through it, until the balancer moves them back Chunks live on shards; a router owns none.

The readings collection is sharded on { deviceId: 1, timestamp: 1 }. Which filter can mongos send to a single shard?

  • { timestamp: { $gte: 1418246025 } } No deviceId, so no prefix of the key: every device has readings in the window, and the query is broadcast.
  • { deviceId: 1003, timestamp: { $gte: 1418246025 } } Device 1003's readings form one stretch of the line, ordered by time: targeted.
  • { kwh: { $gt: 5 } } Not a shard-key field at all: broadcast.
  • { timestamp: 1418244825 } An exact timestamp, but without deviceId the readings of that second may sit in any chunk: broadcast.

According to "Which Sharding to use?" (p. 335), which goals require tag-aware sharding? Select all that apply.

  • Geo-locality Keeping each region's data on servers in that region means pinning key ranges to chosen shards.
  • Hardware optimization Recent data on fast shards, old data on cheap ones: again a placement decision.
  • Scale Spreading the volume needs any cut: "Range or Hash".
  • Lower recovery times Smaller shards restore faster whatever the cut: "Range or Hash".

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?

  • The two secondaries elect a new primary; the old primary steps down and refuses writes — availability is lost on its side, consistency is kept Only the majority side can keep a primary; anything the old primary accepted before stepping down is rolled back, so one version of the data survives.
  • Both sides keep a primary and accept writes, and the writes are merged when the partition heals That is the AP behaviour: two primaries accepting conflicting writes.
  • The whole replica set stops accepting writes until the partition heals The majority side can still elect a primary and keep working.
  • The old primary keeps accepting writes, because it was primary first A primary that cannot see a majority steps down; seniority does not count.

Why does a hashed shard key spread an ever-growing timestamp evenly over the shards?

  • Consecutive timestamps get unrelated hash values, so new readings fall into all the chunks, not only the last one The chunks are ranges of hash values, and the hash scatters neighbours.
  • Because the balancer migrates hashed chunks more often The balancer is the same; what changes is where each insert lands in the first place.
  • Because MongoDB sends hashed documents to the shards in turn, round-robin The hash decides the place, not the order of arrival.
  • Because hashing makes the chunks smaller, so more of them fit on each shard The chunk size is unchanged; only the positions on the line are scrambled.

Why can't the ranges of the slide's tag example select regions, with the shard key {uId, regionCode}?

  • A composite key is compared field by field, so a range from MinKey to MaxKey in uId contains every user, whatever the region The region only orders users that tie on uId; it must lead the key to be cut on.
  • Because MinKey and MaxKey cannot appear in tag ranges They can: they are the two ends of the line.
  • Because regionCode is a number and uId a string Types are not the issue; the order of the fields is.
  • Because a tag range must start at MinKey Any stretch of the line can be tagged: the corrected East range starts at (51, MinKey).

Key take-aways

What to watch and read