Vineet Ganti
Inside MongoDB, Memcached and Redis
All posts

Data Engineering/Database Engineering · Part 12 of 14

·15 min read

Inside MongoDB, Memcached and Redis

The same storage ideas in three NoSQL systems, all run for real: how MongoDB finds a document and why clustered collections remove a tree walk, Memcached's slab allocator and client-side hashing, and what Redis really loses when it crashes.

DatabasesMongoDBRedisMemcachedNoSQL

The course's view of NoSQL is a useful antidote to marketing: under the API it's the same fundamentals. Pages, B-trees, memory, logs. If you've read post 2 and post 5, you already know most of what follows.

This post covers MongoDB's storage evolution, Memcached's memory allocator, and Redis's durability options. I ran all three for real, including killing Redis four times to see what each persistence setting really loses.

#MongoDB

Mongo stores documents in collections. A document is BSON, a binary form of JSON, and every document has an _id, by default a 12-byte ObjectId. Here's what a real server reports:

✅ ran here · MongoDB 8.0.34
db.serverStatus().storageEngine.name
wiredTiger

ObjectId().toString().length
24

ObjectId("65f1a2b3c4d5e6f708192a3b").getTimestamp()
ISODate('2024-03-13T12:57:23.000Z')

db.t.insertOne({ name: "a" }).insertedId.constructor.name
ObjectId

db.t.stats().wiredTiger.creationString.match(/(internal_page_max|leaf_page_max)=\w+/g)
[
  'internal_page_max=4KB',
  'leaf_page_max=32KB'
]

The ObjectId carries a timestamp, so it's time-ordered, and for the reasons in post 4 that's good for a B-tree.

#Three eras of finding a document

The course's article traces how the path to a document changed.

MMAPv1 indexes pointed at a DiskLoc, a file number and an offset. One index walk, then a direct read. Its weakness was concurrency: a global write lock at first, then a lock per collection. And a document that grew might have to move, changing its location. MongoDB 4.2 removed it.

WiredTiger, acquired in 2014, brought document-level concurrency, compression and MVCC. Documents live in a hidden tree keyed by a 64-bit recordId, and every index, including _id, points at the recordId. So a lookup by _id is two tree walks. Keeping that value small keeps indexes small.

Clustered collections arrived in 5.3. The _id tree holds the documents in its leaves, which is the same design as InnoDB. One walk, and secondary indexes hold _id, so a long _id costs what a long InnoDB primary key costs (post 5).

Here are the plans for a normal collection:

✅ ran here · MongoDB 8.0.34
db.users.insertMany(Array.from({ length: 100000 }, (_, i) => ({ _id: i, name: "user" + i, age: i % 80 }))).acknowledged
true

db.c_users.drop()
true

db.createCollection("c_users", { clusteredIndex: { key: { _id: 1 }, unique: true } }).ok
1

db.c_users.insertMany(Array.from({ length: 100000 }, (_, i) => ({ _id: i, name: "user" + i, age: i % 80 }))).acknowledged
true

db.users.createIndex({ name: 1 })
name_1

db.c_users.createIndex({ name: 1 })
name_1

db.users.find({ _id: 500 }).explain("executionStats").queryPlanner.winningPlan.stage
EXPRESS_IXSCAN

db.users.find({ name: "user500" }).explain("executionStats").executionStats.totalDocsExamined
1

db.users.find({ name: "user500" }).explain().queryPlanner.winningPlan.stage
FETCH

db.users.find({ name: "user500" }).explain().queryPlanner.winningPlan.inputStage.stage
IXSCAN

db.users.find({ name: "user500" }, { _id: 0, name: 1 }).explain("executionStats").executionStats.totalDocsExamined
0

db.users.find({ age: 7 }).explain("executionStats").queryPlanner.winningPlan.stage
COLLSCAN

The stages read like Postgres plans. FETCH on top of IXSCAN is an index scan with a heap visit. With a projection that only needs name, totalDocsExamined is 0, which is a covered query, an index-only scan under another name. No index on age gives COLLSCAN, a table scan. The first line is new in 8.0: an EXPRESS path for simple lookups by _id.

Now a clustered collection with the same data:

✅ ran here · MongoDB 8.0.34
db.users.insertMany(Array.from({ length: 100000 }, (_, i) => ({ _id: i, name: "user" + i, age: i % 80 }))).acknowledged
true

