FALVARIX
FALVARIX
devops --real --no-hype

Redis in Production: Distributed Caching for Your API

Redis in Production: Distributed Caching for Your API

Redis in Production: Distributed Caching for Your API

Your API responds in 800 ms. 70% of that time is spent waiting on the database to return, over and over, the same data that hasn’t changed in hours. Nobody notices until the traffic spike hits, PostgreSQL CPU goes through the roof and users start seeing timeouts.

That’s the classic scenario where Redis in production stops being a luxury and becomes core infrastructure. A well-designed distributed cache can take endpoints from hundreds of milliseconds down to under 10 ms. Under read-heavy loads, a 90% improvement in response times is realistic, and even more so at the 95th percentile.

But wiring a client to Redis and calling SET is not a caching strategy. In this guide you’ll see the patterns, configuration and metrics that separate a cache that speeds things up from one that causes incidents.

Why a distributed cache and not a local in-memory cache

A local cache inside the process (a dictionary, Caffeine, lru_cache) is blazing fast, but it has a serious problem once you scale: each instance of your application keeps its own copy. With ten replicas you get ten different caches, ten low hit rates and ten different moments when the data expires.

A distributed cache solves three problems at once:

  • Consistency: all instances read and write the same state. Invalidate a key and it’s invalidated for everyone.
  • Memory efficiency: a single set of hot data instead of N duplicates.
  • Resilience to scaling: when new replicas spin up (say, with Kubernetes autoscaling), the cache is already warm and there’s no cold start.

Redis is a particularly good fit because it offers rich data structures (hashes, sorted sets, streams), sub-millisecond latencies and a mature client ecosystem in any language.

What to cache and what not to

The most common mistake is caching everything. The rule of thumb: cache what is expensive to compute, read often and tolerant of some staleness.

Good candidates:

  • Catalogs, product pages and configurations.
  • Results of aggregate queries or reports.
  • Sessions and short-lived tokens.
  • Responses from third-party APIs with rate limits.

Bad candidates: account balances, real-time inventory or any data where serving a 30-second-old version has financial or legal consequences. If in doubt, start with the 5 slowest or most-called endpoints of your API and measure before expanding.

Caching patterns that work in production

Cache-aside: the default pattern

The application checks Redis first; on a miss, it reads from the database and stores the value with a TTL.

import json, redis

r = redis.Redis(host="redis", port=6379, decode_responses=True)

def get_product(product_id: int):
    key = f"api:v1:product:{product_id}"
    cached = r.get(key)
    if cached:
        return json.loads(cached)

    product = db.fetch_product(product_id)
    r.set(key, json.dumps(product), ex=300)
    return product

It’s simple, it tolerates Redis going down (the app keeps working, just slower) and it’s the pattern you should master first.

Write-through and explicit invalidation

When data changes, you have two options: update the cache in the same write operation (write-through) or delete the key so the next read regenerates it. The second is safer: it avoids storing an inconsistent state if the database write fails halfway.

def update_product(product_id, data):
    db.update_product(product_id, data)
    r.delete(f"api:v1:product:{product_id}")

Always delete after confirming the database write, never before.

How to avoid the cache stampede

Picture a very popular key that expires. At that instant, 500 concurrent requests miss the cache and all 500 go to the database to regenerate the same value. That’s the cache stampede, and it takes down services that looked healthy.

Three defenses you can combine:

  1. Regeneration lock: only one request recalculates; the rest wait or serve the previous value. Implement it with SET lock:clave 1 NX EX 10.
  2. TTL with jitter: add a random margin (say, ±10%) so keys don’t all expire at once.
  3. Early refresh: regenerate the key while it still has some life left, before it expires.

Key design and TTL strategy

A good key convention will save you hours of debugging. Use hierarchical, versioned namespaces: api:v2:user:1234:profile. The version prefix lets you invalidate in bulk after a format change without running dangerous commands.

As for TTL, every cache key must have one. Without it, memory grows until Redis starts evicting data indiscriminately. As a guideline:

Data typeSuggested TTL
Configuration and catalogs15 min – 1 h
Product pages5 – 15 min
Search results30 – 120 s
SessionsPer security policy

And avoid KEYS * in production: it blocks the server while it walks the entire keyspace. Use SCAN with a cursor instead.

Production-ready Redis configuration

