How-To Guide

How to Implement Tiered Caching with Redis

Layer Redis behind a local cache: size each tier, serialize values safely, handle Redis outages, and test hit rates across the tiers.

On this page

  1. Introduction
  2. Assign keys to tiers
  3. Serialize values safely
  4. Degrade when Redis is unavailable
  5. Measure per-tier hit rates
  6. Test hits, fallthrough, and outage
  7. Common pitfalls
  8. Conclusion

Introduction

Redis is the common shared cache: it keeps the fleet coherent and absorbs load the origin should not see. But every Redis read is a network round trip, and for the hottest keys, read thousands of times a second, that hop is the cost that dominates. A local in-process tier in front of Redis serves those keys with no hop, while Redis remains the tier that everyone agrees on for everything else. The result is a tiered cache where each tier has a different latency and cost.

This tutorial builds a two-tier cache with a local map in front of Redis. It covers what each tier should hold, how to serialize values so a schema change does not break a reader, how to degrade when Redis is unavailable, and how to measure per-tier hit rates so you can size the tiers. The examples use Node.js and Redis.

Assign keys to tiers

The local tier should hold the smallest, hottest set: keys read many times per key, small in size, and tolerant of a brief per-instance staleness. Its capacity is bounded by process memory and by the number of instances, so it must be small. The Redis tier holds a larger working set and is the coherent copy across the fleet, so a key missing locally is found there without reaching the origin.

Keys that must be coherent instantly, or that are large, or that are read rarely, can skip the local tier and go straight to Redis. Keys that are tiny and read constantly, such as a feature flag or a reference record, belong in the local tier. Decide per key class and keep the decision with the read, so the tiering is visible rather than implicit.

import { LRUCache } from 'lru-cache';
import { createClient } from 'redis';

const local = new LRUCache({ max: 1000, ttl: 5000 });   // small, seconds
const redis = createClient();
await redis.connect();

async function read(key, load, { localAllowed = true } = {}) {
  if (localAllowed) {
    const l = local.get(key);
    if (l !== undefined) return { value: l, tier: 'local' };
  }
  const r = await redis.get(key);
  if (r !== null) {
    const value = decode(r);
    if (localAllowed) local.set(key, value);
    return { value, tier: 'redis' };
  }
  const value = await load();
  await redis.set(key, encode(value), { EX: 300 });
  if (localAllowed) local.set(key, value);
  return { value, tier: 'origin' };
}

Serialize values safely

Redis stores bytes, so the value is serialized and deserialized. Choose a compact format, and version it, so a cached value written by an older version of the code does not break a reader after a deploy. Include a schema version in the stored value, and when the reader sees a version it does not understand, treat it as a miss and reload rather than failing to parse it.

Compactness matters more than for a local cache, because every byte crosses the network and is stored in a shared store. Avoid verbose formats for large values, and consider whether a large value belongs in Redis at all or should be fetched from the origin with a smaller cache of metadata. Keep the serializer in one module so encode and decode cannot drift.

import { createHash } from 'node:crypto';
const SCHEMA = 2;

function encode(value: unknown): string {
  return JSON.stringify({ v: SCHEMA, d: value });
}
function decode(raw: string): unknown {
  const parsed = JSON.parse(raw) as { v: number; d: unknown };
  if (parsed.v !== SCHEMA) return undefined;   // unknown version -> treat as a miss
  return parsed.d;
}

Degrade when Redis is unavailable

A tiered cache adds a failure mode: Redis can be down or slow. When it is, do not fail the request. Fall through to the origin for the keys you cannot serve from the local tier, and protect the origin, because losing a cache tier multiplies its load. Serve local hits, load the rest from the origin, and shed or queue if the origin cannot take the extra, rather than failing every request.

Set a short timeout on Redis operations so a slow Redis does not stall every request. A cache read that can hang is worse than no cache, because it turns a degraded situation into an outage. Combine the timeout with a circuit breaker that stops calling Redis for a while after repeated failures, so a down Redis does not add its timeout to every request.

async function safeRedisGet(key) {
  try {
    const v = await Promise.race([
      redis.get(key),
      new Promise((_, rej) => setTimeout(() => rej(new Error('redis timeout')), 50)),
    ]);
    return v;
  } catch {
    metrics.incr('cache.redis.error');
    return null;   // treat as a miss; let the caller load from the origin
  }
}

Measure per-tier hit rates

Track hits at the local tier, hits at Redis, and origin loads separately. The local hit rate tells you whether the local tier is sized and TTL’d well. A high Redis hit rate and a low local one means the local tier is too small or its TTL too short for the hot set. A high origin load means either tier is missing the working set, and the origin is absorbing what the cache should.

Watch the total request latency by tier as well, because a tier that is hit but slow is not helping. A Redis hit that takes fifty milliseconds may be worse than a slightly stale local hit. Use the per-tier data to decide where to grow capacity and where a TTL is causing churn, rather than guessing.

const { value, tier } = await read(key, load);
metrics.incr('cache.hit.' + tier);   // local | redis | origin
// alert if origin share climbs, or if redis latency rises under a stable hit rate

Test hits, fallthrough, and outage

Test that a warm local key is served without a Redis call, by counting Redis calls. Test that a Redis hit promotes into the local tier so the second read is local. Test that an origin load populates both tiers. Test that a Redis outage falls through to the origin and the request still succeeds, and that a slow Redis is cut off by the timeout rather than stalling the request.

# read the same key twice: Redis call count stays 1 (second is a local hit)
curl -s http://localhost:3000/flag >/dev/null
curl -s http://localhost:3000/flag >/dev/null
# stop redis, then the request must still succeed via the origin
docker stop redis >/dev/null
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/flag   # 200, not 500

Common pitfalls

A local TTL longer than coherence allows so instances diverge, unversioned serialization so an old value breaks a new reader, a Redis read with no timeout that stalls requests when Redis is slow, falling back to errors instead of the origin on a Redis outage, and no per-tier metrics so the tiers cannot be sized are the recurring mistakes. A short local TTL, a versioned serializer, a timeout and circuit breaker, origin fallthrough, and per-tier metrics address them.

Conclusion

Tiered caching puts a small local tier for the hottest keys in front of a shared Redis tier for coherence. Assign keys to tiers deliberately, serialize with a version, degrade to the origin on a Redis outage with a short timeout, and measure per-tier hit rates to size each tier. Self-check by asserting a warm key skips Redis and that the service survives a Redis outage. Then hot reads avoid the hop and a Redis failure is a slowdown, not an outage.

Sources: Redis: Client-side caching, Redis: Pipelining and performance, Redis: Persistence and availability.

FAQ

Why keep a local tier if Redis is fast?
Even a fast Redis is a network round trip, and for the hottest keys that hop is the dominant cost. A local tier serves them with no hop. It trades memory per process and some coherence for latency on the hottest path.
What should happen when Redis is down?
Fall through to the origin so requests still succeed, and protect the origin, because losing a cache tier multiplies origin load. Serve local hits, load missing keys from the origin, and shed or queue if the origin cannot take the load, rather than failing every request.

Related Examples