Why This Matters at Engineering Leadership Scale
Reading a key from Redis takes roughly 0.5ms to 1ms, compared to 15ms to 80ms for a multi-join SQL query against Postgres. That two-order-of-magnitude gap makes caching the fastest lever to cut p95 API latency and protect primary database CPU. Yet poorly engineered caches trigger some of the most painful production outages in B2B SaaS.
Two failure modes dominate at scale. First, a cache stampede (thundering herd): when a hot tenant configuration key expires at 9:00 AM on Monday morning, 5,000 concurrent requests miss Redis simultaneously and slam the primary database, exhausting connection pools and cascading into HTTP 503s. Second, cross-tenant collisions and invalidation drift: missing key namespaces cause cache flushes to wipe unrelated tenants, while sprawling cross-service invalidation chains silently drop events and serve stale permissions for hours.
Core Mental Model & Architecture
Every caching RFC must explicitly justify which of the four core patterns fits the workload's read/write ratio and consistency budget:
| Caching Pattern | How It Works | Best For | Primary Risk |
|---|---|---|---|
| Cache-Aside (Lazy Loading) | App checks Redis first; on miss, reads DB and populates Redis with a TTL. | Read-heavy APIs, tenant settings, feature flags, user profiles. | Cold miss latency after expiry; brief stale window until TTL expires. |
| Write-Through | App writes to cache and DB synchronously in one request path. | Data requiring immediate read-after-write consistency across nodes. | Higher write latency; fills Redis RAM with cold data rarely read. |
| Read-Through | Cache proxy or library fetches from DB automatically on a miss. | Standardizing read boilerplate when cache tier supports loader plugins. | Tight coupling between cache infrastructure and database schemas. |
| Write-Behind (Write-Back) | App writes to cache immediately and flushes batches to DB asynchronously. | High-volume counters, rate telemetry, non-financial analytics ingestion. | Data loss if cache node crashes before async batch flush completes. |
For 90% of enterprise SaaS and fintech APIs, Cache-Aside is the cleanest default. Keep short TTLs (30s to 300s) on mutable domain records rather than maintaining fragile distributed invalidation meshes, and layer three stampede-defense mechanisms on top:
- Tenant-Prefixed Key Namespacing: Prefix every key with
tenant:{tenantId}:{domain}:{version}:{key}so multi-tenant keys never collide and version bumps cleanly invalidate schema changes without dangerousKEYS *scans. - TTL Jitter: Randomize expiry windows by
+/- 10%to20%(baseTtl + random(-jitter, +jitter)) so batches of keys populated during startup or a Monday login surge never expire in lockstep. - Request Coalescing (Singleflight) & Early Recomputation: Inside each app instance, deduplicate concurrent misses for the exact same key so only one database query executes while all concurrent callers await that single in-flight promise. For ultra-hot keys, trigger a background refresh probabilistically when remaining TTL drops below
15%.
Step-by-Step Implementation Tutorial
Follow these four steps to build a stampede-resistant, tenant-isolated cache-aside wrapper in TypeScript:
- Standardize Key Formatting With Tenant Prefix & Schema Version: Make
tenantIda mandatory function parameter rather than an optional string concatenation so engineers cannot accidentally create global colliding keys. - Add In-Process Singleflight Coalescing: Maintain a
Map<string, Promise<T>>keyed by the full Redis key. If a request misses Redis while another request on the same pod is already querying Postgres for that key, attach to the existing promise and clean up insidefinally. - Apply Random TTL Jitter on Every
SET: Spread expirations across a+/- 15%window so warm keys decay smoothly over time instead of creating cliff spikes. - Refresh Hot Keys Early Before Hard Expiry: Store a lightweight metadata envelope (
value,expiresAtMs) or check RedisPTTLto trigger a non-blocking refresh when less than15%of TTL remains, keeping p99 reads off the database entirely.
// safe-cache.ts - Tenant-prefixed Cache-Aside with TTL Jitter, Singleflight & Early Refresh
import type { Redis } from "ioredis";
interface CacheOptions {
tenantId: string;
namespace: string;
key: string;
schemaVersion?: string;
baseTtlSeconds: number;
jitterRatio?: number; // Default +/- 15%
}
const inFlightLoads = new Map<string, Promise<unknown>>();
export function buildTenantCacheKey(opts: CacheOptions): string {
const version = opts.schemaVersion ?? "v1";
return `tenant:${opts.tenantId}:${opts.namespace}:${version}:${opts.key}`;
}
export function computeJitteredTtl(baseSeconds: number, jitterRatio = 0.15): number {
const maxDelta = Math.max(1, Math.floor(baseSeconds * jitterRatio));
const offset = Math.floor(Math.random() * (maxDelta * 2 + 1)) - maxDelta;
return Math.max(5, baseSeconds + offset);
}
export async function getOrLoadCached<T>(
redis: Redis,
opts: CacheOptions,
loader: () => Promise<T>
): Promise<T> {
const fullKey = buildTenantCacheKey(opts);
const [raw, remainingTtlSec] = await Promise.all([
redis.get(fullKey),
redis.ttl(fullKey),
]);
if (raw !== null) {
const parsed = JSON.parse(raw) as T;
// Probabilistic early refresh when <15% TTL remains
const refreshThreshold = opts.baseTtlSeconds * 0.15;
if (remainingTtlSec > 0 && remainingTtlSec < refreshThreshold && !inFlightLoads.has(fullKey)) {
void refreshSingleflight(redis, fullKey, opts, loader).catch(() => {
// Best-effort background refresh; keep serving valid cached value
});
}
return parsed;
}
return refreshSingleflight(redis, fullKey, opts, loader);
}
async function refreshSingleflight<T>(
redis: Redis,
fullKey: string,
opts: CacheOptions,
loader: () => Promise<T>
): Promise<T> {
const existing = inFlightLoads.get(fullKey) as Promise<T> | undefined;
if (existing) {
return existing;
}
const loadPromise = (async () => {
const fresh = await loader();
const ttl = computeJitteredTtl(opts.baseTtlSeconds, opts.jitterRatio ?? 0.15);
await redis.set(fullKey, JSON.stringify(fresh), "EX", ttl);
return fresh;
})().finally(() => {
inFlightLoads.delete(fullKey);
});
inFlightLoads.set(fullKey, loadPromise);
return loadPromise;
}For high-write mutations where a user must immediately see their own update (such as updating a tenant webhook secret), call await redis.del(buildTenantCacheKey(...)) right after the database transaction commits, while relying on short jittered TTLs as your safety net against missed invalidations.
Worked Production Scenario: Before vs. After
A multi-tenant fintech portfolio-reporting platform serving 350 enterprise tenants suffered predictable Monday-morning latency spikes between 8:55 AM and 9:10 AM as advisors logged in simultaneously.
- Before: Tenant configuration and permission summaries were cached in Redis with a fixed
3600-second TTL and unprefixed keys (config:<id>). Every hour on the hour, synchronized key expiries unleashed thousands of simultaneous cache misses across 24 API pods. Primary Postgres CPU pegged at88%, active connections saturated, and API p95 latency spiked above4.5sfor several minutes. Worse, an ad-hoc cache clear script usingKEYS config:*blocked the single-threaded Redis event loop for 2.4 seconds during business hours. - After: The squad rolled out the shared
getOrLoadCachedhelper across the top eight read endpoints: mandatorytenant:{id}:key prefixes with schema versioning,+/- 15%TTL jitter, singleflight request coalescing per pod, and probabilistic early refresh below15%remaining TTL. Combined with composite indexing and PgBouncer, Monday-morning Postgres CPU dropped from88%to34%, p95 API latency fell from4.5sto190ms, Redis cache hit ratio rose from81%to97.4%, and cache stampede alerts dropped to zero.
Common Failure Modes & Anti-Patterns
- Running
KEYS *in Production for Cache Invalidation: CallingKEYS tenant:123:*scans the entire Redis keyspace on its single main thread, freezing every other tenant's reads for seconds. Structural Fix: Use explicit key lists, schema version suffixes (v2), orUNLINKon known deterministic keys; never permitKEYSin application code or Redis ACLs. - Caching Unbounded Payloads or Missing
maxmemory-policy: Storing giant 5MB report JSON blobs without eviction policies causes Redis OOM crashes that fail writes across the cluster. Structural Fix: Enforce per-value size checks (for example,< 64KB), setmaxmemory-policy allkeys-lruon cache clusters, and separate ephemeral cache Redis instances from durable queue or session Redis instances. - Building Complex Multi-Service Cache Invalidation Meshes: Trying to broadcast Redis delete events across six microservices via Kafka leads to silent out-of-order overwrites (a slow read repopulating stale data right after a delete). Structural Fix: Default to cache-aside with short TTLs (
30sto120s) on mutable data, delete explicitly only inside the owning service on writes, and skip caching entirely for strict financial balances or authz revocations that demand read-after-write accuracy.
How to Handle Pushback in the Room
Pushback 1 (Senior Backend Engineer): "Short TTLs feel lazy. If we emit Kafka invalidation events whenever any service updates a tenant record, we can set a 24-hour TTL and get 99.9% cache hits."
Verbatim Response: "A 24-hour TTL with cross-service Kafka invalidation fails badly under race conditions: if one consumer lags or an in-flight read writes stale DB data right after an invalidation runs, that customer is stuck with wrong settings for 24 hours. With a three-minute jittered TTL plus singleflight coalescing and early refresh, we still clear 97% hit rates while guaranteeing any missed invalidation heals itself automatically in minutes."
Pushback 2 (Product Manager): "Wait, if we use a 60-second TTL on workspace settings, could an admin change a display label and not see it immediately on refresh?"
Verbatim Response: "We separate the two cases cleanly. When an admin saves a setting, the write endpoint explicitly deletes that single tenant key right after the database commit so the admin sees their change immediately. The 60-second jittered TTL is our safety net for secondary views and edge cases, while strict security actions like revoking a user session bypass the cache completely."
Key Takeaways & This Week's Action Rep
- Default to Cache-Aside with explicit
tenant:{tenantId}:{namespace}:{version}:{key}namespacing so multi-tenant data never collides and schema changes roll out safely. - Stop cache stampedes by combining
+/- 10%to20%random TTL jitter, singleflight request coalescing, and probabilistic early refresh on hot keys. - Prefer short jittered TTLs plus owner-side explicit deletes over fragile cross-service invalidation chains, and never cache strict ledger balances or immediate permission revocations.
- Ban
KEYS *via Redis ACLs and isolate cache Redis clusters (allkeys-lru) from durable session or rate-limit stores.
This Week's Action Rep: Audit your highest-QPS read endpoint's caching layer. Check whether keys are prefixed with tenant_id:, add +/- 15% TTL jitter if expiries are fixed, and wrap the DB fallback in a singleflight map so concurrent misses cannot stampede Postgres.