db.c_users.drop()
true

db.createCollection("c_users", { clusteredIndex: { key: { _id: 1 }, unique: true } }).ok
1

db.c_users.insertMany(Array.from({ length: 100000 }, (_, i) => ({ _id: i, name: "user" + i, age: i % 80 }))).acknowledged
true

db.users.createIndex({ name: 1 })
name_1

db.c_users.createIndex({ name: 1 })
name_1

db.c_users.find({ _id: 500 }).explain("executionStats").queryPlanner.winningPlan.stage
EXPRESS_CLUSTERED_IXSCAN

db.adminCommand({ fsync: 1 }).ok
1

db.users.stats().indexSizes
{
  _id_: 1093632,
  name_1: 1200128
}

db.c_users.stats().indexSizes
{
  name_1: 1376256
}

db.users.stats().storageSize + db.users.stats().totalIndexSize
3661824

db.c_users.stats().storageSize + db.c_users.stats().totalIndexSize
2957312

EXPRESS_CLUSTERED_IXSCAN, and no _id_ index at all: it's gone, because the collection is the index. The whole collection plus indexes came to 2.96 MB, against 3.66 MB. The docs add the limits: it's chosen at creation, and the key must be _id.

Mongo can't run in a browser, but Postgres's jsonb is a close cousin, a binary document format with a real index:

Documents in a relational tableruns in your browser
Mongo isn't available in the browser, but Postgres stores documents too. jsonb is binary, like BSON, and a GIN index can search inside it.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#Memcached

Memcached does one thing: a key-value cache in memory. No persistence, no replication, no query language. Keys are limited to 250 characters and values to 1 MB by default. It's usually placed beside the database:

Request or acknowledgmentMetadata

The protocol is plain text, and you could use it over telnet:

✅ ran here · Memcached 1.6.45
set name 0 3600 3
ana
STORED

get name
VALUE name 0 3
ana
END

set counter 0 0 1
5
STORED

incr counter 3
8

delete name
DELETED

get name
END

The course quotes a view that a cache is often a last resort: it papers over a slow query, and adds a second copy that can go stale.

#Slabs

The interesting part is memory. Allocating and freeing items of all sizes fragments memory over time, so Memcached doesn't. It splits memory into 1 MB pages, assigns each page to a slab class, and cuts it into equal chunks. Each class's chunks are 1.25 times larger than the last. An item goes in the smallest chunk that fits:

152 B6,898 per page
192 B5,461 per page
240 B4,369 per page
304 B3,449 per page
384 B2,730 per page
480 B2,184 per page
600 B1,747 per page
A 300-byte item goes in class 6, a 304-byte chunk, wasting 4 bytes (1%). With this factor there are 40 classes.

Here's the real thing with three sizes of value, and the limits tested:

✅ ran here · Memcached 1.6.45
-- 2,000 values each of 100, 500 and 5,000 bytes, then:
stats slabs
class  4  chunk   192 bytes   5461 chunks per 1 MB page  2000 in use
class  9  chunk   600 bytes   1747 chunks per 1 MB page  2000 in use
class 19  chunk  5680 bytes    184 chunks per 1 MB page  2000 in use

get <a 251-character key>
CLIENT_ERROR bad command line format

set big 0 0 2000000   -- a 2 MB value
SERVER_ERROR object too large for cache

-- 16,000 more values of 5,000 bytes, about 80 MB, into a 64 MB cache
evictions: 6776
get fill-0: miss, evicted
get fill-15999: hit

A 100-byte value took a 192-byte chunk, since each item carries a key and a header too. The last block shows the cache behaving as a cache: past its 64 MB limit, it evicted 6,776 items, the oldest first. Eviction is per slab class, which has a catch the course points out: a class can be starved while another has spare pages.

🎓 The course also traces how LRU locking evolved, from a global lock to a lock per class, then to the 2018 segmented design. Each item used to be moved to the front of the list on read, and that needs a lock, so reads are now batched, updating at most once a minute. I didn't test that.

#Servers that don't know each other

Memcached servers never talk. A client holds a list of servers, and hashes each key to pick one, the same idea as post 7. That makes it trivially scalable, and it means that losing a server only loses its keys:

