Skip to content
LESSON 08 / 50Intermediatebson storage

GridFS Binary Chunking Architecture

GridFS splits binary files exceeding the 16MB document boundary into standardized 255KB chunks across two collections: fs.files and fs.chunks.

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

GridFS is a driver-level specification and storage abstraction for storing files that exceed the 16MB BSON document size limit. Instead of storing a file in a single document, GridFS divides the file into contiguous 255KB chunks stored in a chunks collection (fs.chunks) and stores file metadata in a companion collection (fs.files).

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

If you have a 100MB video, you cannot fit it into a single 16MB box. GridFS slices the video into 400 small 255KB sandwich bags, numbers them from 0 to 399, and puts a label in an index book so you can reassemble them in order.

3. Real-World Architecture Example

Storing a 50MB PDF report in MongoDB.

Sample BSON Documents:
Collection: db.fs.files
{
  "_id": "ObjectId(\"65b2a1e8c4e09f3e12000050\")",
  "length": 52428800,
  "chunkSize": 261120,
  "filename": "annual_report_2026.pdf",
  "contentType": "application/pdf"
}
Collection: db.fs.chunks
{
  "_id": "ObjectId(\"65b2a1e8c4e09f3e12000051\")",
  "files_id": "ObjectId(\"65b2a1e8c4e09f3e12000050\")",
  "n": 0,
  "data": "BinData(0, \"...255KB of raw binary...\")"
}

Drivers reconstruct the file stream on-the-fly by querying fs.chunks sorted by { files_id: 1, n: 1 }.

4. MQL Implementation Steps

Step 1: Upload a file via mongofiles CLI
mongofiles -d media_store put backup.tar.gz
Automatically fragments into fs.chunks and fs.files.
Step 2: Query GridFS file metadata in mongo shell
db.fs.files.find({ filename: "annual_report_2026.pdf" });
Inspect file length, uploadDate, and md5 hash.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Chunk SizeDefault chunk size is 255 KB (261,120 bytes).
Compound Unique Indexfs.chunks requires a compound unique index on { files_id: 1, n: 1 } to guarantee stream reassembly order.

6. Deep Dive: Range Requests & Streaming Video

GridFS allows clients to stream files and perform range queries (e.g. HTTP 206 Partial Content for video seeking). Drivers can calculate the exact chunk index: chunk_n = Math.floor(byte_offset / chunkSize), fetching only the required 255KB chunk instead of loading the entire multi-gigabyte file into memory.

// Index enforced automatically on fs.chunks:
db.fs.chunks.createIndex({ files_id: 1, n: 1 }, { unique: true });
Production Warning: GridFS does not provide atomic multi-file updates; updating a file typically writes a new version.

7. Architectural Trade-offs

Advantages
  • •Enables storing files of arbitrary size (gigabytes) within MongoDB
  • •Supports random byte access and streaming playback without reading the entire file
  • •File chunks inherit MongoDB replication, sharding, and automatic failover
Disadvantages & Gotchas
  • •Serving static files from MongoDB is slower than dedicated Object Storage (AWS S3) combined with a CDN
  • •Modifying a portion of a file requires updating chunks or rewriting the stream

8. Technical Interview Questions

Q1: How does GridFS enable range requests for video playback?

Because GridFS divides files into deterministic 255KB chunks indexed by sequence number n, an HTTP byte-range request (e.g. bytes 500000-800000) can calculate exactly which chunks are needed (chunk 1 and 2), querying only those specific chunk documents from fs.chunks.

9. Staff-Level Ready Answer

"GridFS is MongoDB's specification for storing files exceeding 16MB. It stores file metadata in fs.files and partitions the raw binary into 255KB chunks in fs.chunks with a unique index on { files_id: 1, n: 1 }. It enables streaming and range seeks, though dedicated cloud storage like S3 is preferred for high-volume static media."

10. Quick Knowledge Check

What is the default chunk size used by MongoDB GridFS?