Course contentsShow
← Node.js
Lesson 1383 of 1,98012. Caching Strategies and Application SpeedFree lesson

Tiered Expiration Logic

You will apply different TTLs based on user authority and cache access frequency.

In this lesson, you will learn how to optimize cache memory and performance by applying dynamic Time-To-Live (TTL) values based on user authority and the frequency of cache access.

The Problem with "One Size Fits All" TTLs

In high-scale Node.js applications, a static TTL (e.g., setting every cache entry to expire in 60 minutes) is often inefficient. If your cache is flooded with data, you risk evicting high-value items to make room for low-value ones. Tiered Expiration Logic allows you to prioritize your cache memory by assigning shorter or longer TTLs based on the context of the data request.

Applying Tiered Logic

You can categorize your cache items into tiers. For example:

  1. High-Authority/Frequent Users: Users with administrative privileges or active sessions often require the most current data. You might set a shorter TTL here to ensure consistency and frequent refreshes.
  2. Low-Frequency/Public Data: Content that rarely changes and is accessed by many users can have a very long TTL to maximize hit rates and reduce backend load.
  3. High-Access "Hot" Keys: Even if the data isn't "important," if it is requested thousands of times per minute, keeping it cached longer avoids constant re-computation.

Consider this implementation snippet using a simple wrapper:

function getTTL(userRole, accessCount) {
  if (userRole === 'admin') return 300; // 5 minutes (Freshness)
  if (accessCount > 1000) return 3600;  // 1 hour (Hot data)
  return 1800; // Default 30 minutes
}

// Usage
const ttl = getTTL(user.role, cacheMetadata.accessCount);
redisClient.set(key, JSON.stringify(data), 'EX', ttl);

By decoupling your expiration strategy from the data type and attaching it to the access pattern, you preserve your limited memory footprint for the data that actually moves the needle for your application. This prevents "cache churning," where frequently updated, high-importance items are evicted prematurely by stale, low-priority data.

Key Takeaway: Tiered Expiration Logic ensures that memory is allocated to the most valuable data by aligning TTLs with user authority and access intensity rather than applying a blanket expiration policy.