ADVERTISEMENT

Redis Caching Strategies: Cache-Aside, Write-Through & Eviction Policies

📁 System Design & Caching
⏱️ 12 min read • Updated: Sep 2026

Redis Caching Strategies & System Design: From Cache-Aside to Distributed Locks

Redis In-Memory Distributed Caching Architecture with Cache-Aside Pattern, TTL Eviction, and Database Fallback
Caching Summary • Direct Answer

Redis is an in-memory key-value data store used to cache frequently accessed database queries, reduce latency from 50ms down to sub-1ms, and shield primary databases from read overload. The foundational caching patterns include Cache-Aside (lazy loading data on demand), Write-Through (updating cache and database synchronously), and Write-Behind (buffering writes in Redis for asynchronous persistence). Cache memory limits are safely managed via allkeys-lru (Least Recently Used) eviction and jittered TTL expiration.

Even a highly tuned relational database (PostgreSQL Performance Tuning & Indexing Guide) struggles when thousands of concurrent users repeatedly query the same trending products, user sessions, or configuration objects. Physical disk I/O and query parsing introduce latency that compounds under load.

Introducing an in-memory caching tier powered by Redis (or Amazon ElastiCache in an AWS High-Availability Multi-AZ Architecture) is the single most effective way to scale web applications from 1,000 to 1,000,000 daily active users.

[ Web Client / API ] ➔➔ Query Data ➔➔ [ Redis In-Memory Cache ]
                                │
            ┌───────────────────┴───────────────────┐
            ▼ (CACHE HIT - 0.8ms) ▼ (CACHE MISS - 45ms)
[ Return Instant Cached Data ] [ Query Primary PostgreSQL DB ]
                                                    │
                                                    ▼
                                    [ Populate Redis with TTL ]

01. The Three Primary Caching Patterns

A. Cache-Aside (Lazy Loading) • The Gold Standard

The application checks Redis first. If the key exists (Cache Hit), it returns immediately. If the key does not exist (Cache Miss), it queries the database, writes the result to Redis with a TTL (Time-To-Live), and returns the response.

// Production Cache-Aside Pattern in TypeScript
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });

export async function getUserProfile(userId: string) {
  const cacheKey = `user:${userId}:profile`;

  // 1. Check Redis Cache
  const cachedData = await redis.get(cacheKey);
  if (cachedData) {
    return JSON.parse(cachedData); // Cache Hit
  }

  // 2. Cache Miss: Query Database
  const user = await db.user.findUnique({ where: { id: userId } });

  if (user) {
    // 3. Write to Cache with a 15-minute TTL + random jitter
    const ttlSeconds = 900 + Math.floor(Math.random() * 60);
    await redis.setEx(cacheKey, ttlSeconds, JSON.stringify(user));
  }

  return user;
}

B. Write-Through

The application updates the cache and the primary database simultaneously in the same transaction. This guarantees that data in the cache is never stale, but incurs write latency on every mutation.

C. Write-Behind (Write-Back)

The application writes data exclusively to Redis. A background queue worker asynchronously flushes batches of writes to PostgreSQL every 5 seconds. Perfect for high-volume telemetry and analytics counters, but risks data loss if the Redis instance crashes before flushing.

02. Mitigating Cache Stampede & Thundering Herd

What happens when a viral product's cached key expires during peak traffic? 5,000 concurrent requests simultaneously experience a Cache Miss and hammer your database at the exact same millisecond. This Cache Stampede can bring down your primary database.

  • TTL Jitter: Never set fixed expiration times. Add a random variation (e.g., 900s + Math.random() * 120s) so keys expire at different moments.
  • Distributed Mutex Locks: When a miss occurs, require the first worker to acquire a short-lived Redis lock (SET key token NX EX 5). Only that worker queries the database and refreshes the cache, while other requests wait or return slightly stale data.

03. Configuring Safe Redis Eviction Policies

Redis stores data entirely in RAM. When memory is full, what happens? If unconfigured, Redis defaults to noeviction, throwing out-of-memory errors on new writes. In redis.conf, set:

# Maximum memory allocation (e.g., 2GB on a 4GB server)
maxmemory 2gb

# Evict the least recently used keys among all keys
maxmemory-policy allkeys-lru

Under allkeys-lru, Redis automatically discards inactive keys when RAM fills up, keeping active user sessions and popular queries hot in memory.

04. Running Redis Locally with Docker Compose

You can spin up an optimized Redis instance alongside your backend application in under 5 seconds using Docker (Docker Containerization Guide):

# docker-compose.yml
services:
  redis:
    image: redis:7-alpine
    container_name: app_cache
    restart: always
    ports:
      - "6379:6379"
    command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru --save ""
    volumes:
      - redis_data:/data

