StackPractices
advanced By Mathias Paulenko

Complete Guide to Redis in Production: HA & Persistence

Keep Redis stable in production: RDB/AOF persistence, Sentinel vs Cluster for HA, memory management, security hardening, monitoring, and backups.

Introduction

Running Redis on your laptop and running it in production are different jobs. On localhost, a crashed cache costs you a restart. In production, Redis sits in the request path of your application — a failover, a memory blowup, or a misconfigured ACL becomes an outage or a data leak that users notice.

Operations are where Redis earns or loses trust: persistence configured so a crash costs seconds instead of hours, the right choice between Sentinel and Cluster for failover, memory kept under control, and the instance locked down, monitored, and backed up. It assumes you already know Redis data types — the examples target Redis 7.x. If you’re still picking caching patterns, start with Redis caching strategies and come back when you’re ready to deploy.

Quick answers before you read on:

  • One node holds your data but downtime is unacceptable → Sentinel.
  • One node can’t hold your data or serve your throughput → Cluster.
  • Pure cache you can rebuild from the database → a single instance is enough.
  • You need ACID, joins, or queries → Redis is the wrong tool — use a database.

Deployment Architecture

Before touching configs, decide what failure modes you can tolerate. A single Redis instance handles more traffic than most people expect — tens of GB and hundreds of thousands of ops/sec — but it’s also a single point of failure. The two production topologies that matter:

  • Sentinel: one master, one or more replicas, and a quorum of Sentinel processes that detect failure and promote a replica. The app keeps talking to “the master”; Sentinel re-points it. Capacity stays at one node’s worth — this is about availability, not scale.
  • Cluster: data sharded across multiple masters by hash slot, with replicas per shard. Capacity and throughput scale horizontally; the trade-off is operational complexity and multi-key restrictions.