Memory and eviction policy

Always set a memory limit and an eviction policy. For a pure cache, allkeys-lru or allkeys-lfu are the usual choices.

maxmemory 2gb
maxmemory-policy allkeys-lfu
tcp-keepalive 60
timeout 0

Leave headroom on the server: Redis may need extra memory during persistence and replication. As a rule, don’t give maxmemory more than 70-75% of available RAM.

Persistence: do you need it?

If Redis is only a cache, you can disable persistence and rebuild from the database. But a restart with an empty cache triggers an avalanche against the origin. A periodic RDB snapshot is usually a good compromise: smoother restarts without the write cost of AOF. If you also use Redis for queues or sessions, enable AOF with appendfsync everysec.

High availability: Sentinel or Cluster

  • Redis Sentinel: one primary, replicas and several Sentinels that detect failures and promote a replica. The right choice when your dataset fits on one node and you want simplicity.
  • Redis Cluster: spreads data across shards using 16,384 hash slots. Scales memory and writes horizontally, but requires a cluster-aware client and that you design multi-key operations with hash tags.

For most mid-sized APIs, Sentinel with one primary and two replicas across availability zones is more than enough. If you’d rather not operate it yourself, managed services like Amazon ElastiCache hand failover and patching to the provider.

Security: Redis should never be exposed

Redis was born for trusted networks and its defaults aren’t safe for the internet. The non-negotiable minimums:

  • Bind it to a private interface (bind) and protect it with a firewall or container network.
  • Enable requirepass or, better, ACLs with least-privilege users.
  • Encrypt traffic between app and Redis with TLS if it crosses networks you don’t control.
  • Disable or rename dangerous commands like FLUSHALL, CONFIG or DEBUG.
  • Don’t commit passwords to the repo: apply secret management with OpenBao to inject them at runtime.

Monitoring: what you don’t measure, you can’t improve

A cache without metrics is a black box. Keep an eye on these indicators with the Redis exporter:

  • Hit ratio (keyspace_hits / (hits + misses)): below 80-85% and you should review what you’re caching and your TTLs.
  • Used memory and evicted_keys: if evictions are climbing, the cache is too small or there are keys without TTL.
  • Latency and slow commands (SLOWLOG).
  • Connected and rejected clients.
  • Replication lag if you use replicas.

With Prometheus and Grafana you can send critical alerts to Slack and Telegram when the hit ratio drops or memory approaches the limit. And if you want to cross-reference these figures with business impact, a solid Grafana dashboard that combines business and infrastructure metrics will show you what each miss really costs.

How to verify you’ve gained that 90%

Don’t trust your gut: measure before and after under the same load. A simple method:

  1. Capture the baseline p50, p95 and p99 latency of the chosen endpoints with a load tool like k6 or wrk.
  2. Enable the cache and let it warm up for a few minutes.
  3. Repeat the test and compare, along with database CPU and connections.

A typical example: a listing endpoint with three joins drops from 420 ms to 18 ms on a hit and the database load falls to a fraction. Remember the result depends on your hit ratio: with 95% hits, average latency approaches the hit latency. With 50%, the gain will be modest. That’s why key and TTL design matters as much as Redis itself.

If you also have a proxy in front, combine both layers: caching and rate limiting in Nginx as a load balancer absorb identical traffic before it reaches the application, and Redis covers the dynamic data that depends on business logic.

Common mistakes that will cost you an incident

  • Keys without TTL that silently fill up memory.
  • Giant values (megabytes per key): they block Redis’s main thread and saturate the network. Compress or split them.
  • “Hot” keys that concentrate all traffic on a single shard.
  • Treating the cache as the source of truth: if losing Redis means losing data, you’re using the wrong tool.
  • No plan for cold starts: preload the most critical keys or limit concurrency toward the origin.
  • No client timeouts: if Redis slows down, your API should fall back to the database in milliseconds, not hang waiting.

Conclusion

Redis can transform your API’s performance, but the leap doesn’t come from installing it — it comes from operating it wisely: cache-aside with TTL and jitter, stampede protection, clear memory limits, high availability, security from day one and metrics that tell you whether the cache is doing its job.

Start small: pick your three slowest endpoints, cache them, measure the difference and expand from there. Once you see latency and database load drop, you’ll have the data to justify the next step.

Keep reading