Problem Statement
What is the role of journaling in MongoDB?
Explanation
Journaling in MongoDB is a write-ahead logging mechanism that ensures data durability and enables crash recovery. Before applying changes to data files, MongoDB writes operations to the journal, a durable log file on disk.
If MongoDB crashes or shuts down unexpectedly, it can replay the journal on restart to recover any writes that occurred after the last checkpoint. This prevents data loss and ensures consistency. The journal is especially important for single-server deployments, though replica sets provide additional durability through replication.
Code Solution
SolutionRead Only
// Journaling configuration
storage:
journal:
enabled: true
commitIntervalMs: 100 // Flush journal every 100ms
// WiredTiger journal behavior:
// - Write operations first go to journal
// - Journal flushed to disk every 50-100ms
// - Checkpoints written every 60 seconds
// - On crash: replay journal from last checkpoint
// Journal ensures durability:
// Time 0: Write operation
// Time 50ms: Written to journal (durable)
// Time 2s: Written to data files (checkpoint)
// Crash at 1s: Data recovered from journal
// Check journal status
db.serverStatus().wiredTiger.log