Redis Caching Strategies for High-Traffic Applications: Cache-Aside, Write-Through & Eviction

The Caching Imperative in Modern Microservices

Relational databases and document stores are built for transactional integrity and persistence, not sub-millisecond read throughput at scale. When high-traffic events occur (flash sales, viral articles, breaking news), hitting PostgreSQL, MySQL, or MongoDB on every incoming HTTP request saturates database connection pools and causes cascading timeout failures.

Redis (Remote Dictionary Server) operates entirely in memory, delivering sub-millisecond response times at hundreds of thousands of operations per second. However, introducing a cache layer adds the legendary challenge of distributed systems: cache consistency, invalidation strategies, and thundering herd mitigation.

In this guide, we evaluate production caching patterns, configure memory eviction algorithms, and build stampede-proof caching middleware.


Architectural Caching Patterns Compared

PatternData FlowConsistencyComplexityPrimary Production Use Case
Cache-Aside (Lazy Loading)App reads Cache $
ightarrow$ on Miss reads DB $
ightarrow$ Populates Cache
Eventual (Cache can become stale)LowGeneral read-heavy web apps, blog posts, user profiles
Write-ThroughApp writes to Cache $
ightarrow$ Cache synchronously writes to DB
High (Cache & DB always in sync)MediumFinancial ledgers, real-time inventory counts
Write-Behind (Write-Back)App writes to Cache $
ightarrow$ Cache asynchronously flushes to DB
Eventual (Risk of data loss on crash)HighAnalytics event counters, gaming leaderboards, IoT streams
Refresh-AheadCache automatically reloads hot keys before TTL expiresHigh for predictable accessMediumHigh-frequency market tickers, weather data

1. Implementing Cache-Aside with Distributed Mutex Locks

The standard Cache-Aside pattern suffers from the Cache Stampede (Thundering Herd): when a popular cache key expires, thousands of concurrent requests simultaneously observe a cache miss and hit the database at the exact same millisecond.

Prevent stampedes by acquiring a short-lived Redis mutex lock using SET NX EX:

// cache-aside-safe.ts
import { Redis } from 'ioredis';

const redis = new Redis({ host: 'localhost', port: 6379 });

export async function getOrSetCache<T>(
  key: string,
  ttlSeconds: number,
  fetchFromDb: () => Promise<T>
): Promise<T> {
  // 1. Try reading from cache
  const cachedData = await redis.get(key);
  if (cachedData) {
    return JSON.parse(cachedData) as T;
  }

  // 2. Cache Miss: Attempt to acquire mutex lock to query DB
  const lockKey = `lock:${key}`;
  const acquiredLock = await redis.set(lockKey, 'locked', 'EX', 5, 'NX');

  if (acquiredLock) {
    try {
      // Sole worker fetching from database
      const freshData = await fetchFromDb();
      await redis.set(key, JSON.stringify(freshData), 'EX', ttlSeconds);
      return freshData;
    } finally {
      // Release mutex lock
      await redis.del(lockKey);
    }
  } else {
    // Another worker is already populating the cache; wait and retry
    await new Promise((resolve) => setTimeout(resolve, 50));
    return getOrSetCache(key, ttlSeconds, fetchFromDb);
  }
}

2. Configuring Redis Memory Eviction Policies

When Redis reaches its maximum configured memory (maxmemory), it must decide which keys to evict. Configure this in redis.conf based on your architecture:

# Set maximum RAM ceiling
maxmemory 2gb

# Choose eviction policy:
# 1. volatile-lru: Evict least recently used keys WITH an explicit TTL (Recommended)
# 2. allkeys-lru: Evict least recently used keys regardless of TTL
# 3. volatile-lfu: Evict least frequently used keys (Great for long-tail traffic)
# 4. noeviction: Return error on writes when RAM is full (Crucial for job queues)
maxmemory-policy volatile-lru

Frequently Asked Questions (FAQ)

What is Cache Penetration and how do I prevent it?

Cache Penetration occurs when requests query keys that exist neither in the cache nor in the database (e.g. malicious crawlers requesting random user IDs). Because the key is never cached, every request hits the database. Prevent this by caching null results with a short TTL (e.g. SET key "null" EX 60) or placing a Bloom Filter in front of the cache.

How do I handle cache invalidation cleanly?

Never rely solely on long TTLs. When updating an entity in your database, execute a proactive invalidation: delete the corresponding cache key (redis.del(key)). If multiple services read this entity, emit a message over Redis Pub/Sub or Kafka to trigger distributed cache eviction.


Continue expanding your technical depth with our related engineering guides:

Published by Mohit Kumar under Database Engineering. Read our companion tutorial on MySQL Query Optimization & B-Tree Indexing.

Related Modular Guides & Next Steps

Authoritative Reference: Consult the Redis Official Documentation for normative standards and release specifications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top