flowchart diagram: App[Application

Most deployments should start with Sentinel: it gives you automatic failover without sharding complexity. Move to Cluster when one node genuinely can’t hold your data or serve your throughput — not before.

Persistence: RDB and AOF

Redis gives you two ways to survive a restart, and they answer different questions. RDB snapshots dump the whole dataset to disk on a schedule; AOF appends every write to a log.

RDB Snapshots

RDB writes a compact, point-in-time dump of the dataset. Recovery is fast — you load one file — but everything written since the last snapshot is gone.

# redis.conf — save <seconds> <changes>
save 900 1      # snapshot if ≥1 key changed in 15 minutes
save 300 10     # snapshot if ≥10 keys changed in 5 minutes
save 60 10000   # snapshot if ≥10000 keys changed in 1 minute

The save lines stack — any condition triggers a snapshot. For a pure cache you can go lighter (or disable persistence entirely); for anything resembling a store, the defaults above are a sane starting point. Snapshots also cost fork time: on a 20GB instance the fork alone can pause writes for a noticeable moment, so schedule heavier intervals outside peak if you can.

AOF (Append-Only File)

AOF logs every write command and replays the log on restart. With appendfsync everysec you lose at most one second of writes — the standard production trade-off between durability and write overhead.

appendonly yes
appendfsync everysec
# auto-rewrite when the AOF doubles in size and is ≥64MB
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

always gives you zero-loss writes at a real latency cost per write; no is the fastest but can lose up to 30 seconds. everysec is the right default for almost everything — use always only when a lost write is genuinely unacceptable and you have measured the overhead.

Which one, or both?

For a pure cache where rebuild-from-database is cheap, RDB (or nothing) is enough. For write-behind queues, sessions you can’t lose, or anything where Redis briefly holds the only copy, you want AOF. Many production systems run both: AOF for durability, RDB for fast restarts and point-in-time backups.

Memory Management

Redis keeps everything in RAM, so memory is the resource you manage most carefully.

maxmemory 4gb
maxmemory-policy allkeys-lru

Two numbers drive the math. used_memory is what your data actually takes; maxmemory is the ceiling you set. Run sustained over ~80% of maxmemory and you’re letting the eviction policy do your capacity planning — which works until it evicts something you needed.

Choosing an eviction policy

The policy decides what dies when memory fills up:

PolicyEvictsUse when
noevictionNothing — writes errorRedis holds data you cannot lose
allkeys-lruLeast recently used, all keysDedicated cache — the usual answer
allkeys-lfuLeast frequently used, all keysSkewed access (few hot keys)
volatile-lruLRU among keys with TTLMixed cache + persistent data
volatile-ttlShortest TTL firstTime-boxed data only
volatile-randomRandomUniform access, simplest

For a dedicated cache instance, allkeys-lru is the right default. If you’re mixing cache entries and data you can’t afford to drop, don’t solve it with volatile-* — run a second instance. LFU policies are approximations that decay over time; fine for caching, worth knowing before you rely on them.

Eviction decides what Redis drops when memory fills; invalidation decides what your app drops when data changes — a different problem, covered in the cache invalidation guide.

Fragmentation

Watch mem_fragmentation_ratio: values above ~1.5 mean you’re wasting RAM to allocator slack. activedefrag yes can compact in the background on modern Redis; otherwise a rolling restart of replicas (failover, restart, fail back) clears it.

High Availability: Sentinel vs Cluster

Both give you failover; they differ in what else they give you. Decide by capacity and throughput, not by fashion.

SentinelCluster
PurposeHA only — one master’s capacityHA + horizontal sharding
FailoverAutomatic (quorum of sentinels)Automatic (replica promotion per shard)
ScalingNone — vertical onlyAdd masters, re-shard slots
Multi-key opsUnrestrictedKeys must share hash slot
Client complexitySimple — connect to SentinelCluster-aware client required
WhenOne node holds your dataOne node cannot hold your data

Sentinel

Sentinel needs at least three processes to form a quorum and avoid split-brain — typically on separate machines alongside the master and replicas.

# sentinel.conf
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1

mymaster is the logical name your client connects to; 2 is the quorum — the number of sentinels that must agree the master is down before a failover starts. down-after-milliseconds is how long an unresponsive master waits before being marked down. On the client side, connect to Sentinel rather than a fixed host, and the client follows the promoted master.

from redis.sentinel import Sentinel

sentinel = Sentinel([("localhost", 26379), ("localhost", 26380)])
master = sentinel.master_for("mymaster", socket_timeout=0.1)
replica = sentinel.slave_for("mymaster", socket_timeout=0.1)

Cluster

Cluster splits the keyspace into 16,384 hash slots distributed across masters. Keys with the same hash tag — {user}:42:profile, {user}:42:prefs — land on the same slot, which is how you keep multi-key operations working.

from redis.cluster import RedisCluster  # requires redis-py >= 4.1

rc = RedisCluster(host="localhost", port=7000)
rc.set("user:42", "Alice")          # routed to the slot's master
rc.mget("{user}:42:a", "{user}:42:b")  # same slot → allowed

The cost is real: cluster-aware clients, MOVED/ASK redirects during re-sharding, and restrictions on multi-key and transaction semantics. Sentinel with a bigger box solves most scale problems until you outgrow a single large node.

Security

Redis was built for trusted networks — out of the box it listens on all interfaces with no auth. Before anything else:

  1. Bind to private interfaces. bind 127.0.0.1 for same-host, or your private network interface for cluster traffic. Never expose Redis to the public internet — it has been a top mass-exploitation target for years.
  2. Require auth. requirepass gives you a shared secret; better, use ACLs to create per-service users.
  3. Rename or disable dangerous commands. FLUSHALL, CONFIG, DEBUG, KEYS and SHUTDOWN have no business in an app-facing instance.
bind 127.0.0.1 -::1
requirepass "a-long-random-password"
rename-command FLUSHALL ""
rename-command CONFIG "CONFIG-9f2k-admin"
rename-command KEYS ""

ACLs

Redis 6+ ACLs let you scope users to commands and key patterns — the right model for multi-service deployments.

# read-only user for a reporting service
ACL SETUSER reporter on >rep-pass ~cache:* +get +info

# app user that can read/write cache keys but not admin
ACL SETUSER app on >app-pass ~app:* +@all -@dangerous

TLS

Redis speaks plaintext by default; any traffic crossing a network boundary should go over TLS. Modern Redis supports tls-port natively — run TLS and plaintext on separate ports, and require TLS from off-machine clients.

port 0                  # disable plaintext entirely
tls-port 6379
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
tls-ca-cert-file /path/to/ca.crt

Disabling plaintext with port 0 closes the classic misconfiguration where TLS exists but the old port stays open. Client-side, most redis-py versions accept rediss:// URLs and a ssl_cert_reqs parameter — use them; a TLS endpoint that clients bypass in plaintext is TLS for show. Note that Sentinel and Cluster gossip has its own TLS story (tls-replication yes) — enabling TLS only on the client port while replication flows in plaintext is a half-done job.

Performance

Redis is single-threaded per command, which is why it’s fast — but it means every microsecond you save per command compounds.

  • Pipeline instead of per-request round trips. Sending 100 commands one by one costs 100 RTTs; pipelining sends them in one. It’s the single biggest win for bulk operations.
  • Pool connections. A TCP handshake plus Redis auth costs more than the command you wanted to run. Reuse a pool sized to your worker count — see the pooling section below.
  • Lua for atomic multi-step ops. A Lua script runs atomically on the server — no race between GET, modify, SET. Ideal for counters, rate limiters, check-and-set patterns.
# Pipelining — one round trip for 100 commands
pipe = r.pipeline()
for i in range(100):
    pipe.set(f"key:{i}", f"value:{i}")
pipe.execute()

# Lua — atomic increment with cap
r.eval("""
local v = redis.call('GET', KEYS[1]) or 0
if tonumber(v) < tonumber(ARGV[1]) then
    return redis.call('INCR', KEYS[1])
end
return v
""", 1, "rate:counter", 1000)
# Connection pool — reuse, don't reconnect per request
pool = redis.ConnectionPool(host="localhost", port=6379, max_connections=50)
r = redis.Redis(connection_pool=pool)

Size max_connections to workers plus headroom: 20 app instances × 50 connections means the server must accept up to 1,000 — check maxclients on the Redis side.

Monitoring

You can’t operate what you can’t see. Collect these from day one and alert on the thresholds, not the averages.

MetricWatch forThreshold
used_memory / maxmemoryCapacity pressureAlert > 80%
evicted_keys rateUndersized cache / wrong TTLsAlert if sustained > 0 on non-cache
keyspace_hits / (hits+misses)Cache effectivenessInvestigate < 80%
connected_clientsConnection leaksAlert on unexplained growth
blocked_clientsSlow commandsAlert if > 0 sustained
instantaneous_ops_per_secThroughput / anomaly detectionBaseline your own normal
rejected_connectionsmaxclients hitAlert > 0
rdb_last_save_time / aof_last_write_statusPersistence healthAlert on stale save / failure
mem_fragmentation_ratioAllocator wasteInvestigate > 1.5
master_link_status (replicas)Replication brokenAlert down
redis-cli INFO memory | grep -E "used_memory_human|maxmemory|mem_fragmentation"
redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses|evicted_keys|rejected_connections"
redis-cli INFO replication | grep -E "master_link_status|master_last_io_seconds"

Two that bite teams in production: blocked_clients climbing steadily usually means a slow command (KEYS, SMEMBERS on a huge set, a heavy Lua script) is serializing the event loop — find it with SLOWLOG GET. And master_last_io_seconds_ago growing on a replica means replication is lagging, which silently turns your “replica” into stale data.

Backup and Recovery

Redis backups are simpler than a real database’s — but only if you plan for them.

  • RDB files are the backup. dump.rdb is a compact, single-file snapshot — copy it off the box (object storage, another region) on a schedule. SAVE/BGSAVE from cron or a replica.
  • Use a replica for backups. Snapshot on a replica, not the master — the fork pause and I/O hit land where no one is writing.
  • Test restores. A backup you’ve never restored is a hope, not a backup. Script a restore drill into staging.
  • AOF for point-in-time-ish recovery. With everysec you replay to within a second of the crash; RDB restores you to the snapshot time. Pick based on how much you can afford to lose.
# snapshot on a replica, then copy it off
redis-cli -h replica-host BGSAVE
scp replica-host:/var/lib/redis/dump.rdb s3://backups/redis-$(date +%F).rdb

For a pure cache, “backup” can mean “we rebuild from the database” — but write that down as a decision, not an accident. The distinction matters most when you’re asked “where did the data go?” after an incident: a documented rebuild path answers the question in minutes; an undocumented one starts a forensic session nobody budgeted for.

Capacity Planning

Sizing Redis means sizing memory, then throughput — in that order, because memory is what you run out of first.

Start with your working set: the bytes of data that must actually live in Redis, not the total you could store. Measure it by loading a representative slice and reading used_memory — not by multiplying rows times a guessed row size, because serialization overhead (JSON strings vs hashes vs MessagePack) changes the number by 2-4x. Add 20-30% headroom for fragmentation, replication buffers, and spikes, then double it if you run AOF rewrite or BGSAVE on the same node (the fork can briefly require memory equal to the dataset).

For throughput, a single modern Redis handles roughly 100k-1M simple ops/sec depending on value size and pipelining — so CPU is rarely the first wall; memory and network bandwidth usually are. If you hit the wall anyway, check SLOWLOG for heavy commands before blaming the instance.

A few rules that save real outages:

  • Leave OS memory free. Redis isn’t the only process; give it maxmemory at ~60-70% of physical RAM, not 100% — the fork for BGSAVE/AOF needs room.
  • Watch the network, not just the CPU. Redis saturates the NIC before the CPU on large values; instantaneous_output_kbps tells you when.
  • Plan re-sharding before you need it. Cluster re-sharding moves data live; doing it under pressure is how slots end up on the wrong nodes.

Networking and Latency

Co-locate Redis in the same region — ideally the same AZ — as your app servers. Every extra RTT multiplies: a 1ms RTT on 50 sequential GETs is 50ms of invisible latency per request; pipelining converts that to one round trip and is why it’s the single most important client-side optimization.

Measure before blaming: redis-cli --latency gives you the wire cost, --intrinsic-latency 10 tells you if the host itself is slow (virtualization steal, noisy neighbors). If --latency is fine but app-visible latency is not, the problem is serialization, connection churn, or slow commands — not Redis.

Common Mistakes

A handful of deployment errors recur in incident reports more than everything else combined:

  • Running with no maxmemory or noeviction on a cache. The instance fills up, then every write fails — the outage looks like a Redis bug when it’s a config default.
  • Exposing Redis on a public interface. A bind 0.0.0.0 with no auth gets found and exploited in hours, not days.
  • Using KEYS, FLUSHALL, or huge SMEMBERS in request path. They block the single-threaded event loop; SLOWLOG GET will show them — rename or avoid them.
  • Snapshotting on the master under write load. The BGSAVE fork pause lands where users are writing; do it on a replica.
  • Hardcoding a master host instead of going through Sentinel. After a failover your app keeps talking to the old master — or nothing.
  • Treating replication lag as real redundancy. A replica seconds behind is stale data wearing a “replica” label; monitor master_last_io_seconds_ago.

Production Checklist

Before a Redis instance touches production traffic, confirm:

  1. maxmemory set and an eviction policy chosen deliberately (not left noeviction by accident).
  2. Persistence configured to your loss tolerance — RDB, AOF, or both, decided on purpose.
  3. requirepass/ACLs in place; bind restricted; dangerous commands renamed or disabled.
  4. TLS on any traffic that leaves the host.
  5. Sentinel or Cluster if downtime is unacceptable; quorum sized correctly.
  6. Connection pooling on the client; maxclients headroom on the server.
  7. Monitoring on the metrics table above with alerts, not just dashboards.
  8. A backup schedule that copies data off the box, and at least one tested restore.

When Redis Alone Is Not Enough

A few places where the honest answer is “use something else”:

  • Durable primary storage. Redis can be a primary store with careful AOF, but if you need ACID, queries, and schemas, that’s a database’s job — Redis is a cache or a fast auxiliary store.
  • Very large datasets. If your dataset exceeds RAM on any reasonable node, a disk-backed store (PostgreSQL, a search engine, a columnar DB) will beat a sharded Redis fleet on cost and sanity. If sharding is genuinely the answer, the database sharding guide covers the mechanics beyond Redis.
  • Complex querying. Redis has no query planner. If you need ad-hoc joins, aggregations, or full-text search over the same data, keep it in a real database and cache the results.

See Also

Frequently Asked Questions

Should I use RDB or AOF persistence?

Use AOF (appendfsync everysec) when losing more than a second of writes is unacceptable — sessions, write-behind queues, anything Redis holds alone. Use RDB for a pure cache that rebuilds from the database, where a snapshot for fast restarts and off-site backups is enough. Many production systems run both: AOF for durability, RDB for fast recovery and backups.

When should I use Redis Cluster vs Sentinel?

Use Sentinel when one node can hold your data but downtime is unacceptable — it gives you automatic failover without sharding complexity. Use Cluster when you have outgrown a single node's memory or throughput and can live with hash-slot restrictions on multi-key operations. Start with Sentinel; most deployments never need Cluster.

How do I choose an eviction policy?

For a dedicated cache instance, allkeys-lru is the right default — recently used data is what you want to keep. Use volatile-lru only when the same Redis holds both cache and persistent data (though a separate instance is usually cleaner). noeviction when Redis is a store and a dropped key would be data loss — then watch memory carefully because writes fail when it fills.

What causes high memory fragmentation?

The allocator leaves gaps when keys are allocated and freed unevenly — mem_fragmentation_ratio above ~1.5 means you're wasting real RAM. activedefrag yes can compact in the background on modern Redis; otherwise a rolling restart of replicas (failover, restart, fail back) clears it without downtime.

How do I handle Redis failover in my application?

Let Sentinel or Cluster do the promotion; your job is making the client follow it. Use a cluster-aware or Sentinel-aware client (not a hardcoded host), retry on connection errors, and handle the read-only window while the new master promotes. Writes during failover may be rejected — have the app retry rather than crash.

How can I reduce Redis memory usage?

Audit what you're storing first — the biggest wins are usually removing keys that shouldn't be there. Then: set TTLs on everything cacheable, use Redis hashes for objects with many fields, keep values small (JSON for readability, MessagePack when memory matters), and avoid storing large blobs — put the payload in object storage and cache a reference. Only then reach for allkeys-lfu or more RAM.

Is it safe to run KEYS in production?

No — KEYS blocks the single-threaded event loop while it scans every key, which on a busy instance is an outage you scheduled yourself. Use SCAN (or scan_iter in redis-py) for incremental, non-blocking iteration, and disable KEYS outright with rename-command on production instances.