✅ ran here · Memcached 1.6.45
-- 3,000 keys, client-side hash over 3 servers
server 1: 1000 items
server 2: 1000 items
server 3: 1000 items

$ docker kill server2
-- read all 3,000 keys again
hits: 2000
lost with server 2: 1000
the other servers never noticed

A real client should use a ring, or adding a server moves most keys. There's also no authentication by default, so never expose it to a network. The course notes that UDP was turned off by default in 2018 after it was used in huge reflection attacks.

#Redis

Redis is also in memory, and goes much further: strings, lists, sets, hashes, streams, pub/sub, replication and clustering. Its creator's bet is that memory is the primary store, with disk as a backup.

#One thread

Redis runs commands on a single thread, which makes every command atomic with no locks. The course discusses this as a basic trade-off. The numbers show the effect of removing round trips:

✅ ran here · Redis 8.0.6
$ redis-benchmark -t set,get -n 100000 -c 50
SET: 68775.79 requests per second,
GET: 69252.08 requests per second,

$ redis-benchmark -t set -n 100000 -c 50 -P 16   # pipelining 16 commands
SET: 1020408.19 requests per second,

$ redis-cli info server; redis-cli config get io-threads
multiplexing_api:epoll
io_threads_active:0
io-threads
1

About 69,000 requests a second with 50 clients, and over a million with pipelining, which sends many commands without waiting for each reply. That's a 15-fold gain from the same thread: most of the time was going on network round trips. Newer versions can use I/O threads for the network work, off by default here, while commands still run one at a time.

#The wire

The protocol, RESP, is simple enough to read by eye:

✅ ran here · Redis 8.0.6
-- SET name ana, as it goes over TCP
*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$3\r\nana\r\n

-- the reply
+OK\r\n

-- GET name, and its reply
*2\r\n$3\r\nGET\r\n$4\r\nname\r\n
$3\r\nana\r\n

#Expiry and pub/sub

The features the course's demo covers, over real connections:

✅ ran here · Redis 8.0.6
> SET session:1 ana EX 2
+OK

> TTL session:1
:2

> GET session:1
ana

-- 2.3 seconds later
> GET session:1
(nil)

> EXISTS session:1
:0
✅ ran here · Redis 8.0.6
-- connection 1
> SUBSCRIBE news
-- connection 2
> PUBLISH news hello
subscribers reached: 1
connection 1 received: message news hello

-- connection 3 subscribes after the message was sent
received nothing: messages aren't stored

Pub/sub is fire and forget. A subscriber that isn't listening misses the message, because nothing is stored. Use streams if that matters.

#What survives a crash?

Post 1 killed Postgres with SIGKILL. Here's the same test on Redis, with each persistence option:

Data

✅ ran here · Redis 8.0.6 · four settings, four kills
-- one client sets keys in a loop for about 3 seconds, the server is killed, then restarted
no persistence              1411 writes/s   acknowledged   5230   survived      0   lost 5230
RDB snapshot only           1499 writes/s   acknowledged   5633   survived   5398   lost 235
AOF, fsync every second     1484 writes/s   acknowledged   5506   survived   5506   lost 0
AOF, fsync always            167 writes/s   acknowledged    619   survived    619   lost 0
SettingLostCost
No persistenceEverythingNone
RDB snapshotsWhat came after the last snapshotAlmost none
AOF, everysecNothing here, up to a second on a power cutAlmost none
AOF, alwaysNothingAbout 9 times slower

This has the same caveat as post 1: a process kill leaves the operating system's cache alive, which is why everysec lost nothing. Redis had already handed its writes to the OS. A real power cut could cost up to the last second, as the docs say. Note the always row: 167 writes a second, which is the true price of fsync, the same trade Postgres makes with synchronous_commit.

The course's Q&A on persistence makes the distinction well: durability is about what happens after you're told the write succeeded. With Redis that's a setting you choose.

#Choosing between them

They aren't competitors in most designs. Mongo is a primary store, Memcached is a cache, and Redis can be a cache or a small primary store, if you've thought through its durability.

