Caching strategies

From FerroxLabs/wayland · View interactive version

Caching strategies is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level caching strategies implementation: optimization and database decision frameworks, production-ready patterns, and concrete templates for caching strategies workflows. Use when the user asks about caching strategies, caching strategies configuration, or backend best practices for c

How to use this skill

Skill file

Caching Strategies

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Profile the Workload Before Designing Any Cache

Never design a cache for a workload you have not measured. Guessing cache placement wastes engineering effort and can make performance worse.


2. Select the Caching Layer

There are five distinct caching layers, each with different latency characteristics, consistency properties, and implementation complexity. Match the layer to the data access pattern.

For most production web applications, the right answer is a two-level cache: in-process LRU for hot reference data combined with Redis for shared mutable state.


3. Select the Cache Pattern

The pattern determines how data gets into the cache, how writes are handled, and what happens on a miss. Each pattern has specific use cases.

Cache-Aside (Lazy Loading):

Read-Through:

Write-Through:

Write-Behind (Write-Back):

Refresh-Ahead (Prefetch):


4. Design Cache Keys

Poor key design causes cache pollution, incorrect sharing of data across users, and difficult invalidation. Apply these practices:


5. Configure TTL and Eviction Policy

TTL and eviction are the primary knobs controlling cache effectiveness and memory safety.

TTL Selection Framework:

TTL Jitter: Add ±10-20% random jitter to all TTLs to prevent synchronized expiration (cache stampede). If 10,000 sessions are all cached with TTL=3600, they expire simultaneously at the hour mark, flooding the database. Jitter staggers the expiration across the TTL window.

Redis Eviction Policies:


6. Handle Cache Failure and Consistency Hazards

A cache that causes outages when it fails, or that serves incorrect data, is worse than no cache.

Cache Miss Storms (Thundering Herd):

Stale-While-Revalidate:

Cache Stampede on Cold Start:

Split-Brain / Inconsistent Reads in Redis Cluster:


7. Implement Cache Monitoring and Observability

An unmonitored cache is a liability. These metrics determine whether the cache is working correctly.

Key Metrics to Track:

Instrumentation approach:


8. Document the Caching Architecture Decision

Cache design decisions have long-term maintenance implications. Document them explicitly.


Output Format

## Caching Architecture Analysis

### Workload Profile
| Data Entity         | Access Pattern      | Read:Write Ratio | Cacheable | Notes                     |
|---------------------|---------------------|------------------|-----------|---------------------------|
| [entity name]       | [random/sequential] | [X:1]            | [yes/no]  | [staleness tolerance]     |

### Recommended Caching Stack
- **Layer 1 (in-process):** [library] -- for [entity types], TTL [duration]
- **Layer 2 (distributed):** [Redis/Memcached config] -- for [entity types], TTL [duration]
- **Eviction policy:** [policy name] -- rationale: [reason]
- **maxmemory:** [value and % of host RAM]

### Pattern Selection
| Data Entity         | Pattern        | TTL     | Invalidation Trigger        | Consistency Guarantee |
|---------------------|----------------|---------|-----------------------------|-----------------------|
| [entity name]       | [pattern name] | [value] | [event or schedule]         | [eventual/strong]     |

### Cache Key Schema
| Entity              | Key Template                          | Example                          |
|---------------------|---------------------------------------|----------------------------------|
| [entity name]       | [namespace]:[entity]:[id]:[version]   | catalog:product:84729:v2         |

### Implementation Notes
- **Thundering herd mitigation:** [mutex lock / probabilistic refresh / stale-while-revalidate]
- **TTL jitter:** [±X% on all TTLs]
- **Cold start strategy:** [warming script / request coalescing / gradual traffic shift]

### Monitoring Targets
| Metric              | Warning Threshold | Critical Threshold | Action                     |
|---------------------|-------------------|--------------------|----------------------------|
| Hit rate            | < 80%             | < 60%              | Review key design, TTL     |
| Memory usage        | > 75%             | > 85%              | Increase maxmemory or scale|
| Eviction rate       | > 100/min         | > 1000/min         | Cache is undersized        |
| Connection pool     | > 70% utilized    | > 90% utilized     | Increase pool size         |

### Implementation Skeleton
[Language-specific code for the chosen pattern]