volumes:
  redis_data:
Security Warning: Redis Authentication & Zero-Trust

Never expose port 6379 to the public internet! Automated malware constantly scans for unauthenticated Redis servers to execute remote code. Place Redis strictly inside private VPC subnets with strong authentication passwords (requirepass) or IAM authentication: Zero-Trust Cloud Security Architecture.

Redis Caching Design Patterns Matrix

Caching Strategy Read Latency Write Overhead Cache Consistency Risk Best Production Workload
Cache-Aside (Lazy Loading) Sub-millisecond (on hit) Direct to DB; zero cache write cost Stale data possible if updates miss cache eviction Read-heavy web apps & user profile queries
Write-Through Instant sub-millisecond Higher (writes both cache and DB synchronously) Zero stale data; cache is always in sync with DB Financial balances & real-time inventory counts
Write-Behind (Write-Back) Instant sub-millisecond Lowest (writes to cache; DB updated asynchronously) High risk of data loss if Redis crashes before flush Activity feeds, video view counts & high-volume metrics
Redlock Distributed Lock N/A (concurrency guard) Low latency atomic locking via Lua scripts Deadlock risk without strict automated TTL expiries Preventing double-spends & concurrent cron triggers
📖 Authoritative Documentation & Technical References

05. Frequently Asked Questions (FAQ)

Q: What is the difference between Redis and Memcached?
Memcached is a pure in-memory key-value cache. Redis supports rich data structures (Hashes, Lists, Sets, Sorted Sets, Bitmaps, Geospatial indexes), optional disk persistence (RDB/AOF), pub/sub messaging, and atomic transactions.
Q: What is Cache Penetration and how do you prevent it?
Cache Penetration occurs when malicious requests query non-existent keys (e.g., user:99999999) to bypass the cache and force database lookups. Prevent it by caching null values with a short 60-second TTL or using Bloom Filters to verify key existence before hitting the database.
Q: Can Redis be used for session storage in microservices?
Yes! Redis is the industry standard for centralized user session storage in microservice architectures, allowing stateless web containers to verify authenticated users seamlessly across clusters as described in our Microservices Architectural Guide.

06. Conclusion & Next Steps

Integrating Redis In-Memory Caching into your application architecture is one of the highest-leverage system design optimizations you can implement. By applying the Cache-Aside pattern with deliberate TTL jitter, selecting appropriate memory eviction policies like allkeys-lru, and protecting against stampedes with distributed locks, you achieve sub-millisecond API response times while shielding your primary database from collapse.

To ensure high availability in production, deploy Redis in a clustered multi-AZ configuration with automated failover (such as Amazon ElastiCache or Redis Sentinel) and monitor cache hit ratios continuously to identify suboptimal queries before they impact database load.

Designing high-throughput distributed caching tiers or mitigating cache thundering herds in production? View distributed caching deployments in the Waseem Kaluwal Portfolio, or connect through Architecture Consultation to maximize application response speeds.

Topic Cluster

Related Cloud & DevOps Engineering Guides

Supercharge your infrastructure and deployment workflow with these companion production tutorials:

Database Optimization Read Guide →
PostgreSQL Performance Tuning: Indexing Strategies, EXPLAIN ANALYZE, and Query Optimization
Eliminate slow queries with B-Tree indexes, GIN indexing, VACUUM maintenance, and query execution plans.
System Design Read Guide →
Microservices vs Monolith: Architectural Decision Guide for Modern Engineering Teams
Evaluate architectural trade-offs between monolithic simplicity and microservices scalability.
API Security Read Guide →
API Security Best Practices: OAuth 2.0, JWT Tokens, Rate Limiting & OWASP Top 10 Hardening
Defend APIs against OWASP vulnerabilities with OAuth 2.0 PKCE, cryptographically signed JWTs, and rate limiting.
Web Performance Read Guide →
Modern Frontend Performance: Optimizing Core Web Vitals (LCP, INP, CLS) and Sub-Second Loads
Achieve 95+ Google PageSpeed and sub-second rendering by optimizing Core Web Vitals, critical CSS, and bundles.
Waseem Kaluwal - Web Developer, Python & AI Expert, SEO Specialist, AWS DevOps

Written by Waseem Kaluwal

Software Engineer, Full-Stack Website Developer, Social Media Influencer, Python & AI Expert, Technical SEO Strategist, and AWS DevOps Specialist. Tech YouTuber, Photographer, and Global Freelancer dedicated to engineering high-performance digital platforms and intelligent automation systems.

No comments:

Post a Comment

ADVERTISEMENT