Course contentsShow
← Node.js
Lesson 835 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Implementing TTL for Data Expiration

You will set automated record expiration for transient or ephemeral data.

Implementing TTL for Data Expiration

In this lesson, you will learn how to automatically purge short-lived, ephemeral data from your database using Time-To-Live (TTL) indices.

When building applications, we often generate data that is only relevant for a short period—such as email verification codes, temporary session tokens, or caching results for an API. Manually writing scripts to find and delete these records every few minutes is inefficient and prone to errors. Instead, we can offload this responsibility to the database engine itself using a TTL index.

How TTL Works

A TTL index is a special type of index that automatically removes documents from a collection after a certain amount of time. You define a field in your document (usually a createdAt timestamp) and tell the database how many seconds to wait after that time before it should delete the record.

If you are using a document store like MongoDB, you can implement this directly within your schema definition or via your ORM/ODM configuration:

// Setting an index that expires documents 3600 seconds (1 hour) 
// after the 'createdAt' timestamp
const SessionSchema = new Schema({
  token: String,
  createdAt: { type: Date, default: Date.now }
});

// Create the TTL index
SessionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 3600 });

Why Use TTL?

By using a TTL index, you ensure that your database doesn’t grow indefinitely with "garbage" data. Because the database engine handles the deletion internally, it is far more performant than performing a deleteMany query from your Node.js application, which would require pulling data over the network and creating unnecessary load on your database server.

Remember that TTL indices rely on the field type being a Date object. If you update the timestamp on a document, the clock resets, which is a great way to "refresh" the expiration of a session if a user remains active.

Key Takeaway: TTL indices allow your database to self-clean by automatically removing ephemeral records after a defined duration, keeping your storage lean without requiring manual application logic.