Rules

  1. Never design a cache before measuring the workload. A cache applied to a non-bottleneck path wastes memory and adds operational complexity with zero user-visible benefit. Always get query latency numbers first.
  1. Never cache data with a read:write ratio below 3:1 using write-through. The write overhead and invalidation churn exceed the read latency savings. Use cache-aside with short TTL or skip caching for write-heavy entities.
  1. Never use Redis KEYS * in production for any purpose. It blocks the entire Redis event loop for the duration of the scan, causing latency spikes across all consumers. Always use SCAN with a cursor and a COUNT hint (e.g., SCAN 0 MATCH prefix:* COUNT 100).
  1. Always add TTL jitter of ±10-20%. Synchronized expiration of large numbers of keys causes cache stampede and sudden database load spikes. This rule applies to every TTL set in every cache layer.
  1. Never use write-behind caching for data where loss is unacceptable. Write-behind sacrifices durability for throughput. Financial records, order history, authentication events, and audit logs must be written synchronously to the database regardless of the performance cost.
  1. Always set a maxmemory limit on Redis when used as a cache. Without this, Redis will consume all available host memory and cause OOM failures affecting co-located processes. Set maxmemory to 70-80% of available RAM and pair it with an appropriate eviction policy.
  1. Never store sensitive data in a shared cache without encryption or access controls. Redis in default configuration has no authentication and no encryption at rest. PII, authentication tokens, and session data stored in a shared Redis must use Redis ACLs and TLS transport. Consider whether shared cache access logging meets your compliance requirements.
  1. Always implement graceful cache degradation. When the cache is unavailable, the application must fall back to the database with appropriate circuit breaker logic. Never let a cache failure cascade into a full application outage. The database should always be able to serve traffic at degraded but functional throughput.
  1. Never use a single cache key for data shared across tenants in a multi-tenant system. A single shared key means tenant A's data can be returned to tenant B, creating a data leak. Always namespace keys by tenant ID and verify ownership before returning cached data.
  1. Always benchmark cache hit rate after deployment and at 30-day intervals. Access patterns drift over time as usage evolves. A cache designed for the initial workload may have poor hit rates six months later due to new features, changed query patterns, or a shifted user base. Treat hit rate monitoring as a permanent operational responsibility, not a post-launch verification step.

Edge Cases

Hot Key Concentration (Cache Hotspot)

A single Redis key receiving tens of thousands of requests per second saturates the CPU of the single Redis node that owns that key slot. This is common for global reference data (top-rated products, homepage configuration) and viral content.

Handling:

Cache Poisoning After a Bug Deploy

A bug in application code writes incorrect data to the cache. The bug is fixed in the next deploy but the corrupted cache entries persist until their TTL expires.

Handling:

Large Object Caching (>1MB Values)

Storing objects larger than 1MB in Redis increases network serialization time, disrupts Redis pipeline efficiency, and can trigger slow log entries.

Handling:

Cache in Database Read Replicas Environment

Some teams use a cache to reduce read replica lag effects -- if stale data from a replica is cached, it may be served long after the replica has caught up, creating longer effective staleness than the replica lag alone.

Handling:

Distributed Cache Consistency During Rolling Deploys

During a rolling deploy that changes cache key schemas, data serialization formats, or TTL policies, multiple application versions run simultaneously and write to the same cache.

Handling:

Multi-Region Caching Consistency

Applications deployed across multiple geographic regions with a Redis cache per region face cross-region consistency challenges when a write in Region A must be reflected in Region B's cache.

Handling:


Example

Input: "We have a product catalog API backed by PostgreSQL. There are 500,000 products. Read traffic is approximately 50,000 requests/minute during peak. About 95% of those reads target the same 10,000 products. Writes (price updates, stock changes) happen at about 200/minute. Product page response time is currently 180ms p50, 420ms p95. We are running 8 Node.js application instances. We want to get p50 below 20ms."


Output:

Caching Architecture Analysis

Workload Profile

| Data Entity | Access Pattern | Read:Write Ratio | Cacheable | Notes |

|---------------------|----------------------|------------------|-----------|--------------------------------------------|

| Product detail | Heavily skewed (Zipf)| 250:1 | Yes | 10K hot products out of 500K total |

| Product price | Hot subset same 10K | 250:1 | Yes | Staleness tolerance: 30s acceptable |

| Stock availability | Hot subset | 150:1 | Yes | Staleness tolerance: 5s; never cache 0-stock as "in-stock" |

| Product images/media| CDN-served | -- | CDN layer | Out of scope for this analysis |

Assessment: The 95%/10K hotspot concentration is ideal for caching. A 10,000-product cache at ~2KB per serialized product record = 20MB -- trivially small for in-process or Redis caching. This is a textbook Zipf distribution; even an L1 in-process cache with a 60-second TTL will absorb most traffic before it reaches PostgreSQL.


Recommended Caching Stack


Pattern Selection

| Data Entity | Pattern | TTL | Invalidation Trigger | Consistency Guarantee |

|----------------------|-----------------------|----------------|---------------------------------------|-----------------------|

| Product detail | Read-through (L1+L2) | L1: 60s, L2: 300s | Price/stock update event | Eventual (≤ 310s max staleness) |

