Skip to content
LESSON 26 / 50Intermediateindexing

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.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 26: TTL (Time To Live) Indexes & Automated Document Expiry

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "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.

Sample BSON Documents:
Collection: db.sessions
{
  "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

Step 1: Create a TTL index expiring documents after 1 hour (3600s)
db.sessions.createIndex(
  { created_at: 1 },
  { expireAfterSeconds: 3600 }
);
created_at field must store a BSON UTC Date (ISODate).
Step 2: Modify expireAfterSeconds on an existing live TTL index
db.runCommand({
  collMod: "sessions",
  index: {
    keyPattern: { created_at: 1 },
    expireAfterSeconds: 7200 // Extended to 2 hours
  }
});
Modifies expiry interval without dropping and rebuilding the index.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
UTC Date Type RequiredIf the indexed field is not a Date (e.g. integer timestamp or string), the document will never expire.
Primary Node DeletionsThe TTL thread runs only on the primary node and replicates deletes to secondaries via the oplog.
Single-Field OnlyTTL 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
Production Warning: Capped collections do not support TTL indexes.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •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

Q1: How can you configure a TTL index so that each document has a completely custom expiration time?

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?