TL;DR — A two‑tier Redis cache pairs an in‑memory front‑tier with a durable back‑tier, and write‑behind invalidation pushes updates to the back‑tier only when the front‑tier evicts stale entries, keeping read latency low while preserving eventual consistency for read‑heavy APIs.
In modern API‑driven systems, read traffic often outweighs writes by an order of magnitude. Caching is the primary lever to keep response times sub‑millisecond, but a naïve single‑tier cache can become a bottleneck when write workloads outpace eviction or when data must remain consistent across multiple services. This article walks through a two‑tier Redis design that adds a write‑behind invalidation layer, explains how the architecture scales, and offers concrete patterns you can adopt today.
Overview
Read‑heavy APIs—such as user‑profile lookups, feed rendering, or product‑detail pages—benefit enormously from aggressive caching. The challenge is threefold:
- Latency: Every extra round‑trip to the backing data store erodes the sub‑millisecond goal.
- Consistency: Writes must eventually propagate so that readers never see stale data beyond an acceptable window.
- Scale: A single Redis instance can become a hotspot; sharding or clustering is often required.
A two‑tier architecture addresses these concerns by separating a hot front‑tier (L1) from a more persistent back‑tier (L2). The front‑tier holds the most‑recently accessed keys in RAM, while the back‑tier stores the full dataset, possibly on flash or SSD, and can be distributed across a Redis cluster. Write‑behind invalidation sits between the two tiers, deciding when and how modifications are flushed downstream.
Two‑Tier Architecture
L1 – Front‑Tier (Hot Cache)
- Implementation: A dedicated Redis instance (or a small cluster) configured with a strict memory limit (
maxmemory). - Eviction policy:
allkeys-lruorvolatile-ttldepending on whether you have a secondary TTL strategy. - Access pattern: Reads go directly to L1. Misses are forwarded to L2, and the fetched value is placed into L1 for subsequent calls.
- Typical size: 1 – 10 GB, depending on QPS and key cardinality.
L2 – Back‑Tier (Durable Store)
- Implementation: A Redis Cluster or group of nodes with larger
maxmemoryand slower storage (e.g., Redis on Flash). - Data model: Holds the canonical copy of every key that the system tracks.
- Replication: Synchronous or asynchronous based on your durability requirements.
- Purpose: Serves as the source of truth for cache misses, cache warm‑starts, and as the target for write‑behind flushes.
Inter‑Tier Communication
| Direction | Mechanism |
|---|---|
| Read | Client → L1. On miss, L1 fetches from L2, stores copy, returns to client. |
| Write (cache‑aside) | Client → L1 (SET). L1 marks the key as “dirty” and schedules a background flush to L2. |
| Write‑behind | When L1 evicts a key (LRU) or its TTL expires, the pending mutations are pushed to L2 before the key is removed from L1. |
| Invalidation | Downstream services that update the source database can trigger a write‑behind event that updates L2 and evicts the corresponding entry from L1. |
A schematic of the data flow:
Client --> L1 (Redis) --miss--> L2 (Redis Cluster) --> Source DB
^ ^
| write‑behind | async flush
+------------------------+
Write‑Behind Invalidation Strategy
Write‑behind differs from classic write‑through (where every SET immediately propagates to L2) because it batches and delays the propagation, reducing write amplification. The key is to guarantee eventual consistency without sacrificing read performance.
When to Flush
- LRU Eviction: As L1 reaches its memory cap, the evicted key’s pending writes are forwarded to L2 before the entry is discarded.
- TTL Expiry: If a key has a short TTL (e.g., 30 s) and the TTL expires, any pending updates are flushed first.
- Periodic Batch: A background worker runs every N seconds (e.g., 5 s) and pushes all “dirty” keys to L2, regardless of eviction events.
Tracking Pending Writes
Each key in L1 carries a small metadata struct:
key: user:123
value: {"name":"Alice","email":"alice@example.com"}
version: 5 # incremented on every write‑behind flush
dirty: true # set when a local write occurs
When a client issues a SET, the client library (or a wrapper service) increments the version and marks dirty := true. The background flusher reads all dirty entries and executes MULTI/EXEC pipelines or HSET commands to update L2 atomically.
Consistency Guarantees
- Read‑your‑writes: Because the client always writes to L1 first, subsequent reads from the same client will see the updated value immediately, even before it reaches L2.
- Stale‑read window: Readers from other services may see the old value until the background flusher propagates the change. The window is bounded by the flush interval (typically < 5 s).
- Loss tolerance: If a node running L1 crashes before a dirty entry is flushed, the data in L2 remains the last committed state. The system can tolerate this loss if the application can tolerate a brief inconsistency.
Practical Example (Python with redis-py)
import redis
import time
l1 = redis.Redis(host="l1.example.com", port=6379, db=0) # front tier
l2 = redis.Redis(host="l2.example.com", port=6379, db=0) # back tier
def write_behind(key, value, version):
# Store in L1 and mark dirty
l1.set(key, value) # L1 cache
# Attach version & dirty flag as a hash overlay
l1.hset(f"{key}:meta", mapping={
"version": str(version),
"dirty": "1"
})
# Schedule async flush (in real code, push to a job queue)
flush_to_l2.delay(key, version)
def flush_to_l2(key, version):
# Read meta from L1 to confirm dirty state
meta = l1.hgetall(f"{key}:meta")
if meta.get("dirty") != b"1":
return
# Propagate to L2 only if version hasn't changed
current_version = int(meta.get("version", 0))
if current_version >= version:
l2.set(key, value) # write‑through to L2
# Clear dirty flag
l1.hset(f"{key}:meta", mapping={"dirty": "0"})
The snippet demonstrates the minimal plumbing: store in L1, tag as dirty, and let a worker push changes to L2.
Architecture and Patterns in Production
1. Cache‑Aside (Read‑Through) + Write‑Behind
Most systems start with a cache‑aside pattern: on a miss, the application fetches from the database and populates L1. Adding write‑behind on top of this pattern yields a hybrid that:
- Keeps read latency low (hot data stays in L1).
- Reduces write load on the database (batches are sent to L2, not directly to the DB).
- Preserves a single source of truth in L2, which can be the input for other downstream services.
2. Stampede (Thundering Herd) Protection
When a popular key expires simultaneously, many requests may hit the backend at once. Mitigations include:
- Mutex per key: Use Redis SETNX to acquire a lock while one request rebuilds the cache.
- Background refresh: Periodically re‑populate L1 before TTL expiry, using a lightweight version of the data.
- Graceful degradation: Serve a “stale” version from L1 while the fresh data is being fetched.
3. Key Namespace & Versioning
Organize keys into logical namespaces (e.g., user:, product:, session:). Attach a monotonically increasing version number (as shown in the metadata example) to each namespace. When a write‑behind flush occurs, compare the version in L1 with the version stored in L2; if L2’s version is older, the flush proceeds, otherwise it’s skipped. This prevents out‑of‑order updates from overwriting newer data.
4. Autoscaling the Tiers
- L1 autoscaling: Use Redis Cluster with hash slots. Add nodes when
used_memoryapproachesmaxmemory. - L2 autoscaling: Leverage Redis on Flash or tiered storage (RAM + SSD). Cloud providers (AWS Elasticache, GCP Memorystore) can resize clusters with minimal downtime.
5. Observability
- Hit/miss ratios per tier (Prometheus metrics
redis_cache_hits,redis_cache_misses). - Dirty‑queue length: Number of pending write‑behind entries.
- Flush latency: Time from eviction to L2 acknowledgment.
- Alerts on sustained miss‑rate spikes or growing dirty queues indicate mis‑configurations or hot‑key patterns that may need sharding.
Key Takeaways
- Two‑tier separates concerns: L1 provides sub‑millisecond reads; L2 guarantees durability and serves as the canonical store.
- Write‑behind reduces write amplification: Flushes are triggered by evictions, TTL expiry, or a periodic batch, not on every client write.
- Metadata versioning is essential: A small overlay (
version,dirty) lets the flush logic decide when and whether to push updates to L2, preventing stale or out‑of‑order writes. - Production patterns matter: Combine cache‑aside reads with write‑behind writes, protect against stampede with per‑key mutexes, and namespace keys with version numbers for safe concurrent updates.
- Observability closes the loop: Track hit/miss ratios, dirty‑queue depth, and flush latency to fine‑tune memory limits, eviction policies, and batch intervals.
Further Reading
- Redis Documentation – Introduction to Redis Data Structures
- Redis Labs – Cache Topologies and Patterns
- Redis University – Redis Cluster Deep Dive
- Google Cloud Blog – Building Scalable Caches with Memorystore
- Stack Overflow – Write‑Behind Caching Strategies