0PricingLogin
Node.js Backend Development Bootcamp · Lesson

Cache-Aside, Write-Through, and TTL Strategies

Choose the right caching pattern and expiration policy to balance freshness against database load.

Why Caching Exists: The Database Bottleneck

Every Node.js backend eventually hits the same wall: the database becomes the bottleneck. As traffic grows, repeated reads for the same data — user profiles, product listings, config values — hammer your DB with identical queries.

Caching solves this by storing the result of an expensive operation so subsequent requests can be served from a fast in-memory store instead of hitting the database again.

  • Redis is the industry-standard caching layer for Node.js — it operates entirely in memory, supports rich data structures, and handles hundreds of thousands of operations per second.
  • A cache hit returns data in under 1ms; a DB query can take 10–200ms or more under load.
  • The trade-off is freshness: cached data may not reflect the latest DB state.

Choosing the right caching pattern determines how well your system balances speed against consistency.

Connecting to Redis with ioredis

Before implementing any caching pattern, you need a reliable Redis client. ioredis is the most popular choice for Node.js — it supports clustering, Sentinel, pipelining, and Lua scripting out of the box.

Install it and create a reusable client instance:

  • Use a singleton module so every part of your app shares one connection pool.
  • Configure maxRetriesPerRequest and lazyConnect for production resilience.
  • The client emits connect, error, and reconnecting events — always handle errors.
// redis/client.js
const Redis = require('ioredis');

const redis = new Redis({
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: parseInt(process.env.REDIS_PORT || '6379'),
  password: process.env.REDIS_PASSWORD || undefined,
  maxRetriesPerRequest: 3,
  lazyConnect: true,
});

redis.on('connect', () => console.log('[Redis] Connected'));
redis.on('error', (err) => console.error('[Redis] Error:', err.message));
redis.on('reconnecting', () => console.log('[Redis] Reconnecting...'));

module.exports = redis;

All lessons in this course

  1. Cache-Aside, Write-Through, and TTL Strategies
  2. Distributed Locks and the Redlock Algorithm
  3. Pub/Sub, Streams, and Rate Limiting with Redis
  4. Preventing Cache Stampedes and Thundering Herds
← Back to Node.js Backend Development Bootcamp