Caching: The Art of Not Doing Work Twice

"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
This quote has been repeated so often it's become a cliché. But here's the thing: most developers don't actually understand why cache invalidation is hard until they've been woken up at 3 AM because users are seeing prices from yesterday.
Let's fix that.

The Problem: Your Database Can't Keep Up

It's Diwali sale on Flipkart. Traffic has spiked 50x. Every time someone views a product, your system runs this query:
sql
SELECT p.*, c.name as category, s.quantity as stock, AVG(r.rating) as avg_rating, COUNT(r.id) as review_count FROM products p JOIN categories c ON p.category_id = c.id JOIN stock s ON p.id = s.product_id LEFT JOIN reviews r ON p.id = r.product_id WHERE p.id = 12345 GROUP BY p.id;
This query takes 50 milliseconds. Seems fast, right?
Here's the math that will ruin your day:
  • Normal traffic: 1,000 requests/second × 50ms = your database spends 50 seconds of work per second. Manageable.
  • Diwali sale: 50,000 requests/second × 50ms = 2,500 seconds of database work... every second.
Your database can't do 2,500 seconds of work in 1 second. It collapses. Users see errors. Carts are abandoned. Revenue evaporates.
The solution? Stop asking the database the same question over and over.
That's caching. And done right, it's the difference between a system that handles 1,000 requests/second and one that handles 1,000,000.

Building a Mental Model: What Is a Cache?

Before diving into strategies and patterns, let's build intuition.
A cache is a fast storage layer that remembers answers to questions you've asked before. Think of it like this:
Without cache: Every time someone asks "What's the price of iPhone 15?", you walk to the warehouse, find the iPhone section, locate the price tag, write it down, walk back, and tell them "₹79,900."
With cache: The first time someone asks, you do the warehouse walk. But you also write "iPhone 15 = ₹79,900" on a sticky note on your desk. Next time someone asks, you glance at the sticky note. Done in 2 seconds instead of 2 minutes.
That's the entire philosophy: trade memory for time.

The Numbers That Matter

Here's what those latency numbers actually mean for your system:
Latency Hierarchy

Latency Hierarchy

Storage LayerLatencyRelative Speed
L1 Cache (in-process memory)~1 microsecond1x
L2 Cache (Redis)~1 millisecond1,000x slower than L1
Database query~50 milliseconds50,000x slower than L1
Database under load~500+ milliseconds500,000x slower than L1
The gap between "cached" and "not cached" isn't a small optimization. It's the difference between a snappy app and one where users rage-quit.

Where Should Caching Happen?

This is where many teams go wrong. They hear "performance problem" and immediately think "add Redis." But caching can happen at multiple layers, and each layer solves different problems.

Mental Model: The Caching Layers

Think of requests flowing through your system like water through pipes:
User → Browser Cache → CDN → Load Balancer → App Server (L1) → Redis (L2) → Database
Each layer can cache. The question is: which layers should cache what?

Layer 1: Browser and CDN

Before a request even hits your servers, caching can happen at the edge.
Browser caching: Static assets (images, CSS, JavaScript) are stored on the user's device. Set the right Cache-Control headers, and returning users load your site from their own hard drive.
http
Cache-Control: public, max-age=31536000, immutable
This header says: "Cache this for 1 year. It will never change."
CDN caching: Services like Cloudflare or CloudFront store content at servers geographically close to users. A user in Chennai gets your homepage from a Chennai server, not your Mumbai data center.
What to cache here: Static assets, public pages, API responses that are identical for all users.
What NOT to cache here: Personalized content. "Hi Rahul, your cart has 3 items" cannot be served from a CDN because it's different for every user.

Layer 2: Application Server (In-Process / L1)

Your application can keep frequently-accessed data in its own memory.
Speed: ~1 microsecond. No network hop, no serialization.
The catch: If you have 10 servers, you have 10 separate caches. Update data on server 1, and servers 2-10 don't know about it.
What to cache here: Configuration, feature flags, hot reference data that changes rarely.

Layer 3: Distributed Cache (Redis / L2)

