TTL (Time To Live) Indexes & Automated Document Expiry
TTL indexes automatically purge documents from collections after a designated time interval based on a date timestamp field, replacing custom cron cleanup jobs.
Index Traversal & IXSCAN vs COLLSCAN Execution Plan
Topic 26: TTL (Time To Live) Indexes & Automated Document Expiry
{
"queryPlanner": {
"winningPlan": {
"stage": "FETCH",
"inputStage": {
"stage": "IXSCAN",
"indexName": "role_1_country_1",
"isMultiKey": false,
"direction": "forward"
}
}
},
"executionStats": {
"nReturned": 2,
"executionTimeMillis": 1,
"totalKeysExamined": 2,
"totalDocsExamined": 2
}
}1. Formal Definition & Architecture Intent
A TTL (Time To Live) Index is a specialized single-field index that MongoDB uses to automatically delete documents after a specified number of seconds (expireAfterSeconds). A background thread (the TTLMonitor) runs every 60 seconds, scanning the TTL index B-Tree and purging expired documents.
2. Explain Like I'm 5 (Mental Model)
Think of an expiration date stamped on a carton of milk. Every minute, a store clerk checks the milk aisle and throws away any carton whose date has passed.
3. Real-World Architecture Example
Auto-expiring temporary user login sessions after 24 hours.
{
"session_token": "tok_982172",
"user_id": "u42",
"created_at": "ISODate(\"2026-03-01T10:00:00Z\")"
}Setting expireAfterSeconds: 86400 (24h) guarantees the session is purged automatically.
4. MQL Implementation Steps
db.sessions.createIndex(
{ created_at: 1 },
{ expireAfterSeconds: 3600 }
);db.runCommand({
collMod: "sessions",
index: {
keyPattern: { created_at: 1 },
expireAfterSeconds: 7200 // Extended to 2 hours
}
});5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| UTC Date Type Required | If the indexed field is not a Date (e.g. integer timestamp or string), the document will never expire. |
| Primary Node Deletions | The TTL thread runs only on the primary node and replicates deletes to secondaries via the oplog. |
| Single-Field Only | TTL indexes must be single-field; compound TTL indexes are not supported. |
6. Deep Dive: TTL Monitor Execution Loop & Timing Guarantees
The TTLMonitor thread awakens every 60 seconds. Because it runs once a minute and deletes documents in batches, a document whose TTL expires at 10:00:05 might not be deleted until 10:00:59. Applications requiring exact sub-second expiry must include a filter: { expireAt: { $gt: new Date() } } in query statements.
// Check TTL deletion metrics in serverStatus: db.serverStatus().metrics.ttl; // "deletedDocuments": total expired documents purged
7. Architectural Trade-offs
- •Eliminates custom background cron jobs or worker scripts for data retention cleanup
- •Deletions are automatically sequenced through the replication oplog
- •Supports dynamic per-document expiry by setting expireAfterSeconds: 0 and storing future dates
- •Deletions are not sub-second instantaneous (subject to the 60s TTL thread period)
- •High deletion bursts can create temporary I/O lock contention on primary nodes
8. Technical Interview Questions
Set expireAfterSeconds: 0 on the index, and in each document, store the exact future expiration date/time in the indexed field (e.g. expireAt: ISODate("2026-12-31T23:59:59Z")). When the current time reaches that date, the document expires.
9. Staff-Level Ready Answer
"TTL indexes automatically delete documents after expireAfterSeconds based on a BSON Date field. The TTLMonitor background task runs every 60 seconds on the primary and replicates deletes through the oplog. Custom per-document expiration is achieved by setting expireAfterSeconds: 0 and storing target expiration timestamps."
10. Quick Knowledge Check
What happens to a document in a collection with a TTL index if its indexed timestamp field contains a string instead of an ISODate?