| Product price | Cache-aside + write-through | L1: 30s, L2: 30s | Price update webhook/event | Eventual (≤ 35s) |

| Stock availability | Cache-aside | 10s ±2s | Stock mutation event | Eventual (≤ 12s) |

Note on write-through for prices: Price updates happen at 200/minute -- the write overhead is negligible. The consistency improvement (cache updated immediately on write) eliminates the window where users see stale prices without complex invalidation logic.


Cache Key Schema

| Entity | Key Template | Example |

|---------------------|-------------------------------------------|--------------------------------------|

| Product detail | catalog:product:{productId}:v3 | catalog:product:84729:v3 |

| Product price | catalog:price:{productId}:v1 | catalog:price:84729:v1 |

| Stock availability | catalog:stock:{productId}:v1 | catalog:stock:84729:v1 |

Version suffix v3 on product detail allows a full cache bust by incrementing to v4 in a config variable -- all v3 keys expire naturally via TTL.


Thundering Herd Mitigation

For a 10,000 product working set with 8 Node.js instances, synchronized TTL expiration at peak traffic (50K RPM) could send up to 6,250 RPM to PostgreSQL in a worst case. Jitter alone is sufficient at this scale -- no distributed mutex needed.

If traffic were 10x higher, implement a per-key mutex using Redis SET NX:

// Pseudo-mutex to prevent stampede on high-traffic keys
const lockKey = `lock:catalog:product:${productId}`;
const acquired = await redis.set(lockKey, '1', 'NX', 'EX', 5);
if (!acquired) {
  // Wait up to 200ms for the lock holder to populate cache
  await sleep(50 + Math.random() * 150);
  return getProductFromCacheOrDB(productId); // retry
}

Implementation Skeleton (Node.js)

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

// Layer 1: In-process LRU
const l1Cache = new LRUCache({
  max: 15_000,
  ttl: 60_000, // 60 seconds base; jitter applied on set
  ttlResolution: 1000,
});

// Layer 2: Redis
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const JITTER_FACTOR = 0.15; // ±15%

function withJitter(ttlSeconds) {
  const jitter = (Math.random() * 2 - 1) * JITTER_FACTOR;
  return Math.round(ttlSeconds * (1 + jitter));
}

async function getProduct(productId) {
  const l1Key = `product:${productId}`;

  // L1 hit
  const l1Hit = l1Cache.get(l1Key);
  if (l1Hit) {
    metrics.increment('cache.l1.hit');
    return l1Hit;
  }
  metrics.increment('cache.l1.miss');

  // L2 hit
  const redisKey = `catalog:product:${productId}:v3`;
  const l2Hit = await redis.get(redisKey);
  if (l2Hit) {
    metrics.increment('cache.l2.hit');
    const parsed = JSON.parse(l2Hit);
    // Populate L1 from L2 hit
    l1Cache.set(l1Key, parsed, { ttl: withJitter(60) * 1000 });
    return parsed;
  }
  metrics.increment('cache.l2.miss');

  // Database fallback
  const product = await db.query(
    'SELECT * FROM products WHERE id = $1',
    [productId]
  );

  if (!product) return null;

  // Populate both layers
  const serialized = JSON.stringify(product);
  await redis.setEx(redisKey, withJitter(300), serialized);
  l1Cache.set(l1Key, product, { ttl: withJitter(60) * 1000 });

  return product;
}

// Write-through for price updates
async function updatePrice(productId, newPrice) {
  // 1. Write to database first (source of truth)
  await db.query(
    'UPDATE products SET price = $1 WHERE id = $2',
    [newPrice, productId]
  );

  // 2. Update cache synchronously (write-through)
  const redisKey = `catalog:price:${productId}:v1`;
  await redis.setEx(redisKey, withJitter(30), JSON.stringify({ price: newPrice }));

  // 3. Invalidate product detail cache to force refresh with new price
  await redis.unlink(`catalog:product:${productId}:v3`);
  l1Cache.delete(`product:${productId}`);
}

Monitoring Targets

| Metric | Warning Threshold | Critical Threshold | Action |

|---------------------|-------------------|--------------------|---------------------------------------------|

| L1 hit rate | < 70% | < 50% | Increase LRU max size; check hotspot shift |

| L2 hit rate | < 85% | < 70% | Review TTL settings; check eviction rate |

| Redis memory usage | > 1.5GB (75%) | > 1.7GB (85%) | Evaluate working set size; scale memory |

| Redis eviction rate | > 50/min | > 500/min | Cache undersized for working set |

| DB query rate (RPM) | > 5,000 | > 15,000 | Cache miss storm or cache failure |

| p95 response time | > 50ms | > 200ms | Investigate cache layer; check L2 latency |


Expected Outcome

With this two-layer cache implementation:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.