A dedicated caching service shared by all application servers.
Speed: ~1 millisecond. Network round-trip required.
The advantage: All servers see the same cache. Update once, visible everywhere.
What to cache here: Session data, user profiles, product details, API responses.

The Multi-Level Pattern

Most production systems use L1 and L2 together:
Multi-Level Cache

Multi-Level Cache

go
func (s *ProductService) GetProduct(ctx context.Context, id string) (*Product, error) { // Level 1: Check in-process cache (microseconds) if product, found := s.localCache.Get(id); found { return product, nil } // Level 2: Check Redis (milliseconds) product, err := s.redis.Get(ctx, "product:"+id) if err == nil && product != nil { // Populate L1 for next request s.localCache.Set(id, product, 5*time.Minute) return product, nil } // Level 3: Database (tens of milliseconds) product, err = s.db.GetProduct(ctx, id) if err != nil { return nil, err } // Populate both caches s.localCache.Set(id, product, 5*time.Minute) s.redis.Set(ctx, "product:"+id, product, 1*time.Hour) return product, nil }
Why two levels?
L1 (in-process) is blindingly fast but isolated per server. Good for absorbing repeated requests within a single server.
L2 (Redis) is slower but shared. Good for ensuring all servers see consistent data.
L1 with a short TTL (5 minutes) acts as a buffer in front of L2. This reduces Redis load by 80-90% for hot data.

The Four Caching Patterns

Now let's get precise. There are four fundamental patterns for how applications interact with caches.

Pattern 1: Cache-Aside (Lazy Loading)

The application manages the cache explicitly. This is the most common pattern.
How it works:
  1. Application checks cache
  2. On miss: query database, write to cache, return result
  3. On hit: return cached result
Multi-Level Cache

Multi-Level Cache

go
func GetUser(ctx context.Context, userID string) (*User, error) { // Try cache cached, err := cache.Get(ctx, "user:"+userID) if err == nil && cached != nil { return cached, nil } // Cache miss - go to database user, err := db.GetUser(ctx, userID) if err != nil { return nil, err } // Populate cache for next time cache.Set(ctx, "user:"+userID, user, 1*time.Hour) return user, nil }
Pros:
  • Simple to understand
  • Only caches data that's actually requested
  • Application has full control
Cons:
  • First request for any item is always slow
  • Cache and database can become inconsistent
When to use: This is your default. Use it unless you have a specific reason not to.

Pattern 2: Read-Through

The cache itself handles database lookups. Your application only talks to the cache.
How it works:
  1. Application requests data from cache
  2. On miss: cache queries database, stores result, returns it
  3. On hit: cache returns result
go
// Your application code is simpler: func GetUser(ctx context.Context, userID string) (*User, error) { return cache.Get(ctx, "user:"+userID) // Cache handles the miss } // But you configure the cache with a loader function: cache := NewReadThroughCache(Config{ Loader: func(ctx context.Context, key string) (interface{}, error) { return db.GetUser(ctx, key) }, TTL: 1 * time.Hour, })
Pros:
  • Cleaner application code
  • Caching logic centralized in one place
Cons:
  • Cache becomes critical infrastructure
  • Less flexibility per-query
When to use: When you want caching abstracted away from business logic.

Pattern 3: Write-Through

Every write goes to cache first, then cache writes to database synchronously.
Write-Through

Write-Through

go
func UpdateUser(ctx context.Context, user *User) error { // Write to cache if err := cache.Set(ctx, "user:"+user.ID, user); err != nil { return err } // Cache writes to database (synchronous) if err := cache.WriteThrough(ctx, "user:"+user.ID, user); err != nil { cache.Delete(ctx, "user:"+user.ID) // Rollback cache return err } return nil }
Pros:
  • Cache and database always consistent
  • Reads immediately see writes
Cons:
  • Writes are slower (two operations)
  • Cache stores data that might never be read
When to use: When consistency matters more than write latency. User profiles, settings, permissions.

Pattern 4: Write-Behind (Write-Back)

Writes go to cache immediately. Database is updated asynchronously later.
Write-Behind

Write-Behind

go
func IncrementPageView(ctx context.Context, pageID string) error { // Write to cache only - returns instantly return cache.Increment(ctx, "views:"+pageID) } // Background process flushes to database: func (f *Flusher) Run() { ticker := time.NewTicker(1 * time.Minute) for range ticker.C { counts := cache.GetAllViewCounts() for pageID, count := range counts { db.IncrementViews(pageID, count) cache.ResetViewCount(pageID) } } }
Pros:
  • Writes are extremely fast
  • Batching reduces database load (1000 increments → 1 database write)
Cons:
  • Data loss if cache crashes before flush
  • Database is eventually consistent
When to use: Analytics, counters, metrics. Anywhere you can tolerate data loss and eventual consistency.

Cache Invalidation: The Actually Hard Part

Now we arrive at the hard problem. You've cached a product's price as ₹999. The pricing team changes it to ₹899 in the database.
What happens to your cache?

The Fundamental Problem

Here's why this is hard. Consider this timeline:
Time 0ms: Cache has product price = ₹999 Time 1ms: Database updated to price = ₹899 Time 2ms: User A requests product → Gets ₹999 from cache (WRONG!) Time 3ms: Cache invalidation message sent Time 4ms: Cache receives invalidation, deletes entry Time 5ms: User B requests product → Cache miss → Gets ₹899 from DB (correct)
Between times 1ms and 4ms, your cache is lying to users. This window might be milliseconds or minutes, depending on your invalidation strategy.
There is no perfect solution. Every strategy trades off consistency, latency, and complexity.

Strategy 1: TTL-Based Expiration

The simplest approach: every cache entry expires after a fixed time.
TTL Strategy

TTL Strategy

go
cache.Set(ctx, "product:123", product, 10*time.Minute)
After 10 minutes, the entry disappears. Next request fetches fresh data from database.
The tradeoff table:
Short TTL (1 minute)Long TTL (1 hour)
Max staleness: 1 minuteMax staleness: 1 hour
Cache hit rate: ~60-70%Cache hit rate: ~95%+
Database load: HigherDatabase load: Lower
When to use: When you can tolerate bounded staleness. Product descriptions (10 min TTL), user settings (1 hour TTL), feature flags (5 min TTL).
Pro tip: Different data types deserve different TTLs. Don't use one TTL for everything.

Strategy 2: Event-Based Invalidation

When data changes, publish an event. Cache listeners delete the stale entries.
Event-Based Invalidation

Event-Based Invalidation

go
// Product service publishes event on update func (s *ProductService) UpdatePrice(ctx context.Context, id string, price int) error { if err := s.db.UpdatePrice(ctx, id, price); err != nil { return err } // Publish invalidation event s.eventBus.Publish(ctx, Event{ Type: "product.updated", ProductID: id, }) return nil } // Cache invalidator subscribes to events func (i *Invalidator) Handle(event Event) { switch event.Type { case "product.updated": i.cache.Delete("product:" + event.ProductID) // Also invalidate related caches i.cache.Delete("category:" + event.CategoryID + ":products") } }
Pros:
  • Near real-time invalidation
  • Works across distributed systems
Cons:
  • Requires message queue infrastructure (Kafka, RabbitMQ)
  • Events can be delayed or lost
  • More moving parts
When to use: When staleness is unacceptable. Prices, inventory levels, user permissions.

Strategy 3: Version-Based Keys

Instead of invalidating, use a new key.
go
// Store version in database func (s *ProductService) GetProduct(ctx context.Context, id string) (*Product, error) { version := s.db.GetProductVersion(id) // e.g., returns 7 cacheKey := fmt.Sprintf("product:%s:v%d", id, version) if product, found := cache.Get(ctx, cacheKey); found { return product, nil } product, _ := s.db.GetProduct(ctx, id) cache.Set(ctx, cacheKey, product, 24*time.Hour) return product, nil } // On update, just increment version in database // Old cache entries become orphans and expire naturally
Pros:
  • No explicit invalidation needed
  • Atomic updates (new version or old, never partial)
Cons:
  • Orphaned entries waste memory until TTL expires
  • Requires version tracking infrastructure
When to use: When you need atomic cache updates without race conditions.

Cache Stampede: When Caching Makes Things Worse

Here's a scenario that catches many teams by surprise.
Your most popular product has 10,000 users viewing it right now. The cache entry expires.
What happens next?
Time 0ms: Cache entry expires Time 1ms: Request 1 → Cache miss → Query database Time 1ms: Request 2 → Cache miss → Query database Time 1ms: Request 3 → Cache miss → Query database ... Time 1ms: Request 10,000 → Cache miss → Query database
Your database receives 10,000 identical queries in the same millisecond. It collapses.
This is called a cache stampede (or thundering herd). The irony: caching was supposed to protect your database, but the cache expiration caused a worse spike than no caching at all.
Stampede Problem

Stampede Problem

Solution 1: Single-Flight (Request Coalescing)

Only one request actually queries the database. Others wait for the result.
Singleflight Solution

Singleflight Solution

go
import "golang.org/x/sync/singleflight" var group singleflight.Group func GetProduct(ctx context.Context, id string) (*Product, error) { // Check cache if product, _ := cache.Get(ctx, id); product != nil { return product, nil } // singleflight: only ONE goroutine fetches, others wait result, err, _ := group.Do(id, func() (interface{}, error) { // Double-check cache (another request might have populated it) if product, _ := cache.Get(ctx, id); product != nil { return product, nil } // Fetch from database product, err := db.GetProduct(ctx, id) if err != nil { return nil, err } // Populate cache cache.Set(ctx, "product:"+id, product, 1*time.Hour) return product, nil }) if err != nil { return nil, err } return result.(*Product), nil }
How it works: The singleflight package ensures that for any given key, only one function execution happens at a time. All other callers wait and receive the same result.
10,000 requests → 1 database query. The other 9,999 requests share the result.

Solution 2: Probabilistic Early Refresh

Don't wait for expiration. Refresh proactively.
Probabilistic Refresh

Probabilistic Refresh

go
func GetProduct(ctx context.Context, id string) (*Product, error) { product, expiry := cache.GetWithExpiry(ctx, id) if product == nil { return fetchAndCache(ctx, id) } // If less than 10% of TTL remaining... timeLeft := time.Until(expiry) totalTTL := 1 * time.Hour if timeLeft < totalTTL/10 { // Small random chance to refresh in background if rand.Float64() < 0.1 { go fetchAndCache(ctx, id) } } return product, nil // Always return cached value immediately }
The math: With 1000 requests/minute and 10% refresh probability in the last 6 minutes of a 1-hour TTL, you get ~100 refresh attempts. Combined with singleflight, exactly one succeeds. Cache refreshes before expiration.

Solution 3: Stale-While-Revalidate

Serve stale data immediately, refresh in background.
Stale-While-Revalidate

Stale-While-Revalidate

go
func GetProduct(ctx context.Context, id string) (*Product, error) { product, isStale := cache.GetWithStaleness(ctx, id) if product != nil { if isStale { go refreshInBackground(ctx, id) } return product, nil // Return immediately, even if stale } // True miss - must wait return fetchAndCache(ctx, id) }
The insight: Users prefer slightly stale data instantly over fresh data after a loading spinner. A price from 30 seconds ago is better than waiting 500ms for the current price.

Cache Security: Attacks You Need to Know

Your cache isn't just a performance layer—it's an attack surface. Let's talk about how hackers exploit caches and how to defend against them.
Cache Attack Vectors

Cache Attack Vectors

Attack 1: Cache Penetration

The attack: An attacker requests data that doesn't exist—repeatedly.
Attacker requests: GET /user/99999999999 → Cache miss (user doesn't exist) → Database query: SELECT * FROM users WHERE id = 99999999999 → Returns null → Nothing cached (we don't cache nulls) → Repeat 100,000 times per second
Every request bypasses the cache and hits the database. The attacker is using your cache miss path as a weapon.
Why it works: Most systems only cache positive results. "User not found" isn't cached, so every request for a non-existent user goes to the database.
The defense: Cache negative results
go
func GetUser(ctx context.Context, id string) (*User, error) { // Check cache cached, err := cache.Get(ctx, "user:"+id) if err == nil { if cached == nil { // Cached "not found" - return immediately return nil, ErrUserNotFound } return cached, nil } // Query database user, err := db.GetUser(ctx, id) if err == sql.ErrNoRows { // Cache the "not found" with short TTL cache.Set(ctx, "user:"+id, nil, 5*time.Minute) return nil, ErrUserNotFound } cache.Set(ctx, "user:"+id, user, 1*time.Hour) return user, nil }
Additional defense: Bloom filters
A Bloom filter is a space-efficient data structure that can tell you "definitely not in set" or "maybe in set."
go
var userBloomFilter *bloom.Filter // Populated at startup with all user IDs func GetUser(ctx context.Context, id string) (*User, error) { // Fast check: could this user possibly exist? if !userBloomFilter.MightContain(id) { return nil, ErrUserNotFound // Definitely doesn't exist } // Proceed with normal cache/database lookup // ... }
Bloom filters use minimal memory (~1GB for 1 billion entries with 1% false positive rate) and O(1) lookups.

Attack 2: Cache Avalanche

The attack: Many cache entries expire at the same time, causing massive database load.
This can happen accidentally (bulk data load with same TTL) or intentionally (attacker learns your TTL pattern).
Time 00:00:00 - Bulk load 1 million products with TTL = 1 hour Time 01:00:00 - All 1 million entries expire simultaneously Time 01:00:01 - Database receives 1 million queries Time 01:00:02 - Database is dead
The defense: Jittered TTLs
Never use exact TTLs. Add randomness.
go
func setWithJitter(ctx context.Context, key string, value interface{}, baseTTL time.Duration) { // Add ±20% jitter to TTL jitter := time.Duration(rand.Float64()*0.4-0.2) * baseTTL actualTTL := baseTTL + jitter cache.Set(ctx, key, value, actualTTL) } // Instead of all expiring at exactly 1 hour: // - Some expire at 48 minutes // - Some expire at 72 minutes // - Expirations spread over 24-minute window
Additional defense: Circuit breaker for database
go
var dbCircuitBreaker = gobreaker.NewCircuitBreaker(gobreaker.Settings{ MaxRequests: 100, Interval: 10 * time.Second, Timeout: 30 * time.Second, }) func GetFromDB(ctx context.Context, id string) (*Product, error) { result, err := dbCircuitBreaker.Execute(func() (interface{}, error) { return db.GetProduct(ctx, id) }) if err == gobreaker.ErrOpenState { // Circuit is open - database is overwhelmed // Return stale cache or graceful error return nil, ErrServiceDegraded } return result.(*Product), err }

Attack 3: Cache Poisoning

The attack: Attacker injects malicious data into your cache.
This can happen through:
  • Exploiting application bugs to write arbitrary cache keys
  • Man-in-the-middle attacks on cache traffic
  • Exploiting deserialization vulnerabilities
Real example: In 2020, researchers found cache poisoning vulnerabilities in major CDNs. By manipulating HTTP headers, attackers could cache malicious responses that would be served to other users.
Attacker sends: GET /product/123 Headers: X-Forwarded-Host: evil.com If server reflects this header in cached response: All users requesting /product/123 get response pointing to evil.com
The defenses:
1. Never trust user input in cache keys
go
// ❌ DANGEROUS: User controls cache key func GetProduct(ctx context.Context, userInput string) (*Product, error) { cacheKey := "product:" + userInput // What if userInput = "../admin/secrets"? // ... } // ✅ SAFE: Validate and sanitize func GetProduct(ctx context.Context, productID string) (*Product, error) { // Validate: must be numeric if !isValidProductID(productID) { return nil, ErrInvalidInput } cacheKey := fmt.Sprintf("product:%s", productID) // ... } func isValidProductID(id string) bool { _, err := strconv.ParseInt(id, 10, 64) return err == nil && len(id) < 20 }
2. Sign cached data
For high-security scenarios, sign data before caching and verify on read.
go
func SetSecure(ctx context.Context, key string, value interface{}) error { data, _ := json.Marshal(value) signature := hmac.Sum256(data, secretKey) envelope := CacheEnvelope{ Data: data, Signature: signature, Timestamp: time.Now().Unix(), } return cache.Set(ctx, key, envelope, ttl) } func GetSecure(ctx context.Context, key string) (interface{}, error) { envelope, err := cache.Get(ctx, key) if err != nil { return nil, err } // Verify signature expectedSig := hmac.Sum256(envelope.Data, secretKey) if !hmac.Equal(envelope.Signature, expectedSig) { // Cache was tampered with! cache.Delete(ctx, key) metrics.CacheTamperDetected.Inc() return nil, ErrCacheCorrupted } var value interface{} json.Unmarshal(envelope.Data, &value) return value, nil }
3. Encrypt sensitive data
go
func SetEncrypted(ctx context.Context, key string, value interface{}) error { plaintext, _ := json.Marshal(value) // AES-256-GCM encryption ciphertext, err := encrypt(plaintext, encryptionKey) if err != nil { return err } return cache.Set(ctx, key, ciphertext, ttl) }

Attack 4: Hot Key DDoS

The attack: Attacker identifies your hottest cache key and hammers it.
Even Redis has limits (~100K ops/sec per key on a single node). A coordinated botnet can exceed this.
Attacker discovers: /api/trending is your hottest endpoint Attacker sends: 500,000 requests/second to /api/trending Result: Redis CPU maxes out, all other cache operations slow down
The defenses:
1. Rate limiting per key
go
func GetTrending(ctx context.Context) (*TrendingData, error) { clientIP := getClientIP(ctx) // Rate limit: max 10 requests per second per IP for this endpoint if !rateLimiter.Allow("trending:"+clientIP, 10, time.Second) { return nil, ErrRateLimited } return cache.Get(ctx, "trending") }
2. Local caching for ultra-hot keys
Hot keys should be served from in-process memory, not Redis.
go
var hotKeyCache = lru.New(1000) // In-process LRU cache var hotKeyMutex sync.RWMutex func Get(ctx context.Context, key string) (interface{}, error) { // Check if this is a known hot key if isHotKey(key) { hotKeyMutex.RLock() if val, found := hotKeyCache.Get(key); found { hotKeyMutex.RUnlock() return val, nil } hotKeyMutex.RUnlock() } // Normal Redis path val, err := redis.Get(ctx, key) if err != nil { return nil, err } // Promote to hot key cache if accessed frequently if accessCounter.Increment(key) > 1000 { // >1000 accesses per minute hotKeyMutex.Lock() hotKeyCache.Set(key, val) hotKeyMutex.Unlock() } return val, nil }

Attack 5: Sensitive Data Exposure

The attack: Attacker gains access to your Redis instance and dumps all cached data.
This happens more often than you'd think:
  • Redis exposed to internet without authentication (shockingly common)
  • Weak passwords
  • Network segmentation failures
The defenses:
1. Never expose Redis to the internet
# Redis should ONLY listen on internal network bind 10.0.0.0/8 protected-mode yes requirepass <strong-random-password>
2. Don't cache sensitive data in plaintext
go
// ❌ DANGEROUS cache.Set("session:abc123", Session{ UserID: "123", Token: "secret-auth-token", CreditCard: "4111111111111111", }) // ✅ SAFE cache.Set("session:abc123", Session{ UserID: "123", TokenHash: sha256(token), // Store hash, not token // Don't cache credit card at all! })
3. Use Redis ACLs (Redis 6+)
# Create read-only user for application ACL SETUSER app-readonly on >password ~cache:* +get +mget -set -del # Create admin user for cache invalidation ACL SETUSER cache-admin on >admin-password ~* +@all
4. Enable TLS
# redis.conf tls-port 6379 port 0 # Disable non-TLS tls-cert-file /path/to/redis.crt tls-key-file /path/to/redis.key tls-ca-cert-file /path/to/ca.crt

Security Checklist

Before going to production, verify:
  • Redis is not exposed to the internet
  • Redis requires authentication
  • TLS enabled for Redis connections
  • Sensitive data is encrypted or hashed before caching
  • Cache keys are validated (no user-controlled strings)
  • Negative results are cached (prevents penetration attacks)
  • TTLs have jitter (prevents avalanche)
  • Rate limiting on hot endpoints
  • Monitoring for unusual cache patterns

A Real Incident: The Split-Brain Cache

Let me tell you about a bug that took 3 days to diagnose.
The symptom: Users reported seeing other users' profile pictures. User A would see User B's avatar. Intermittent, hard to reproduce.
The investigation:
We checked the obvious things first:
  • Database queries? Correct.
  • API responses? Correct.
  • Frontend rendering? Correct.
The bug was in the cache layer.
What happened:
We had two Redis clusters for redundancy: redis-primary and redis-secondary. The app was configured to read from both (for load balancing) and write to primary.
User A updates profile picture: → Write to redis-primary: user:A:avatar = "new-pic.jpg" User B views User A's profile: → Read from redis-secondary: user:A:avatar = "old-pic.jpg" (stale!)
The secondary cluster had replication lag. Normally milliseconds, but during peak traffic, it would lag by seconds. In those seconds, some users would see stale data.
But that explains seeing old data, not other users' data. What about the cross-user bug?
The deeper bug:
Our cache key generation had a subtle flaw:
go
// Intended: "user:{userID}:avatar" cacheKey := fmt.Sprintf("user:%s:avatar", userID) // But userID was coming from an object that was being reused // due to object pooling in our HTTP framework
Under high concurrency, the object pool was returning objects before they were fully reset. The userID field would briefly contain the previous request's user ID.
The fix:
  1. Fixed the object pool reset logic
  2. Added cache key validation
  3. Switched to single-cluster Redis with Sentinel for failover (eliminated replication-lag reads)
The lesson: Cache bugs are insidious because they're intermittent. Add logging for cache operations in development. Use tracing (like OpenTelemetry) to follow requests through your cache layer.

Redis Architecture: Beyond "Just Add Redis"

"Just add Redis" is not a caching strategy. You need to understand the deployment options.

Single Instance

One Redis server.
Redis Patterns

Redis Patterns

Capacity: ~100,000 operations/second, ~25GB RAM practical max
Failure mode: If it dies, cache is gone. All requests hit database.
When to use: Development, small apps, or when you can tolerate cold-cache scenarios.

Redis Sentinel

High availability without sharding. 3+ Redis nodes with automatic failover.
┌─────────────────────────────────────┐ │ Redis Sentinel │ │ (monitors health, triggers failover)│ └─────────────────────────────────────┘ │ │ │ ┌────┴───┐ ┌────┴───┐ ┌────┴───┐ │ Master │ │Replica │ │Replica │ │(writes)│ │(reads) │ │(reads) │ └────────┘ └────────┘ └────────┘
How it works: Sentinel processes monitor the master. If master dies, they elect a replica to become the new master. Your application reconnects automatically.
When to use: When you need high availability and your data fits in one node.

Redis Cluster

Horizontal scaling. Data is sharded across multiple nodes.
Redis Decision

Redis Decision

Data is split into 16,384 slots Key "user:123" → hash → slot 7842 → Node 2 Key "product:456" → hash → slot 2103 → Node 1
Capacity: Millions of operations/second, limited only by number of nodes.
The catch: Multi-key operations must hit the same node. Use hash tags to force keys to the same slot:
go
// These keys hash to the same slot because of {user:123} "cache:{user:123}:profile" "cache:{user:123}:settings" "cache:{user:123}:permissions"
When to use: When you outgrow a single node (>100K ops/sec or >25GB data).

Monitoring: How Do You Know Your Cache Is Working?

A cache without monitoring is a liability. Here's what to track:

Hit Rate

Hit Rate = Cache Hits / (Cache Hits + Cache Misses)
Target: >95% for most workloads.
If hit rate is low:
  • TTL too short? Entries expiring before reuse.
  • Cache too small? Entries evicted to make room.
  • Access pattern changed? Long tail of unique keys.
Hit Rate Analysis

Hit Rate Analysis

Latency Percentiles

Track p50, p95, p99 latency for cache operations.
Healthy Redis: p99 < 5ms
Warning signs:
  • p99 spiking: Network issues or hot keys
  • p50 increasing: Redis overloaded

Memory Usage

Redis will evict keys when memory is full. Track:
  • Used memory vs. max memory
  • Eviction rate (keys evicted/second)
Healthy: <80% memory usage, near-zero evictions.

Key Metrics Dashboard

Metrics Dashboard

Metrics Dashboard

go
// Instrument your cache wrapper func (c *Cache) Get(ctx context.Context, key string) (interface{}, error) { start := time.Now() result, err := c.redis.Get(ctx, key) duration := time.Since(start) if err == redis.Nil { metrics.CacheMisses.Inc() } else if err != nil { metrics.CacheErrors.Inc() } else { metrics.CacheHits.Inc() } metrics.CacheLatency.Observe(duration.Seconds()) return result, err }

Interview Cheat Sheet: What to Say

When caching comes up in a system design interview, structure your answer like this:

1. Identify What to Cache

"For this system, I'd cache [user profiles / product details / session data] because they're read-heavy and can tolerate [X seconds/minutes] of staleness."
Don't cache:
  • Data that changes every request
  • Data that must be real-time accurate (during transactions)
  • Data unique to each request (one-time tokens)

2. Choose the Architecture

"We'll use a multi-level cache: L1 in-process cache with 5-minute TTL for hot data, backed by Redis as L2 with 1-hour TTL. This gives us microsecond reads for repeat requests while keeping all servers consistent."

3. Address Invalidation

"For invalidation, we'll use [TTL / events / write-through] because [reason]. TTL of X minutes gives us bounded staleness while maintaining a 95%+ hit rate."

4. Handle Edge Cases

Before the interviewer asks:
"For cache stampede, we'll use singleflight to coalesce concurrent misses. For hot keys, we'll replicate across multiple cache keys. If Redis fails, we'll degrade gracefully by falling back to database with rate limiting."

5. Address Security

"For security, we'll cache negative results to prevent penetration attacks, use jittered TTLs to avoid avalanche, validate all cache keys to prevent poisoning, and ensure Redis is not exposed to the public internet with authentication required."

6. Mention Monitoring

"We'll monitor cache hit rate (target >95%), p99 latency (<5ms), and memory utilization. Alerts fire if hit rate drops below 90% or evictions spike."

Key Takeaways

Caching Mastery Mindmap

Caching Mastery Mindmap

The fundamentals:
  1. Caching trades memory for speed. Understand when it's worth it.
  2. Multi-level caching (L1 + L2) gives microsecond reads with cross-server consistency.
  3. Cache-aside is your default pattern. Learn the others for specific use cases.
The hard parts: 4. Invalidation has no perfect solution. Every strategy trades consistency for something else. 5. Cache stampedes can make caching worse than no caching. Use singleflight. 6. Cache bugs are hard to diagnose. Invest in observability.
The security essentials: 7. Cache penetration, avalanche, and poisoning are real attacks. Defend against them. 8. Never expose Redis to the internet. Always require authentication and use TLS. 9. Don't cache sensitive data in plaintext. Encrypt or hash.
The production reality: 10. "Just add Redis" isn't a strategy. Know single vs. Sentinel vs. Cluster. 11. Monitor hit rate, latency, and memory. Set alerts. 12. Plan for cache failure. Your system should degrade gracefully, not collapse.

What's Next?

In Part 6: Event-Driven Architecture, we'll explore:
  • Kafka vs RabbitMQ vs SQS — when to use each
  • Event sourcing for audit trails and debugging
  • CQRS for systems with asymmetric read/write loads
  • Saga pattern for distributed transactions

Found this helpful? Share it with someone preparing for system design interviews.
All Blogs
Tags:cachingredissystem-designscalabilityperformancedistributed-systemsbackendinterview-prep