Skip to content
LESSON 07 / 50Intermediatebson storage

Capped Collections & High-Throughput FIFO Queues

Capped collections are fixed-size circular storage queues that overwrite the oldest documents when allocated space is exhausted, guaranteeing natural insertion-order preservation.

Interactive Engine Simulator

BSON Binary Byte Layout Inspector

Explore how MongoDB serializes JSON documents into binary BSON with length headers for O(1) field navigation.

BSON Total Size
61 bytes
Incl. 4B header & 1B \0
Elements Count
4 fields
Type tagged
Field Traversal
O(1) Jump
Via length headers
Max Document Size
16 MB
Hard engine limit
Document Byte Stream (Click to inspect field)
Header:
3d 00 00 00
(4-byte little-endian int32 total length)
0x07"_id":ObjectId (12 bytes)
075f69640065e31f8a3b...(17 B)
0x02"name":UTF-8 String
026e616d65000b000000...(21 B)
0x10"age":32-bit Integer
10616765001d000000(9 B)
0x08"active":Boolean
086163746976650001(9 B)
Terminator:
00
(1-byte null terminator 0x00)
0x07

Field "_id" • ObjectId (12 bytes)

17 Bytes total

ObjectId: 4-byte timestamp, 5-byte random value, 3-byte incrementing counter.

Why BSON over JSON? JSON is text-based and requires full stream parsing ($O(N)$) to find an inner property. BSON embeds length headers for each document and string, letting WiredTiger jump directly to the target byte offset in $O(1)$ time.

1. Formal Definition & Architecture Intent

A Capped Collection is a circular fixed-size collection in MongoDB that operates like a circular FIFO buffer. Once allocated disk space or document quota is reached, new insertions overwrite the oldest documents automatically in O(1) time without requiring DELETE locks or index maintenance.

2. Explain Like I'm 5 (Mental Model)

Think of a physical notebook with only 100 pages. Once you fill page 100, you erase page 1 and write on it. The notebook never grows larger, and the oldest note is always erased first.

3. Real-World Architecture Example

Storing real-time application access logs or sensor telemetry with automatic aging.

Sample BSON Documents:
Collection: db.audit_tail
{
  "_id": "ObjectId(\"65b2a1e8c4e09f3e12000010\")",
  "ip": "192.168.1.45",
  "event": "SSH_LOGIN_ATTEMPT",
  "timestamp": "2026-03-01T12:00:00Z"
}

A 5GB capped collection retains the most recent 5GB of access logs without any cron job executing DELETE queries.

4. MQL Implementation Steps

Step 1: Create a capped collection with max byte size and document count
db.createCollection("audit_tail", {
  capped: true,
  size: 5242880, // Max size: 5 Megabytes (mandatory)
  max: 5000       // Max document count (optional)
});
The size parameter is always mandatory when creating capped collections.
Step 2: Tailable cursor listening to real-time incoming writes
const cursor = db.audit_tail.find().tailable({ awaitData: true });
while (cursor.hasNext()) {
  printjson(cursor.next());
}
Tailable cursors remain open like a unix tail -f command.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
No DeletionsDocuments cannot be manually deleted using deleteOne() or deleteMany().
Size ImmobilityUpdates that increase the physical BSON size of an existing document are forbidden.
Natural Orderingfind() queries without an ORDER BY automatically return documents in exact insertion order.

6. Deep Dive: Tailable Cursors & The MongoDB Oplog Engine

MongoDB's most critical internal data structure—the replication Oplog (local.oplog.rs)—is physically implemented as a Capped Collection! Secondaries tail the primary's oplog using tailable awaitData cursors, receiving immediate streaming notifications as soon as new write operations are appended.

// Check if collection is capped:
db.audit_tail.isCapped(); // true
Production Warning: Capped collections cannot be sharded.

7. Architectural Trade-offs

Advantages
  • •Extremely high insertion throughput with zero vacuuming or index fragmentation
  • •Automatic FIFO document aging without background maintenance workers
  • •Supports Tailable Cursors for streaming event architectures
Disadvantages & Gotchas
  • •Documents cannot be manually deleted; updates must not increase document byte size
  • •Cannot be horizontally partitioned (sharded) across multiple clusters

8. Technical Interview Questions

Q1: Why is a Capped Collection significantly faster for write-heavy append workloads than a normal collection with a TTL index?

A TTL index requires continuous B-Tree index scans and active DELETE worker sweeps that lock pages and incur MVCC dead tuple bloat. Capped collections write sequentially into contiguous circular disk blocks, overwriting oldest pages in O(1) time without index deletion overhead.

9. Staff-Level Ready Answer

"Capped collections are fixed-size circular buffers that guarantee strict insertion-order preservation and automatically overwrite the oldest documents when quota is exhausted. They power high-throughput logging and tailable cursor streaming, but cannot be sharded or manually deleted."

10. Quick Knowledge Check

Which of the following operations is strictly forbidden on a Capped Collection?