#Things that can trip you up

  • Assuming NoSQL means different physics. It's still pages, trees and logs.
  • A long _id in a clustered collection. Every secondary index carries it.
  • Reading a Mongo plan as magic. FETCH over IXSCAN means an index scan plus a document read.
  • Treating a cache as storage. Memcached can evict anything at any moment.
  • Slab imbalance. Items of a new size can get evicted while other classes hold spare memory.
  • Open Memcached or Redis ports. Neither should face the internet.
  • KEYS * on a busy Redis. One thread means one slow command stalls everyone.
  • Assuming Redis is durable by default. Check what your deployment is set to.
  • Pub/sub as a queue. Messages aren't stored.

#Reproduce this yourself

  1. ✅ MongoDB: docker run --name mg -d mongo:8.0, then docker exec -it mg mongosh, and the commands above.
  2. ✅ Memcached: docker run --name mem1 -p 11211:11211 -d memcached:1.6 -m 64, then telnet localhost 11211. stats slabs shows the classes.
  3. ✅ Redis: docker run --name rdb -d redis:8.0, and docker exec -it rdb redis-cli.
  4. ✅ For the crash test, start Redis with the flags you want, such as redis-server --appendonly yes --appendfsync everysec, write in a loop, count the acknowledgements, run docker kill -s KILL, restart, and compare with DBSIZE.
  5. ✅ For the benchmark, docker exec rdb redis-benchmark -q -t set,get -n 100000 -c 50, then add -P 16.

#Glossary

TermMeaning
BSONThe binary document format MongoDB stores
_id, ObjectIdA document's key, by default 12 bytes with a timestamp
WiredTigerMongoDB's B-tree storage engine
recordIdA hidden 64-bit key for a document
Clustered collectionDocuments stored in the _id tree
Slab classA set of equal-sized chunks in Memcached
Cache asideCheck the cache, read the database on a miss, then fill the cache
RDBA Redis point-in-time snapshot file
AOFA Redis append-only log of writes
RESPThe Redis wire protocol
PipeliningSending many commands without waiting for each reply

#Summary

MongoDB's history is the B-tree story again: direct locations, then a hidden record tree that keeps indexes small, then clustered collections that remove a walk, with InnoDB's trade-offs. Memcached is proudly simple, with slabs to avoid fragmentation, and clients doing all the routing. Redis keeps everything in memory, on one thread, and lets you choose how much you're prepared to lose, and killing it shows exactly what each choice means.

#Concepts at a glance

ConceptIn one lineWhy it matters
recordIdIndexes point at a hidden keySmall indexes, two walks
Clustered collectionDocuments live in the _id treeOne walk, wide keys cost more
FETCH over IXSCANIndex, then documentMongo plans read like SQL plans
Slab classesFixed chunks in growing sizesNo fragmentation, some waste
Per-class LRUEviction within a classOne class can starve
Client-side hashingServers never talkSimple scaling, simple failure
Single threadCommands run one at a timeAtomic, and one slow command stalls all
PipeliningSkip the wait for each replyRound trips were the real cost
RDB and AOFSnapshot or logChoose what a crash can lose

#Test yourself

Why does a normal MongoDB lookup by _id take two tree walks, and how does a clustered collection avoid that?

The _id index maps the key to a recordId, and a hidden tree maps that to the document. A clustered collection stores documents in the _id tree's leaves, so one walk finds the document. Secondary indexes then hold _id.

totalDocsExamined is 0 for a Mongo query. What does that mean, and what's the SQL equivalent?

The index alone answered it, so no document was read. That's a covered query, the same idea as an index-only scan.

A 100-byte value lands in a 192-byte chunk. Why?

The item also has a key and a header, so it needs more than 100 bytes, and it goes in the smallest class that fits. The unused part of the chunk is wasted, which is the price of avoiding fragmentation.

Memcached server 2 dies. What happens to keys on servers 1 and 3?

Nothing. The servers never talk, so they don't notice. Only server 2's keys become misses, and clients fall back to the database for those.

Why did AOF with everysec lose nothing when Redis was killed, and when could it lose data?

Redis had already handed the writes to the operating system, which survives a process kill. A power cut or OS crash could lose up to the last second, because those writes might not have reached the disk.

#Open questions and gaps

  • 🎓 Memcached's LRU history and MongoDB's MMAPv1 details are from the course. MMAPv1 is gone, so it can't be re-run.
  • I didn't test Redis replication or clustering, or Memcached's UDP history.
  • I didn't test power loss, so the everysec limit rests on the docs.
  • The Mongo size comparison is on 100,000 small documents, and won't scale in a simple way.

#Sources