Redis: Data Structures, Commands & Patterns
"All the commands in a transaction are serialized and executed sequentially. A request sent by another client will never be served in the middle of the execution of a Redis Transaction." — Redis documentation, Transactions
Summary: Redis is an in-memory data structure server that runs every command one at a time on one main thread; that single fact explains its speed, its atomicity and almost every production incident it causes. Focus: The execution model and latency sources, every data type with its cost, expiration, eviction and memory encodings, RDB/AOF persistence, replication, Sentinel and Cluster, transactions, Lua and Functions, pipelining, client-side caching, the classic patterns, security, licensing and the Valkey fork, with go-redis and Laravel code. Learning goal: Pick the right structure and command for a job, predict its latency and memory cost, choose persistence and topology on purpose, and implement cache, rate limit, lock, leaderboard and session patterns that survive concurrency and failover.
This page is the complete reference for Redis as a database and cache. It covers the execution model (event loop, I/O threads, background threads and fork), every data type a practitioner meets (String, Hash, List, Set, Sorted Set, Bitmap, HyperLogLog, Geo, the Redis 8 types JSON, time series, probabilistic structures and vector sets, with a pointer to Streams), expiration and eviction, memory encodings, persistence, replication, Sentinel, Cluster, transactions and scripting, pipelining and client-side caching, keyspace design, big and hot keys, the patterns teams actually build, security, Redis versus Memcached, Valkey, Dragonfly and KeyDB, and the 2024–2025 licence changes. It deliberately leaves three neighbours to their own pages: Streams and Pub/Sub as a message broker are in Redis Streams & Pub/Sub; how Laravel's queue driver uses Redis lists and sorted sets is in Laravel Queue Internals; and the theory of Bloom filters and HyperLogLog is in Bloom Filters & Probabilistic Structures. For where Redis sits among key-value, document, column and graph stores see NoSQL: Families & Data Models; for slot-based sharding versus rings see Consistent Hashing; and for a dense command list see the Redis Cheatsheet.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why Redis exists, the trade-off, the analogy | Why Redis exists |
| Event loop, I/O threads, fork, latency sources | The execution model |
| Every data type with commands and complexity | Data structures, one by one |
| EXPIRE, eviction policies, encodings, jemalloc | Keys, expiration, eviction and memory |
| RDB, AOF, fsync, hybrid, replication, Sentinel, Cluster | Mechanics |
| MULTI/EXEC/WATCH, Lua, Functions, pipelining, client-side caching | Atomicity and round trips |
| Error replies you will catch | Error replies |
| Cache-aside, rate limiter, lock, leaderboard, session, queue, big/hot keys | Solving the classic problems |
| ACL, TLS, protected mode | Security |
| Memcached, Valkey, Dragonfly, KeyDB, licences | Redis and its alternatives |
| go-redis, phpredis vs predis, Laravel facades | Go and Laravel |
| Which feature for which job | Choosing |
| Monolith to multi-region | In architecture |
| Reproduce it in Docker | Lab |
| Wrong beliefs, a cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The data types. Costs are the documented complexities; N is the number of elements in the key, M the number returned.
| Type | Use it for | Key commands | Cost |
|---|---|---|---|
| String | counters, cached blobs, flags, locks | SET/GET, INCR, SET ... NX PX, GETEX | O(1) |
| Bitmap (a String) | daily-active flags, feature bits | SETBIT, BITCOUNT, BITOP, BITFIELD | O(1) per bit, BITCOUNT/BITOP O(N) |
| Hash | an object with fields (user:42) | HSET, HGET, HINCRBY, HEXPIRE, HGETALL | O(1) per field, HGETALL O(N) |
| List | simple queues, recent items | LPUSH, RPOP, BLMOVE, LRANGE | O(1) at the ends, LRANGE O(S+N) |
| Set | membership, tags, unique visitors | SADD, SISMEMBER, SINTER, SINTERCARD | O(1) per element, SINTER O(N×M) worst |
| Sorted Set | leaderboards, schedules, sliding windows | ZADD, ZINCRBY, ZRANGE ... BYSCORE, ZRANK | O(log N), range O(log N + M) |
| HyperLogLog | approximate distinct counts in 12 KB | PFADD, PFCOUNT, PFMERGE | O(1) |
| Geo (a Sorted Set) | "within 5 km of me" | GEOADD, GEOSEARCH | O(log N + M) |
| Stream | durable log with consumer groups | XADD, XREADGROUP, XACK | O(1) append; see Streams |
| JSON, time series, Bloom/Cuckoo/CMS/Top-K/t-digest, vector set | documents, metrics, sketches, similarity | JSON.SET, TS.ADD, BF.ADD, VADD/VSIM | per type; built into Redis 8 |
Durability and availability knobs.
| Knob | What you get | What you can still lose |
|---|---|---|
| No persistence | Pure cache, fastest restart to empty | Everything on restart |
RDB save points | Compact snapshots, fast restart | Minutes of writes since the last snapshot |
AOF appendfsync everysec (default when AOF is on) | Log replay on restart | About one second of writes |
AOF appendfsync always | fsync per write batch | Almost nothing, at a large throughput cost |
| Replica + Sentinel | Automatic failover | Writes not yet replicated when the master died (replication is asynchronous) |
| Redis Cluster | Sharding over 16384 slots + failover | Same asynchronous window, per shard |
WAIT n | n replicas acknowledged this write | Still not strong consistency; a failover can lose it |
The five things to remember.
| Situation | Do this |
|---|---|
| Read-modify-write on one key | One command (INCR, HINCRBY, SET ... NX, GETDEL) |
| Read, decide, write across keys | A Lua script or Function; WATCH + MULTI/EXEC with retry |
| Walking keys in production | SCAN with MATCH/COUNT, never KEYS |
| Deleting a large key | UNLINK (background free), never a blocking DEL of millions of elements |
| A cache | maxmemory + allkeys-lru or allkeys-lfu, TTL with jitter, and code that survives an empty Redis |
Why Redis exists
A relational database keeps data on disk, plans each query, takes locks and writes a WAL so that every commit survives a crash. That is the right default for the system of record and far too much work for a session lookup, a page-view counter or "the top 10 players right now". Redis takes the opposite position: all data lives in RAM, the server owns rich structures (lists, sets, sorted sets) and exposes operations on them, and commands run one after another so they never need locks. The data types page opens with the claim: "Redis is a data structure server." A client sends ZINCRBY leaderboard 10 alice instead of downloading a blob, editing it and uploading it again.
| Disk-first relational database (PostgreSQL, MySQL InnoDB) | Redis |
|---|---|
| Data on disk, cached in a buffer pool | All data in RAM; disk only for persistence |
| SQL, planner, indexes on any column | Commands on one key's structure; you design the access path |
| Concurrent transactions with locks/MVCC and isolation levels | One command at a time on one thread; atomic by construction |
| Durable commit by default | Durability is opt-in (RDB, AOF, fsync policy) |
| Scales reads with replicas, writes with sharding projects | Replicas, Sentinel, built-in Cluster with hash slots |
| Microseconds to milliseconds per query | Sub-millisecond per command, if commands stay cheap |
The analogy we reuse on this page: a bakery with one till. Customers queue and the cashier serves exactly one at a time: rings up, takes payment, hands over change, next. Nobody can slip a coin in the middle of someone else's sale, so the till is always right without locks (atomic commands). It works because each sale takes seconds. If one customer starts counting out a thousand coins (KEYS *, DEL of a 10-million-element set), the whole queue stands still. Extra helpers can open the doors and bag the bread (I/O threads), but only the cashier touches the till. A second shop across town with a copy of the till roll is a replica; a chain of shops, each responsible for some product codes, is a cluster.
Three common misunderstandings, up front
- "Redis is single-threaded, so everything I do is safe." Each command is atomic; a sequence of commands from one client is not.
GETthenSETfrom two clients interleaves exactly like an unprotected read-modify-write in SQL. Use one command, a script, orWATCH. - "Redis is a cache, so durability does not matter" / "Redis is durable, so it can be my only database." Both are configuration choices. With no persistence a restart empties it; with
appendfsync everysecyou can still lose about a second; with replication a failover can drop acknowledged writes. - "Redis is fast, so any command is fast."
GETis O(1).SMEMBERSon a million-member set,HGETALLon a huge hash,LRANGE 0 -1,KEYS *or a long Lua script are O(N) and block every other client for their duration.
Where it comes from
Salvatore Sanfilippo (antirez) started Redis in 2009 and released it under the three-clause BSD licence. Redis 2.6 added Lua scripting, 2.8 added SCAN and partial resynchronisation for replicas, 3.0 shipped Redis Cluster, 4.0 added modules and UNLINK, 5.0 added Streams, 6.0 added ACLs, TLS, RESP3, client-side caching and threaded I/O, 7.0 added Functions, multi-part AOF and listpack encodings, 7.4 added hash-field expiration, and Redis 8 folded the former Redis Stack modules (JSON, time series, probabilistic types, the query engine) and the new vector set type into the core. The licence story (BSD → RSALv2/SSPLv1 in March 2024 → AGPLv3 added with Redis 8 in May 2025, and the Linux Foundation's BSD fork Valkey) is in Licences and forks.
Everything below is checked against the Redis documentation at redis.io/docs/latest and the redis.conf shipped with the source; where a feature depends on a version, the page says so.
The execution model
The main thread runs the event loop and executes every command; I/O threads (optional) only read, parse and write sockets; background threads fsync and free memory; a forked child writes snapshots.
Single-threaded command execution and the event loop Must-know
In plain words: one thread runs every command, start to finish, one after another. That is why INCR needs no lock, and why one slow command makes everybody wait.
Common misunderstanding: "Redis 6 added threads, so it is multi-threaded now." Threaded I/O moves socket reads, protocol parsing and reply writes to helper threads; command execution still happens on the main thread. The latency guide says it plainly: Redis "serves all the requests using a single thread".
Definition: Redis uses I/O multiplexing (epoll on Linux, kqueue on BSD/macOS) in an event loop. Each loop iteration collects ready sockets, executes complete commands from client buffers in order, queues replies, and runs time events (serverCron, hz 10 by default) that handle active expiration, eviction, statistics and rehashing. The latency guide: "Redis uses a mostly single threaded design. This means that a single process serves all the client requests, using a technique called multiplexing."
client A main thread client B
1 INCR views ─────────────▶ run INCR views (read 41, write 42)
2 reply 42 ─────────────▶ A
3 run INCR views (read 42, write 43) ◀───────── INCR views
4 reply 43 ─────────────────────────────────────▶ B
-- never 42 twice: the two INCRs cannot interleave
5 KEYS * ─────────────▶ scan 20 M keys ... 4 seconds
6 (B's GET waits in its socket buffer) ◀──────── GET session:9
7 reply to A, then finally GET for B: 4 s latencyReal scenarios: a rate limiter that uses INCR is race-free under any concurrency; a nightly admin script running KEYS user:* freezes checkout for seconds; a Lua script that loops over 100k elements triggers BUSY replies for everyone else; FLUSHALL on a large instance without ASYNC stalls all clients.
Threads that do exist:
| Thread / process | Does | Knob |
|---|---|---|
| Main thread | Event loop, every command, expiration, eviction | hz, dynamic-hz |
| I/O threads | Socket read(2)/write(2) and RESP parsing | io-threads (default 1 = off), io-threads-client-types (source redis.conf) |
| Background (bio) threads | AOF fsync, closing files, lazy freeing | lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del |
| Forked child | BGSAVE (RDB), BGREWRITEAOF, full-sync snapshot for replicas | save, auto-aof-rewrite-percentage |
How to use it: keep every command cheap (check the complexity on each command's page), break big work into small steps (SCAN, HSCAN, SSCAN, ZSCAN, batched UNLINK), and move heavy reads to a replica. The latency guide's advice: "you should either not use slow commands against values composed of many elements, or you should run a replica using Redis replication where you run all your slow queries."
I/O threads Important
In plain words: extra threads that copy bytes between the network and Redis, so the main thread spends its time running commands instead of doing system calls.
Common misunderstanding: "Turn on io-threads and a slow Lua script gets faster." It does nothing for command execution; it helps only when the server is CPU-bound on network I/O with many clients and small commands.
Definition: io-threads N (N greater than 1) starts N−1 helper threads. The current redis.conf explains that with I/O threads "we not only use threads for writes, that is to thread the write(2) syscall and transfer the client buffers to the socket, but also use threads for reads and protocol parsing." It recommends enabling it "only in machines that have at least 4 or more cores, leaving at least one spare core", for example 3 threads on a 4-core box. Older releases split reads behind a separate io-threads-do-reads switch; the current file has no such option. Benchmark with redis-benchmark --threads or the client becomes the bottleneck.
| Product | Threading model for commands |
|---|---|
| Redis | One main thread executes commands; optional I/O threads |
| Valkey | Same execution model (forked from Redis 7.2.4); its launch roadmap lists multi-threaded performance improvements |
| KeyDB | "A Multithreaded Fork of Redis": several threads run commands under a lock |
| Dragonfly | Shared-nothing, one shard per thread, multi-key operations coordinated across shards |
| Memcached | "multithreaded event-based key/value cache"; simple get/set, no structures |
Latency sources Must-know
In plain words: when Redis is "slow", it is almost never the hash table. It is one of five things: a slow command, a big key, a fork for persistence, swapping, or the network/VM itself.
Common misunderstanding: "Average latency is 0.2 ms, so Redis is fine." The averages hide p99.9 stalls of hundreds of milliseconds during BGSAVE forks or a single DEL of a huge key.
Definition, cause by cause (from the latency diagnosis guide):
| Source | What happens | How you see it | Fix |
|---|---|---|---|
| Slow commands | O(N) command on a large value blocks the loop | SLOWLOG GET, high CPU with low traffic | Avoid O(N) on big values; SCAN family; replica for heavy reads |
| Big keys | One key with millions of elements; DEL, HGETALL, migration and expiry of it all block | redis-cli --bigkeys, --memkeys, MEMORY USAGE | Split the key, UNLINK, lazyfree-lazy-* |
fork() for RDB/AOF rewrite | Copying page tables runs on the main thread; the guide measured 6.1 GB forked in 1460 ms on old Xen EC2 | INFO stats latest_fork_usec | Smaller instances, modern VMs, fewer save points, persist on a replica |
| Transparent huge pages | After fork, copy-on-write of 2 MB pages copies nearly the whole memory | Latency and memory spike after BGSAVE | echo never > /sys/kernel/mm/transparent_hugepage/enabled |
| Swap | A swapped-out page stalls the process on disk I/O | /proc/<pid>/smaps Swap: lines | Enough RAM, maxmemory, no other memory hogs |
| AOF fsync and disk I/O | appendfsync always or a slow disk blocks writes | INFO persistence, aof_delayed_fsync | everysec, faster disk, no-appendfsync-on-rewrite |
| Mass expiry | Many keys expiring in the same second | Latency spikes at round times | TTL jitter |
| Network / VM | Intrinsic latency of the host | redis-cli --intrinsic-latency 100 (run on the server) | Better host; pipelining to hide RTT |
Tools: SLOWLOG GET 10 (threshold slowlog-log-slower-than, default 10000 µs), LATENCY DOCTOR and LATENCY HISTORY once latency-monitor-threshold is above 0 (default 0 = off), redis-cli --latency, --latency-history, INFO commandstats.
main thread clients
1 BGSAVE triggered by "save 60 10000"
2 fork(): copy page tables of 24 GB ... 300 ms every client waits
3 child writes dump.rdb; parent serves again
4 parent writes to many pages -> copy-on-write duplicates them (memory grows)
5 with THP on: 2 MB pages copied instead of 4 KB -> RSS nearly doubles, latency spikesData structures, one by one
Each block gives plain words, the usual wrong belief, the definition with costs, a short sequence, scenarios and the commands. Redis 8 ships the former Redis Stack types in the core; on Redis 7.x they need Redis Stack or modules, and Valkey offers some through its own modules.
String, counters and Bitmaps Must-know
In plain words: a key that holds bytes, up to 512 MB. It can be text, a serialised object, an integer you INCR, or an array of bits.
Common misunderstanding: "Store the whole user object as one JSON String and update fields with GET + SET." That is a lost update waiting to happen and rewrites the whole value for one field; use a Hash or JSON.SET on a path.
Definition: binary-safe strings. Integers are stored compactly (OBJECT ENCODING reports int), short strings as embstr (up to 44 bytes, allocated with the object), longer as raw. INCR/INCRBY/INCRBYFLOAT/DECR are atomic read-modify-write. SET takes NX/XX, EX/PX/EXAT/PXAT, KEEPTTL, GET. GETEX reads and changes the TTL; GETDEL reads and deletes. Bitmaps are Strings addressed by bit: SETBIT/GETBIT O(1), BITCOUNT, BITPOS, BITOP AND/OR/XOR/NOT O(N), BITFIELD for packed integer arrays.
client A client B
1 SET stock:42 1
2 DECR stock:42 -> 0 DECR stock:42 -> -1 (atomic, but no floor)
-- fix: a script "if GET > 0 then DECR", or keep the stock in SQL with UPDATE ... WHERE stock > 0Real scenarios: page-view and API-usage counters; idempotency flags (SET idem:<id> 1 NX EX 86400); feature flags; daily-active users with one bit per user id (SETBIT dau:2026-11-25 <uid> 1, then BITCOUNT and BITOP AND for retention); cached HTML fragments.
Hash Must-know
In plain words: a small map inside one key: user:42 → {name, email, plan}. Read or change one field without touching the others.
Common misunderstanding: "HGETALL is cheap because it is one command." It is O(N) in the number of fields; on a hash with 500k fields it blocks like KEYS.
Definition: field → value map. HSET, HGET, HMGET, HINCRBY, HDEL, HEXISTS are O(1) per field; HGETALL, HKEYS, HVALS are O(N); iterate big hashes with HSCAN. Since Redis 7.4, fields can have their own TTL (HEXPIRE, HPEXPIRE, HTTL, HPERSIST), and Redis 8 adds HGETEX/HSETEX/HGETDEL. Small hashes (≤ hash-max-listpack-entries 512 fields, each ≤ hash-max-listpack-value 64 bytes) are stored as a compact listpack, which the memory guide says uses "up to 10 times less memory".
Real scenarios: user profiles and session data; shopping carts (HINCRBY cart:{u1} sku-7 1); per-tenant counters; the "hash bucketing" trick from the memory guide that stores many tiny values inside small hashes to save memory.
List Important
In plain words: a double-ended queue of strings. Push and pop at either end in O(1).
Common misunderstanding: "A list is an array, so LINDEX 500000 is instant." Access by index or LRANGE in the middle is O(N); lists are fast only at the ends.
Definition: a quicklist (a linked list of listpack nodes; small lists are a single listpack). LPUSH/RPUSH/LPOP/RPOP O(1); LRANGE O(S+N); LTRIM keeps a capped list; blocking BLPOP/BRPOP/BLMOVE/BLMPOP wait for data; LMOVE/BLMOVE atomically move an element to a processing list, the "reliable queue" pattern.
producer worker
1 LPUSH jobs j1
2 BLMOVE jobs processing RIGHT LEFT 5 -> j1 (moved atomically)
3 ... worker crashes ...
4 reaper: LRANGE processing 0 -1 -> j1 still there -> LMOVE back to jobsReal scenarios: "last 100 notifications" with LPUSH + LTRIM 0 99; simple work queues (Laravel's Redis queue driver uses lists plus sorted sets; see Laravel Queue Internals); activity feeds. For durable queues with consumer groups and acknowledgements use Streams: Redis Streams & Pub/Sub.
Set Important
In plain words: an unordered bag of unique strings, with fast "is X in it?" and set algebra.
Common misunderstanding: "SINTER of two sets is O(1) like SISMEMBER." It is O(N×M) in the worst case (N = smallest set, M = number of sets); intersecting two 10-million-member sets blocks the server. SINTERCARD key ... LIMIT n stops early when you only need a count.
Definition: SADD, SREM, SISMEMBER, SMISMEMBER O(1) per member; SCARD O(1); SMEMBERS O(N); SINTER/SUNION/SDIFF and their STORE forms; SRANDMEMBER, SPOP for sampling. Small all-integer sets use the intset encoding (≤ set-max-intset-entries 512), small mixed sets a listpack (Redis 7.2+).
Real scenarios: tags and permissions (SISMEMBER role:admin:users 42); deduplicating events within a window; "friends in common" with SINTER; exact unique visitors when the set is small (use HyperLogLog when it is not).
Sorted Set Must-know
In plain words: a set where every member has a score, kept in score order. Ranks, top-N and score ranges are cheap.
Common misunderstanding: "Use a Sorted Set as a general index and ZRANGE 0 -1 it." Range reads are O(log N + M); returning a million members is still a million-element reply.
Definition: a hash table (member → score) plus a skiplist (ordered by score, then member) for large sets; a listpack when small (≤ zset-max-listpack-entries 128). ZADD (with NX/XX/GT/LT/INCR) and ZINCRBY O(log N); ZRANK/ZREVRANK O(log N); ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT] [WITHSCORES] (the unified form since 6.2) O(log N + M); ZREMRANGEBYSCORE; ZPOPMIN/BZPOPMIN; ZRANGESTORE, ZINTERCARD.
game server A game server B
1 ZINCRBY lb:week 50 alice -> 1050
2 ZINCRBY lb:week 30 alice -> 1080 (atomic, no lost update)
3 ZRANGE lb:week 0 9 REV WITHSCORES -> top 10 in O(log N + 10)
4 ZREVRANK lb:week alice -> 3 (0-based rank)Real scenarios: leaderboards; delayed jobs scored by run-at time (poll with ZRANGE ... BYSCORE -inf now LIMIT 0 100); sliding-window rate limiting with timestamps as scores; priority queues; time-ordered indexes of ids.
HyperLogLog Important
In plain words: counts distinct things approximately (standard error 0.81%) using at most 12 KB, no matter whether you add a thousand or a billion items.
Common misunderstanding: "I can ask a HyperLogLog whether user 42 was counted." You cannot list or test members; it only estimates cardinality.
Definition: PFADD key el... and PFCOUNT key... (O(1) per key; counting several keys merges on the fly), PFMERGE dest src.... Sparse encoding for small counts, dense 12 KB register array otherwise. Theory: Bloom Filters & Probabilistic Structures.
Real scenarios: unique visitors per page per day; distinct search queries; distinct IPs per API key; merging daily HLLs into a weekly figure with PFMERGE.
Geo Good to know
In plain words: store longitude/latitude per member and ask "who is within 3 km of here?".
Common misunderstanding: "Geo is a separate index type." It is a Sorted Set whose scores are 52-bit geohashes; ZREM removes a member and TYPE says zset.
Definition: GEOADD key lon lat member, GEOSEARCH key FROMLONLAT lon lat BYRADIUS 3 km ASC COUNT 20 WITHDIST (replaces the deprecated GEORADIUS), GEODIST, GEOPOS, GEOHASH. O(log N + M) plus the area scanned.
Real scenarios: nearest drivers or stores; geofenced notifications; "restaurants open near me" combined with a Set of open restaurant ids.
Redis 8 types: JSON, time series, probabilistic, vector sets Good to know
In plain words: the extra types that used to need Redis Stack are part of Redis 8: JSON documents, time series, Bloom-style sketches, and vector similarity sets.
Common misunderstanding: "Any Redis-compatible service has them." Managed services and forks differ: Valkey ships JSON and Bloom as separate modules, ElastiCache and Memorystore versions vary, and Redis 7.2 without Stack has none of them. Check COMMAND INFO JSON.SET before you design around one.
| Type | Commands | Use | Notes |
|---|---|---|---|
| JSON | JSON.SET key $.path value, JSON.GET, JSON.NUMINCRBY, JSON.ARRAPPEND | Documents updated by path, atomic per command | Indexable by the Redis Query Engine (FT.CREATE ... ON JSON) |
| Time series | TS.CREATE (retention, duplicate policy), TS.ADD, TS.RANGE with aggregation, TS.CREATERULE | Metrics, IoT samples, downsampling | Compaction rules write to other keys |
| Bloom filter | BF.RESERVE key error_rate capacity, BF.ADD, BF.EXISTS | "Have we seen this?" with false positives, no false negatives | No delete |
| Cuckoo filter | CF.ADD, CF.EXISTS, CF.DEL | Like Bloom, but supports delete | Can fail to insert when full |
| Count-min sketch | CMS.INITBYPROB, CMS.INCRBY, CMS.QUERY | Approximate frequency per item | Overestimates, never underestimates |
| Top-K | TOPK.RESERVE, TOPK.ADD, TOPK.LIST | Heavy hitters (hot keys, top URLs) | Approximate |
| t-digest | TDIGEST.CREATE, TDIGEST.ADD, TDIGEST.QUANTILE | p50/p99 latency from a stream of samples | Accurate at the tails |
| Vector set | VADD key VALUES n v1 ... element, VSIM key VALUES ... COUNT k, VSIM ... FILTER '.year > 1950' | Similarity search for embeddings | HNSW graph; attributes via VSETATTR; see Vector Search |
Streams (pointer) Good to know
A Stream is an append-only log of field-value entries with ids (XADD), range reads (XRANGE), and consumer groups with a pending-entries list (XREADGROUP, XACK, XAUTOCLAIM). The Pub/Sub page states that Pub/Sub "exhibits at-most-once message delivery semantics"; Streams are persisted and support at-least-once. Keyspace notifications (notify-keyspace-events, empty by default) publish key events such as expired or set on Pub/Sub channels (__keyevent@0__:expired), with the same at-most-once delivery, so never build billing on "key expired" events. Everything about Streams and Pub/Sub as a broker is on Redis Streams & Pub/Sub.
Keys, expiration, eviction and memory
Expiration: lazy and active Must-know
In plain words: a TTL makes a key disappear "at" a time, but Redis deletes it either when somebody touches it or when a background sweep happens to find it.
Common misunderstanding: "Memory drops the moment keys expire." Expired keys that nobody reads stay in memory until the active cycle samples them; with millions of keys expiring at once, memory and latency both move.
Definition: the EXPIRE page: "Redis keys are expired in two ways: a passive way and an active way. A key is passively expired when a client tries to access it and the key is timed out." Actively, "periodically, Redis tests a few keys at random amongst the set of keys with an expiration." redis.conf adds that the default effort "will try to avoid having more than ten percent of expired keys still in memory"; active-expire-effort (1–10) trades CPU for fewer lingering keys. On a replica, keys are not expired independently: the master synthesises a DEL into the AOF and the replication stream. Commands: EXPIRE/PEXPIRE/EXPIREAT (with NX/XX/GT/LT since 7.0), TTL/PTTL (−1 no TTL, −2 missing), PERSIST, SET ... EX, GETEX, and hash-field HEXPIRE. A SET without KEEPTTL removes the TTL.
t event
1 10:00 SET session:9 ... EX 1800 ; 100k other sessions created in the same second
2 10:30 all 100k expire "now"; nobody reads them
3 10:30+ active expire samples keys with TTL each cycle, deletes the expired ones,
repeats while more than ~10% of the sample was expired -> CPU and latency bump
4 fix EX 1800 + random(0..120) -> expiries spread over two minutesReal scenarios: sessions, OTP codes (SET otp:<phone> 123456 EX 300 NX), rate-limit windows, cache entries, idempotency keys, locks.
Eviction policies Must-know
In plain words: when memory hits maxmemory, the policy decides whether Redis refuses writes or throws keys away, and which ones.
Common misunderstanding: "volatile-lru is safer than allkeys-lru." With volatile policies only keys that have a TTL can be evicted; the eviction page notes they behave like noeviction when no keys have an expiration, so a cache whose keys lack TTLs starts failing writes with OOM.
Definition: maxmemory bytes (0 = no limit on 64-bit) and maxmemory-policy:
| Policy | Evicts | When to use |
|---|---|---|
noeviction | Nothing; write commands return an OOM error, reads still work | Data you cannot lose: queues, locks, primary data |
allkeys-lru | Least recently used, any key | The documented good default for a cache: "allkeys-lru is a good default option if you have no reason to prefer any others." |
allkeys-lfu | Least frequently used (Redis 4.0+) | Skewed popularity where a burst of one-off reads should not push out hot keys |
allkeys-lrm | Least recently modified (Redis 8.6+) | Data that is read often but stale once not written |
allkeys-random | Random key | Uniform access |
volatile-lru / volatile-lfu / volatile-lrm / volatile-random | Same, only among keys with a TTL | Mixed instance: cache keys with TTL plus permanent keys without |
volatile-ttl | Keys with the shortest remaining TTL | The app encodes "cheap to lose" as a short TTL |
LRU, LFU and LRM are approximate: Redis samples maxmemory-samples keys (default 5) and evicts the best candidate from a pool. LFU uses a logarithmic counter (lfu-log-factor 10) that decays (lfu-decay-time 1 minute); OBJECT FREQ key shows it. Replication buffers are not counted toward eviction (mem_not_counted_for_evict in INFO memory), so leave headroom below the machine's RAM.
| Product | Default / behaviour at the limit |
|---|---|
| Redis open source | maxmemory 0 (unbounded on 64-bit), noeviction |
| AWS ElastiCache / Google Memorystore | Managed maxmemory; defaults differ per service and engine version, so check the parameter group |
| Memcached | LRU-style eviction per slab class by default; the -M option returns errors instead of evicting |
| Valkey | Same policy names as Redis 7.2 |
Memory: jemalloc, encodings, OBJECT ENCODING Important
In plain words: Redis stores small collections in a packed format that uses much less memory, switches to a normal format past a size limit, and gets its memory from jemalloc, which does not always give freed memory back to the OS.
Common misunderstanding: "I deleted 2 GB of keys, so RSS should drop by 2 GB." The memory guide: "Redis will not always free up (return) memory to the OS when keys are removed"; RSS stays near the peak and the allocator reuses the freed chunks. Provision for peak memory.
Definition:
| Type | Compact encoding (when small) | Normal encoding | Thresholds (redis.conf) |
|---|---|---|---|
| String | int, embstr (≤ 44 bytes) | raw | fixed |
| Hash | listpack (7.0+; ziplist before) | hashtable | hash-max-listpack-entries 512, hash-max-listpack-value 64 |
| List | listpack | quicklist (linked listpacks) | list-max-listpack-size -2 (8 KB per node) |
| Set | intset (integers), listpack (7.2+) | hashtable | set-max-intset-entries 512, set-max-listpack-entries 128 |
| Sorted Set | listpack | skiplist + hash table | zset-max-listpack-entries 128, zset-max-listpack-value 64 |
| Stream | radix tree of listpacks | same | stream-node-max-bytes, stream-node-max-entries |
Conversion is one-way while the key exists: once a hash grows past 512 fields it stays a hashtable even if it shrinks. Inspect with OBJECT ENCODING key, MEMORY USAGE key [SAMPLES n], MEMORY STATS, MEMORY DOCTOR, INFO memory (used_memory, used_memory_rss, mem_fragmentation_ratio). Fragmentation ratio = RSS / used memory; above ~1.5 after a big delete, turn on active defragmentation (CONFIG SET activedefrag yes, works with the bundled jemalloc, the Linux default); below 1 means swapping. Deleting is itself work: DEL frees a big value on the main thread, UNLINK (4.0+) unlinks the key and frees it in a background thread; FLUSHALL ASYNC does the same for everything; lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-server-del, lazyfree-lazy-user-del make the implicit deletes lazy.
redis-cli
1 HSET small f1 v1 ; OBJECT ENCODING small -> "listpack"
2 (add 600 fields) ; OBJECT ENCODING small -> "hashtable"
3 MEMORY USAGE small -> grows several times for the same data
4 HDEL 590 fields ; OBJECT ENCODING small -> still "hashtable"Keyspace design, SCAN vs KEYS Must-know
In plain words: name keys like paths (app:entity:id:field), never list them with KEYS, and walk them with SCAN when you must.
Common misunderstanding: "SCAN gives me a consistent snapshot of the keys." It gives limited guarantees: a key present for the whole iteration is returned at least once, but it may be returned several times, keys added or removed during the walk may or may not appear, and a call may return zero keys while the cursor is not yet 0.
Definition: KEYS pattern is O(N) over the whole keyspace and, per the latency guide, "should only be used for debugging purposes". SCAN cursor [MATCH p] [COUNT n] [TYPE t] returns a new cursor and a batch; COUNT is "just a hint" for work per call; iteration ends when the cursor returns to 0. HSCAN, SSCAN, ZSCAN do the same inside one key. In Cluster, SCAN runs per node: iterate every master.
Key design rules:
| Rule | Example | Why |
|---|---|---|
| Prefix per app/tenant | shop:user:42 | Shared instances, ACL key patterns (~shop:*), easy SCAN MATCH |
| Colon-separated hierarchy | order:9001:items | Convention tools understand |
| Hash tag for keys used together in Cluster | cart:{u42}, cart-skus:{u42} | Same slot, so MULTI, Lua and multi-key commands work |
| Short but readable | u:42:p only for billions of keys | Key names cost memory per key |
| TTL on everything that is a cache | SET ... EX | Bounded memory, works with volatile policies |
| Version in the key for cache schema changes | v3:product:42 | Deploys do not read old shapes |
Use SELECT databases sparingly | db 0 only in Cluster | Cluster supports only database 0 |
Big keys and hot keys Must-know
In plain words: a big key is one key holding too much (a 2 GB string, a 10-million-member set); a hot key is one key that gets a huge share of all traffic. Both break the "every command is cheap and load spreads" assumption.
Common misunderstanding: "Cluster will spread the load." A key lives in exactly one slot on one master; Cluster can never split a single hot or big key.
Definition and symptoms:
| Problem | Symptoms | Find it | Fix |
|---|---|---|---|
| Big key | Slow DEL/expiry/migration, reply buffers bloat, MIGRATE timeouts during resharding, uneven shard memory | redis-cli --bigkeys, --memkeys, MEMORY USAGE, SLOWLOG | Split by id range or hash (followers:42:0..15), cap lists with LTRIM, UNLINK, page with *SCAN |
| Hot key | One shard at 100% CPU while others idle, network saturation on one node | redis-cli --hotkeys (needs an LFU policy), MONITOR sampling (costly), client metrics, Top-K | Client-side caching, local in-process cache with short TTL, replicate the key (hot:{0..7} copies, read a random one), shard counters (views:42:{0..15} summed on read), read from replicas |
before after (sharded counter)
1 INCR views:home (200k ops/s, one node) INCR views:home:{rand 0..15} (16 keys, spread over slots)
2 read: MGET is cross-slot -> pipeline 16 GETs and sumMechanics
How Redis keeps data across restarts and machines: persistence, replication, Sentinel and Cluster.
Persistence: RDB, AOF, fsync and hybrid Must-know
RDB loses everything since the last snapshot; AOF with everysec loses about a second; the rewrite produces an RDB-format base plus incremental AOF files tracked by a manifest.
In plain words: RDB is a periodic photo of the whole dataset; AOF is a diary of every write. Use both if you care about the data, neither if Redis is a pure cache.
Common misunderstanding: "AOF with everysec means no data loss." It means "you may lose 1 second of data if there is a disaster", in the persistence page's words, and a failover to an asynchronous replica can lose more.
Definition: RDB "performs point-in-time snapshots of your dataset at specified intervals": BGSAVE forks, the child writes dump.rdb from a copy-on-write view while the parent keeps serving. Default save points (current redis.conf): after 3600 s if ≥1 change, 300 s if ≥100, 60 s if ≥10000 (save 3600 1 300 100 60 10000; save "" disables). SAVE does it on the main thread (blocks). If a background save fails and stop-writes-on-bgsave-error yes, writes get a MISCONF error. AOF "logs every write operation received by the server" in RESP format; appendfsync always (fsync per event loop write batch, "very very slow, very safe"), everysec (default), or no (OS flushes, "every 30 seconds" on Linux by default tuning). The AOF grows, so BGREWRITEAOF (automatic via auto-aof-rewrite-percentage 100, auto-aof-rewrite-min-size 64mb) rewrites it from memory. Since 7.0 the AOF is multi-part: a base file, incremental files and a manifest in appenddirname "appendonlydir". With aof-use-rdb-preamble yes (default) the base is in RDB format: that is the hybrid mode, fast to load like RDB, fine-grained like AOF. The persistence page discourages AOF alone ("we discourage it") and recommends both for safety.
| Setting | Restart time | Data loss window | Cost |
|---|---|---|---|
| None | Instant, empty | All | None |
| RDB only | Fast | Minutes | Fork per snapshot |
AOF everysec + RDB preamble | Fast-ish | ~1 s | Disk writes, periodic rewrite fork |
AOF always | Fast-ish | ~0 on that node | Throughput drops to disk fsync speed |
Real scenarios: a session store that tolerates a second of loss (everysec); a cache with persistence off on the master and RDB on a replica to keep forks off the hot node; hourly RDB files copied to object storage for backups (the persistence page suggests archiving them).
Replication: asynchronous, PSYNC, WAIT Must-know
In plain words: replicas receive a copy of every write after the master has already answered the client; if the master dies before sending it, that write is gone.
Common misunderstanding: "WAIT 1 0 makes the write durable." The replication page: WAIT "does not turn a set of Redis instances into a CP system with strong consistency: acknowledged writes can still be lost during a failover".
Definition: REPLICAOF host port. Every master has a replication ID and an offset; a reconnecting replica sends PSYNC <replid> <offset>. If the gap is still in the master's replication backlog (repl-backlog-size, 1 MB default in the shipped file; raise it), it gets a partial resynchronisation; otherwise a full sync: an RDB (written to disk or streamed with repl-diskless-sync yes, the default) followed by the command stream. After a failover, the promoted replica keeps the old ID as a secondary ID so other replicas can still partially resync. Replicas are read-only by default (replica-read-only yes; writes return READONLY). min-replicas-to-write + min-replicas-max-lag make a master refuse writes when too few replicas are recent, limiting the loss window in a partition. replica-serve-stale-data no makes a disconnected replica answer MASTERDOWN. WAIT counts acknowledgements of the writes made on its own connection, so call it on the connection that wrote.
client master (offset) replica
1 SET a 1 ──▶ apply, offset 1001, reply OK ──▶ client
2 stream "SET a 1" ─────────────▶ (in flight)
3 master crashes before byte 1001 arrives
4 Sentinel promotes replica: a is missing
-- "OK" was returned for a write that no longer exists
5 with WAIT 1 100 after step 1: client learns 0 replicas acked -> can retry or alertReplica reads: cheap read scaling, but stale by the replication lag: read-your-writes breaks. go-redis ClusterOptions{ReadOnly: true} routes reads there; never do read-decide-write with the read on a replica. Background: Replication & Failover.
Sentinel Important
In plain words: a set of small watcher processes that notice the master is down, agree on it, promote a replica, and tell clients the new address.
Common misunderstanding: "Two Sentinels are enough." The docs: "You need at least three Sentinel instances for a robust deployment", on independent machines, because a failover needs a majority.
Definition: Sentinels listen on port 26379. sentinel monitor <name> <ip> <port> <quorum>: the quorum is how many Sentinels must agree the master is unreachable (subjectively down, SDOWN → objectively down, ODOWN); the actual failover needs one Sentinel elected leader by a majority of all Sentinels, so "no failover in the minority partition". Knobs: down-after-milliseconds, failover-timeout, parallel-syncs. Clients ask Sentinel SENTINEL get-master-addr-by-name mymaster (go-redis NewFailoverClient, phpredis/predis Sentinel options) instead of hard-coding the master.
S1, S2, S3 (quorum 2) master M replica R
1 S1: no PING reply from M for down-after-ms -> SDOWN
2 S2 agrees -> ODOWN (quorum 2 reached)
3 S1 asks for votes, gets majority (2 of 3) -> leader
4 S1: REPLICAOF NO ONE on R; reconfigures other replicas; publishes new address
5 clients re-resolve via Sentinel -> write to R; old M, when back, becomes a replicaRedis Cluster: slots, hash tags, MOVED/ASK, resharding Must-know
Every key maps to one of 16384 slots; each master owns ranges; a wrong-node request gets MOVED, a slot in migration gets ASK; hash tags keep related keys together.
In plain words: Cluster splits keys over several masters by a fixed hash; each master has replicas; clients learn which node owns which slot and go straight there.
Common misunderstanding: "Cluster is just bigger Redis; my multi-key commands still work." Multi-key commands, transactions and scripts work only when every key is in the same slot; otherwise the server replies CROSSSLOT. Only database 0 exists.
Definition: from the cluster specification: "The cluster's key space is split into 16384 slots", HASH_SLOT = CRC16(key) mod 16384. If a key contains {...} with at least one character inside, only that part is hashed (the hash tag), so user{1000}:profile and user{1000}:cart share a slot. Nodes talk over the cluster bus (data port + 10000) using gossip and detect failures with cluster-node-timeout (15000 ms in the shipped file); replicas of a failed master hold an election. A node that receives a key it does not own replies -MOVED 3999 127.0.0.1:6381; the client updates its slot map and retries. During resharding a slot is MIGRATING on the source and IMPORTING on the target; keys already moved get -ASK slot host:port, and the client sends ASKING then the command to the target, once, without updating its map. A command touching several keys of a slot under migration may get TRYAGAIN. If slots are uncovered and cluster-require-full-coverage yes, the cluster answers CLUSTERDOWN.
The spec is honest about writes:
"Acceptable degree of write safety: the system tries (in a best-effort way) to retain all the writes originating from clients connected with the majority of the master nodes. Usually there are small windows where acknowledged writes can be lost. Windows to lose acknowledged writes are larger when clients are in a minority partition." — Redis documentation, Redis cluster specification
client (stale slot map) node B :7001 node A :7000
1 GET user:1000 ─────────────▶ slot 3999 not mine
2 ◀─────────── -MOVED 3999 127.0.0.1:7000
3 GET user:1000 ───────────────────────────────────────────▶ value
-- resharding slot 3999 from A to C:
4 GET user:1000 ───────────────────────────────────────────▶ A: key already moved
5 ◀────────────────────────────────────────── -ASK 3999 C
6 ASKING ; GET user:1000 ──▶ C (importing) -> value; map still says A until MOVEDOperations: redis-cli --cluster create host:port ... --cluster-replicas 1, --cluster reshard, --cluster rebalance, --cluster add-node, --cluster del-node, --cluster check, --cluster fix; CLUSTER SHARDS/CLUSTER SLOTS, CLUSTER KEYSLOT key, CLUSTER COUNTKEYSINSLOT. Read from replicas with READONLY per connection.
| Multi-key feature | Standalone / Sentinel | Cluster |
|---|---|---|
MGET/MSET, SINTER, RENAME, SMOVE | Any keys | Same slot only (hash tags); clients may split MGET per slot |
MULTI/EXEC, WATCH | Any keys | Same slot only |
| Lua / Functions | Any declared keys | All KEYS in one slot |
SCAN, KEYS, FLUSHALL, DBSIZE | Whole instance | Per node; fan out to every master |
| Pub/Sub | Instance | Broadcast to all nodes; sharded Pub/Sub (SPUBLISH) per slot |
SELECT n | 16 databases by default | Database 0 only |
Comparison with other sharding schemes (rings, vnodes, jump hash) is on Consistent Hashing.
Atomicity and round trips
MULTI / EXEC / WATCH: transactions without rollback Must-know
In plain words: MULTI starts queuing, EXEC runs the queue as one uninterrupted block. Nobody else's command runs in the middle. But if a command inside fails at run time, the others still happen.
Common misunderstanding: "It is like BEGIN/COMMIT in SQL." The transactions page: "Redis does not support rollbacks"; you also cannot read a value inside the queue and branch on it, because every command returns QUEUED until EXEC.
Definition: MULTI, commands (replies QUEUED), then EXEC or DISCARD. Errors detected while queuing (wrong arity, unknown command) make EXEC fail with EXECABORT and discard everything. Errors at execution time (WRONGTYPE on one command) fail only that command. WATCH key... before MULTI gives optimistic check-and-set: if any watched key changes before EXEC, EXEC returns null and nothing runs; you retry. In SQL terms that is the version-column pattern from Optimistic vs Pessimistic Locking.
client A client B
1 WATCH balance:7
2 GET balance:7 -> 100
3 INCRBY balance:7 -30 -> 70
4 MULTI
5 DECRBY balance:7 50 -> QUEUED
6 EXEC -> (nil) watched key changed, nothing executed
7 retry from 1: GET -> 70, DECRBY 50 -> 20Go (go-redis): Watch plus TxPipelined, retried on redis.TxFailedErr.
func Withdraw(ctx context.Context, rdb *redis.Client, account string, amount int64) error {
key := "balance:" + account
for attempt := 0; attempt < 5; attempt++ {
err := rdb.Watch(ctx, func(tx *redis.Tx) error {
bal, err := tx.Get(ctx, key).Int64()
if err != nil && !errors.Is(err, redis.Nil) {
return err
}
if bal < amount {
return errors.New("insufficient funds")
}
_, err = tx.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.DecrBy(ctx, key, amount)
return nil
})
return err
}, key)
if errors.Is(err, redis.TxFailedErr) {
continue // someone touched the key between WATCH and EXEC
}
return err
}
return errors.New("too much contention")
}Laravel: Redis::transaction(fn ($redis) => ...) wraps MULTI/EXEC; the docs warn that inside it "you may not retrieve any values from the Redis connection". For read-decide-write use Redis::eval (next block).
Lua scripts and Functions Must-know
In plain words: send a small program that runs inside Redis, atomically, so "read, decide, write" happens with nobody in between.
Common misunderstanding: "Scripts are free because they save round trips." A script blocks the server while it runs; after busy-reply-threshold (5000 ms, formerly lua-time-limit) other clients get BUSY and you can only SCRIPT KILL (if it has not written) or SHUTDOWN NOSAVE.
Definition: EVAL script numkeys key... arg...; the eval page: "Redis guarantees the script's atomic execution." redis.call() raises errors to the client, redis.pcall() returns them to the script. SCRIPT LOAD caches a script by SHA1 and EVALSHA sha ... runs it; an unknown SHA returns NOSCRIPT No matching script, so clients fall back to EVAL (go-redis NewScript.Run does this). Always pass keys in KEYS[], never build key names inside the script, or Cluster routing and ACL checks break. Functions (Redis 7.0+) are named, persistent libraries: the payload starts with a shebang (#!lua name=mylib), is loaded with FUNCTION LOAD [REPLACE], is replicated and persisted with the dataset, and is called with FCALL name numkeys ... / FCALL_RO. Use Functions for logic that is part of your data model; use EVAL for app-owned one-offs.
client A client B
1 EVALSHA <limit.lua> 1 rate:u1 100 60
2 inside: ZREMRANGEBYSCORE, ZCARD -> 99, ZADD (B's EVALSHA waits in the queue)
3 return 1 (allowed)
4 EVALSHA ... -> ZCARD 100 -> return 0 (denied)
-- exactly 100 allowed per window, never 101Go (Functions):
const counterLib = `#!lua name=counters
redis.register_function('incr_capped', function(keys, args)
local v = redis.call('INCR', keys[1])
if v > tonumber(args[1]) then
redis.call('DECR', keys[1])
return -1
end
return v
end)`
func IncrCapped(ctx context.Context, rdb *redis.Client, key string, limit int) (int64, error) {
if err := rdb.FunctionLoadReplace(ctx, counterLib).Err(); err != nil {
return 0, err
}
return rdb.FCall(ctx, "incr_capped", []string{key}, limit).Int64()
}Laravel:
$value = Redis::eval(<<<'LUA'
local v = redis.call('INCR', KEYS[1])
if v > tonumber(ARGV[1]) then
redis.call('DECR', KEYS[1])
return -1
end
return v
LUA, 1, 'seats:event:7', 500);Pipelining Must-know
In plain words: send many commands without waiting for each answer, then read all answers. One network round trip instead of N.
Common misunderstanding: "A pipeline is a transaction." Commands from other clients can run between pipelined commands; a pipeline only saves round trips. TxPipeline in go-redis and Redis::transaction in Laravel add MULTI/EXEC.
Definition: the pipelining page: "issuing multiple commands at once without waiting for the response to each individual command". With a 250 ms RTT, it notes, even a server doing 100k requests per second serves at most four requests per second to one client without pipelining. Pipelining also cuts system calls on the server. Batch sizes of hundreds to a few thousand commands are typical; huge pipelines bloat the client output buffer. Scripting is the alternative when later commands depend on earlier results.
without pipeline (RTT 1 ms) with pipeline
1 SET k1 ─▶ OK ◀─ 1 ms SET k1, SET k2, ... SET k1000 ─▶
2 SET k2 ─▶ OK ◀─ 1 ms ◀─ OK x 1000
... 1000 commands = ~1000 ms ~1 RTT + server time = a few msfunc WarmCache(ctx context.Context, rdb *redis.Client, items map[string]string) error {
_, err := rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
for k, v := range items {
p.Set(ctx, "warm:"+k, v, 5*time.Minute)
}
return nil
})
return err
}Client-side caching (tracking) Important
In plain words: the application keeps a copy of hot keys in its own memory, and Redis tells it when one of them changes so it can drop the copy.
Common misunderstanding: "A local cache in front of Redis is always stale." With tracking, invalidation is pushed by the server; staleness is bounded by the time to deliver one message.
Definition: CLIENT TRACKING ON (Redis 6+). In the default mode "the server remembers what keys a given client accessed, and sends invalidation messages when the same keys are modified"; the remembered keys live in an invalidation table capped by tracking-table-max-keys. In broadcasting mode (BCAST PREFIX user:) the server keeps no per-client state and notifies on every change under a prefix. OPTIN/OPTOUT with CLIENT CACHING yes|no select which reads are tracked. With RESP3 the invalidation arrives on the same connection as a push message; with RESP2 it goes to another connection (REDIRECT id) subscribed to __redis__:invalidate. go-redis supports it (experimental, RESP3, database 0):
func CachedClient() *redis.Client {
return redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Protocol: 3,
ClientSideCacheConfig: &redis.ClientSideCacheConfig{MaxEntries: 10_000},
})
}Real scenarios: feature flags and configuration read on every request; hot product records; permission sets. Laravel's Cache::memo() is a per-request memo, not server-assisted tracking.
Error replies you will catch
| Reply prefix | Meaning | Retry? |
|---|---|---|
MOVED slot host:port | Cluster: key's slot lives elsewhere | Client redirects and refreshes its slot map automatically |
ASK slot host:port | Cluster: slot being migrated; key already moved | Client sends ASKING + command to target once |
TRYAGAIN | Multi-key command during migration of the slot | Yes, after a short delay |
CROSSSLOT | Keys of one command/transaction/script in different slots | No: fix the key design (hash tags) |
CLUSTERDOWN | Cluster cannot serve the slot (failover in progress or uncovered slots) | Yes, with backoff |
MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no' | Replica cut off from master | Yes, or read elsewhere |
READONLY | Write sent to a replica (often a stale connection after failover) | Yes, after reconnecting to the new master |
LOADING | Server is loading RDB/AOF into memory | Yes, with backoff |
BUSY | A script or function exceeded busy-reply-threshold | Yes, later; operator may SCRIPT KILL |
NOSCRIPT No matching script | EVALSHA of a script not in the cache (restart, failover) | Fall back to EVAL |
EXECABORT | Transaction discarded because a command failed to queue | No: code bug |
WRONGTYPE Operation against a key holding the wrong kind of value | e.g. LPUSH on a String | No: code or key-collision bug |
OOM | maxmemory reached and the policy cannot (or may not) evict | Not blindly: shed load, fix the policy |
MISCONF | Last background save failed and stop-writes-on-bgsave-error yes | No: fix disk/permissions |
NOAUTH / WRONGPASS | Authentication missing or wrong | No |
NOPERM | ACL forbids the command or key | No |
go-redis classifies them: redis.IsLoadingError, IsReadOnlyError, IsClusterDownError, IsTryAgainError, IsMasterDownError, IsMovedError, IsOOMError, IsAuthError, IsExecAbortError, and redis.HasErrorPrefix(err, "BUSY"); redis.Nil means "key does not exist", which is not a failure.
func Retryable(err error) bool {
switch {
case err == nil:
return false
case redis.IsLoadingError(err), redis.IsTryAgainError(err),
redis.IsClusterDownError(err), redis.IsMasterDownError(err),
redis.IsReadOnlyError(err):
return true // transient: failover, restart, resharding
case redis.IsOOMError(err), redis.IsAuthError(err), redis.IsExecAbortError(err):
return false // fix config or code, do not hammer
}
return false
}Solving the classic problems
Cache-aside, TTL jitter and stampede protection
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Cache-aside (lazy loading) | Read cache; on miss read DB, SET ... EX | Simple; cache holds only what is read | First read after expiry is slow; stale until TTL or invalidation |
| TTL jitter | EX base + random(0..k) | Spreads expiries; no synchronized misses | Slightly less predictable freshness |
| Rebuild lock (mutex) | SET key:rebuild 1 NX EX 5; losers wait and re-read | One DB query per key per miss | Waiters add latency; lock TTL must exceed rebuild time |
| Stale-while-revalidate | Serve old value, refresh in background (Laravel Cache::flexible) | No user waits for rebuild | Bounded staleness |
| Delete after commit | DEL the key after the DB transaction commits | Simple invalidation | Race: a reader can re-cache the old value (see Isolation Levels) |
| Write-through / versioned values | Write cache with a version; refuse older versions in Lua | No stale overwrite | More code |
The source query is ordinary SQL against the system of record:
-- PostgreSQL / MySQL: the cache-aside miss path reads the system of record
SELECT id, name, price_cents, updated_at FROM products WHERE id = $1;
-- after an UPDATE commits, the application runs: DEL product:<id>func GetProduct(ctx context.Context, rdb *redis.Client, db *sql.DB, id string) (string, error) {
key := "product:" + id
v, err := rdb.Get(ctx, key).Result()
if err == nil {
return v, nil // hit
}
if !errors.Is(err, redis.Nil) {
return "", err // Redis is down or slow: decide fail-open vs fail-closed
}
// Miss: only one caller rebuilds; the others wait briefly and re-read.
got, err := rdb.SetNX(ctx, key+":rebuild", 1, 5*time.Second).Result()
if err != nil {
return "", err
}
if !got {
time.Sleep(50 * time.Millisecond)
return rdb.Get(ctx, key).Result()
}
var name string
if err := db.QueryRowContext(ctx, "SELECT name FROM products WHERE id = $1", id).Scan(&name); err != nil {
return "", err
}
ttl := 10*time.Minute + time.Duration(rand.IntN(120))*time.Second // jitter
return name, rdb.Set(ctx, key, name, ttl).Err()
}// Laravel: remember() is cache-aside; flexible() serves stale for 5..10 s while refreshing.
$product = Cache::remember("product:{$id}", now()->addMinutes(10)->addSeconds(random_int(0, 120)),
fn () => Product::findOrFail($id));
$users = Cache::flexible('users', [5, 10], fn () => DB::table('users')->get());Rate limiter
Fixed window: INCR + EXPIRE NX in one MULTI/EXEC. Sliding window: a Sorted Set of timestamps trimmed, counted and appended in one Lua script, with the time read from Redis (TIME) so client clocks do not matter. The "before" version reads, decides and writes from the client and lets two requests both see 99:
// Package ratelimit is the naive counter: read, decide, write back.
package ratelimit
import (
"context"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
// Allow lets 100 requests per minute through. Two concurrent callers can both
// GET 99, both pass the check, and both SET 100: the counter loses an update.
func Allow(ctx context.Context, rdb *redis.Client, userID string) (bool, error) {
key := "rate:" + userID
n, err := rdb.Get(ctx, key).Int()
if err != nil && err != redis.Nil {
return false, err
}
if n >= 100 {
return false, nil
}
// Race window: another client may have written between GET and SET.
err = rdb.Set(ctx, key, strconv.Itoa(n+1), time.Minute).Err()
return err == nil, err
}// Package ratelimit shows two atomic limiters: a fixed window built from
// INCR + EXPIRE in one MULTI/EXEC, and a sliding window in one Lua script.
package ratelimit
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
// FixedWindow sends INCR and EXPIRE ... NX (Redis 7+) in one MULTI/EXEC.
// The TTL is set only on the first hit, so the window does not slide forward.
func FixedWindow(ctx context.Context, rdb *redis.Client, userID string, limit int64, window time.Duration) (bool, error) {
key := "rate:fixed:" + userID
pipe := rdb.TxPipeline()
incr := pipe.Incr(ctx, key)
pipe.ExpireNX(ctx, key, window)
if _, err := pipe.Exec(ctx); err != nil {
return false, err
}
return incr.Val() <= limit, nil
}
// The whole script runs without any other command interleaved, so
// trim, count and add cannot race. TIME is read inside the script.
var slidingWindow = redis.NewScript(`
local key = KEYS[1]
local window = tonumber(ARGV[1]) -- milliseconds
local limit = tonumber(ARGV[2])
local member = ARGV[3] -- unique per request
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
if redis.call('ZCARD', key) >= limit then
return 0
end
redis.call('ZADD', key, now, member)
redis.call('PEXPIRE', key, window)
return 1
`)
// SlidingWindow allows at most limit requests in any window-long interval.
func SlidingWindow(ctx context.Context, rdb *redis.Client, userID, requestID string, limit int, window time.Duration) (bool, error) {
res, err := slidingWindow.Run(ctx, rdb,
[]string{"rate:sliding:" + userID},
window.Milliseconds(), limit, requestID,
).Int()
if err != nil {
return false, err
}
return res == 1, nil
}| Algorithm | Redis structure | Accuracy | Memory per client |
|---|---|---|---|
| Fixed window | String + TTL | Bursts of 2× at window edges | One key |
| Sliding log | Sorted Set of request timestamps | Exact | One member per request in the window |
| Sliding window counter | Two Strings (current + previous window) | Approximate | Two keys |
| Token bucket / GCRA | Hash or String updated in Lua | Smooth | One key |
Laravel's RateLimiter::attempt, tooManyAttempts, hit and the throttle middleware run on the cache store named by the limiter key in config/cache.php; Redis::throttle('key')->allow(1)->every(5) is the Redis-native limiter for jobs, and Cache::funnel() limits concurrency on top of atomic locks.
Distributed lock and the Redlock debate
A lock is one atomic SET lock:name <random-token> NX PX <ttl>; release is compare-and-delete in Lua so a client whose lock already expired cannot delete the next holder's lock. The "before" version (SETNX without expiry or owner) blocks everyone forever when the holder crashes:
// Package lock is a lock built on SETNX with no expiry and no owner.
package lock
import (
"context"
"github.com/redis/go-redis/v9"
)
// Acquire takes the lock if nobody holds it. There is no TTL: if the holder
// crashes before Release, the key stays forever and nobody can ever lock again.
func Acquire(ctx context.Context, rdb *redis.Client, name string) (bool, error) {
return rdb.SetNX(ctx, "lock:"+name, "1", 0).Result()
}
// Release deletes the key whoever owns it. A slow client can delete a lock
// that was already handed to somebody else.
func Release(ctx context.Context, rdb *redis.Client, name string) error {
return rdb.Del(ctx, "lock:"+name).Err()
}// Package lock is a single-instance Redis lock: SET NX PX to acquire, and a
// compare-and-delete script to release. It is an efficiency lock, not a
// correctness guarantee; see the page for the Redlock debate and fencing tokens.
package lock
import (
"context"
"crypto/rand"
"encoding/hex"
"time"
"github.com/redis/go-redis/v9"
)
type Lock struct {
rdb *redis.Client
key string
token string
}
// Release deletes the key only if it still holds our token.
// On Redis 8.4+ this can be a single DELEX key IFEQ token.
var release = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
// Acquire returns (nil, nil) when somebody else holds the lock.
func Acquire(ctx context.Context, rdb *redis.Client, name string, ttl time.Duration) (*Lock, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
token := hex.EncodeToString(buf)
// SET key token NX PX ttl: one atomic command, expiry included.
ok, err := rdb.SetNX(ctx, "lock:"+name, token, ttl).Result()
if err != nil || !ok {
return nil, err
}
return &Lock{rdb: rdb, key: "lock:" + name, token: token}, nil
}
// Release reports whether we still owned the lock when we released it.
func (l *Lock) Release(ctx context.Context) (bool, error) {
n, err := release.Run(ctx, l.rdb, []string{l.key}, l.token).Int()
return n == 1, err
}For correctness, a TTL lock has a hole: the holder can pause (GC, page fault, network) past the TTL, and two clients then believe they hold it. The Redis lock page itself says "You should implement fencing tokens", and offers Redlock (acquire on a majority of N independent masters within a validity time). Martin Kleppmann's 2016 critique:
"The algorithm does not produce any number that is guaranteed to increase every time a client acquires a lock. This means that even if the algorithm were otherwise perfect, it would not be safe to use, because you cannot prevent the race condition between clients in the case where one client is paused or its packets are delayed." — Martin Kleppmann, How to do distributed locking
The fix is a fencing token: a number that increases on every acquisition (INCR fence:name in Redis, or a database sequence) and that the protected storage checks:
-- PostgreSQL: the storage rejects writes from a holder with an older token
ALTER TABLE invoices ADD COLUMN fence bigint NOT NULL DEFAULT 0;
UPDATE invoices SET body = $1, fence = $2 WHERE id = $3 AND fence < $2;
-- 0 rows updated => a newer lock holder already wrote; abortfunc AcquireWithFence(ctx context.Context, rdb *redis.Client, name, token string, ttl time.Duration) (int64, bool, error) {
ok, err := rdb.SetNX(ctx, "lock:"+name, token, ttl).Result()
if err != nil || !ok {
return 0, false, err
}
fence, err := rdb.Incr(ctx, "fence:"+name).Result()
return fence, err == nil, err
}| Lock option | Safe for | Not safe for |
|---|---|---|
SET NX PX + compare-and-delete on one Redis | Efficiency: avoid duplicate work | Correctness across pauses or failover (async replica may lose the key) |
| Redlock on 5 independent masters | Same, with tolerance of a node failure | Correctness without fencing; depends on bounded clock drift and pauses |
| Lock + fencing token checked by storage | Correctness | Needs storage that can compare tokens |
Database lock (SELECT ... FOR UPDATE, pg_advisory_lock) | Correctness inside that database | Cross-system work; see Locks & Concurrency |
| etcd / ZooKeeper lease with revision | Correctness with consensus | Extra system to run |
Laravel's Cache::lock('name', 10) is the token-and-compare pattern: get(), block(5), release() only for the owner, owner() + restoreLock() to release from a queued job, refresh() to extend, forceRelease() to ignore the owner.
Leaderboard
ZINCRBY to score, ZRANGE ... REV WITHSCORES for the top N, ZREVRANK for a player's position, ZSCORE for one score. Ties order by member name; to break ties by time, encode score * 1e10 + (MAX_TS - ts) into the score. Weekly boards are separate keys (lb:2026-w48) with an EXPIREAT; all-time = ZUNIONSTORE.
// Package leaderboard keeps scores in a Sorted Set: O(log N) updates,
// O(log N + M) range reads.
package leaderboard
import (
"context"
"github.com/redis/go-redis/v9"
)
const key = "leaderboard:global"
// AddScore increments a player's score (ZINCRBY) and returns the new total.
func AddScore(ctx context.Context, rdb *redis.Client, player string, points float64) (float64, error) {
return rdb.ZIncrBy(ctx, key, points, player).Result()
}
// Top returns the n best players, highest first (ZREVRANGE ... WITHSCORES).
func Top(ctx context.Context, rdb *redis.Client, n int64) ([]redis.Z, error) {
return rdb.ZRevRangeWithScores(ctx, key, 0, n-1).Result()
}
// Rank returns the zero-based position of a player, highest score first.
func Rank(ctx context.Context, rdb *redis.Client, player string) (int64, error) {
return rdb.ZRevRank(ctx, key, player).Result()
}Session store
One Hash per session (session:<id>), a sliding TTL refreshed on each request, HSET of changed fields only. Set maxmemory-policy to noeviction or volatile-* on an instance shared with a cache, or users get logged out by eviction. Use persistence (AOF everysec) if a restart should not log everyone out.
func TouchSession(ctx context.Context, rdb *redis.Client, sid string, fields map[string]any) error {
_, err := rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, "session:"+sid, fields)
p.Expire(ctx, "session:"+sid, 30*time.Minute)
return nil
})
return err
}Laravel: SESSION_DRIVER=redis with SESSION_CONNECTION naming the Redis connection; session blocking (->block() on a route) needs a cache driver with atomic locks, which redis is.
Queues and Pub/Sub (pointers)
Lists with BLMOVE give a light reliable queue; Sorted Sets give delayed jobs; Streams give consumer groups, acknowledgements and redelivery. Pub/Sub is fire-and-forget fan-out to connected subscribers only. Laravel's redis queue driver uses lists and sorted sets and requires hash-tagged queue names on Cluster ('queue' => '{default}'). Details: Redis Streams & Pub/Sub, Laravel Queue Internals, Retry, Backoff & Delayed Delivery.
Big-key and hot-key fixes in code
Walk and delete with SCAN + UNLINK in batches instead of KEYS + DEL:
func PurgePrefix(ctx context.Context, rdb *redis.Client, prefix string) (int, error) {
iter := rdb.Scan(ctx, 0, prefix+"*", 500).Iterator()
batch := make([]string, 0, 500)
n := 0
for iter.Next(ctx) {
batch = append(batch, iter.Val())
if len(batch) == cap(batch) {
if err := rdb.Unlink(ctx, batch...).Err(); err != nil {
return n, err
}
n += len(batch)
batch = batch[:0]
}
}
if err := iter.Err(); err != nil {
return n, err
}
if len(batch) > 0 {
if err := rdb.Unlink(ctx, batch...).Err(); err != nil {
return n, err
}
n += len(batch)
}
return n, nil
}// Laravel (phpredis): SCAN with a cursor; never Redis::keys('*') in production.
// Use a connection WITHOUT options.prefix: SCAN returns full key names and
// MATCH ignores the prefix, so a prefixed connection would double-prefix UNLINK.
$redis = Redis::connection('maintenance');
$cursor = null;
do {
[$cursor, $keys] = $redis->scan($cursor, ['match' => 'app-database-tmp:*', 'count' => 500]) ?: [0, []];
if ($keys) {
$redis->unlink(...$keys);
}
} while ($cursor);Security
ACL, TLS and protected mode Must-know
In plain words: Redis trusts whoever can reach its port. Keep it on a private network, require a user and password per application, restrict commands and keys per user, and encrypt the connection.
Common misunderstanding: "requirepass is enough." It sets the password of the default user, who can still run FLUSHALL, CONFIG SET and DEBUG; a leaked password is full control, including writing files via CONFIG SET dir.
Definition: the security page: "Redis is designed to be accessed by trusted clients inside trusted environments." Protected mode (since 3.2): when Redis runs with the default configuration (binding all interfaces) and no password, it "only replies to queries from the loopback interfaces"; the shipped redis.conf sets bind 127.0.0.1 -::1 and protected-mode yes. ACLs (Redis 6+): ACL SETUSER app on >secret ~app:* &app:* +@read +@write -@dangerous, ACL LIST, ACL WHOAMI, ACL LOG (denied attempts), aclfile for an external file; categories like @dangerous, @admin, @slow; selectors for per-key read/write rules. Errors: NOAUTH, WRONGPASS, NOPERM. TLS (tls-port, tls-cert-file, tls-key-file, tls-ca-cert-file, tls-auth-clients, tls-replication, tls-cluster). rename-command CONFIG "" is the legacy way to hide a command; ACLs replace it.
attacker on the network Redis 6379 open, no auth
1 CONFIG SET dir /var/lib/redis/.ssh
2 CONFIG SET dbfilename authorized_keys
3 SET x "\n\nssh-ed25519 AAAA...\n\n" ; SAVE
-- classic takeover; prevented by bind + protected mode + ACL (-@dangerous) + no root| Control | Redis | Valkey | Memcached |
|---|---|---|---|
| Users and per-command/key ACLs | Yes (6.0+) | Yes (+ ACL roles in 9.2) | No command-level ACLs |
| TLS | Yes (6.0+, build option) | Yes | Build-dependent; check your version |
| Protected mode | Yes (3.2+) | Yes | No (binds per config) |
Laravel: REDIS_USERNAME, REDIS_PASSWORD, a scheme of tls in the connection config; go-redis: redis.Options with Username, Password and TLSConfig (a *tls.Config). See Database Security.
Redis and its alternatives
Redis vs Memcached vs Valkey, Dragonfly, KeyDB Important
In plain words: Memcached is a simpler, multi-threaded cache of strings; Valkey is the open-source (BSD) fork of Redis 7.2.4; Dragonfly and KeyDB are re-implementations or forks focused on using all CPU cores.
Common misunderstanding: "They are all drop-in replacements." Wire protocol compatibility is not feature parity: Redis 8 types (JSON, time series, vector sets), newer commands, module APIs, persistence formats and Cluster behaviour differ. Test your command set.
| Redis 8 | Valkey | Memcached | Dragonfly | KeyDB | |
|---|---|---|---|---|---|
| Licence | RSALv2 / SSPLv1 / AGPLv3 (choose) | BSD 3-clause | BSD 3-clause | Dragonfly Source-Available License (DSAL) | BSD 3-clause |
| Threads for commands | One main thread (+ I/O threads) | One main thread (+ I/O threads) | Multi-threaded | Shard per thread | Multi-threaded fork |
| Data types | All above incl. JSON, TS, vector sets | Core types; JSON/Bloom as modules | Strings only | Redis + Memcached APIs | Redis 6-era types |
| Persistence | RDB, AOF | RDB, AOF; forkless snapshots in 9.2 | None | Snapshots | RDB, AOF, FLASH storage |
| Clustering | Redis Cluster, Sentinel | Same protocol | Client-side sharding | Own replication and cluster mode | Active replication, Cluster |
| Backed by | Redis Ltd. | Linux Foundation (AWS, Google Cloud, Oracle, Ericsson, Snap) | Community | DragonflyDB Ltd. | Snap Inc. |
Dragonfly's README claims "25X more throughput" than a single Redis process; that is a vendor benchmark, not a neutral one. KeyDB describes itself as "A Multithreaded Fork of Redis" with "Active Replication, FLASH Storage and Subkey Expires".
Licences and forks: RSALv2/SSPL (2024) → AGPL (2025), Valkey Important
In plain words: Redis was BSD until 7.2; 7.4 moved to two source-available licences; Redis 8 added the open-source AGPLv3 as a third option. In between, the community forked the last BSD release as Valkey.
Common misunderstanding: "Using Redis in my SaaS now requires a commercial licence." The March 2024 announcement says that for end users using Redis "for their internal or personal usage, there is no change"; the restrictions target offering Redis itself as a competing service. AGPL adds obligations if you modify Redis and offer it over a network.
| Date | Event | Source |
|---|---|---|
| up to Redis 7.2 | BSD 3-clause | redis.io licensing post |
| 20 March 2024 | "Starting with Redis 7.4, Redis will be dual-licensed under the Redis Source Available License (RSALv2) and Server Side Public License (SSPLv1)" | redis.io blog |
| 28 March 2024 | Linux Foundation announces Valkey, continuing from Redis 7.2.4 under BSD 3-clause | Linux Foundation press release |
| November 2024 | antirez rejoins Redis | redis.io AGPL post |
| 1 May 2025 | Redis 8 adds AGPLv3 as an option and folds Redis Stack features into the core | redis.io AGPL post |
"Adding the OSI-approved AGPL as an additional licensing option for Redis, starting with Redis 8 (available now);" — Redis blog, Redis is now available under the AGPLv3 open source license, 1 May 2025
Practical effect: managed services (ElastiCache, Memorystore) added Valkey engines; Linux distributions ship Valkey or Redis 8 depending on policy; client libraries (go-redis BSD-2, phpredis, predis) work with both.
Go
Before
A rate limiter that reads, decides and writes from the client, and a lock that uses SETNX with no expiry or owner. Both are shown in the solutions above with their fixes:
// Package ratelimit is the naive counter: read, decide, write back.
package ratelimit
import (
"context"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
// Allow lets 100 requests per minute through. Two concurrent callers can both
// GET 99, both pass the check, and both SET 100: the counter loses an update.
func Allow(ctx context.Context, rdb *redis.Client, userID string) (bool, error) {
key := "rate:" + userID
n, err := rdb.Get(ctx, key).Int()
if err != nil && err != redis.Nil {
return false, err
}
if n >= 100 {
return false, nil
}
// Race window: another client may have written between GET and SET.
err = rdb.Set(ctx, key, strconv.Itoa(n+1), time.Minute).Err()
return err == nil, err
}After
The token-owned lock with compare-and-delete release, imported from the compiled snippet module. The fixed and sliding-window limiters are in Rate limiter and the leaderboard in Leaderboard.
// Package lock is a single-instance Redis lock: SET NX PX to acquire, and a
// compare-and-delete script to release. It is an efficiency lock, not a
// correctness guarantee; see the page for the Redlock debate and fencing tokens.
package lock
import (
"context"
"crypto/rand"
"encoding/hex"
"time"
"github.com/redis/go-redis/v9"
)
type Lock struct {
rdb *redis.Client
key string
token string
}
// Release deletes the key only if it still holds our token.
// On Redis 8.4+ this can be a single DELEX key IFEQ token.
var release = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
// Acquire returns (nil, nil) when somebody else holds the lock.
func Acquire(ctx context.Context, rdb *redis.Client, name string, ttl time.Duration) (*Lock, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
token := hex.EncodeToString(buf)
// SET key token NX PX ttl: one atomic command, expiry included.
ok, err := rdb.SetNX(ctx, "lock:"+name, token, ttl).Result()
if err != nil || !ok {
return nil, err
}
return &Lock{rdb: rdb, key: "lock:" + name, token: token}, nil
}
// Release reports whether we still owned the lock when we released it.
func (l *Lock) Release(ctx context.Context) (bool, error) {
n, err := release.Run(ctx, l.rdb, []string{l.key}, l.token).Int()
return n == 1, err
}The Go angle
The official client is github.com/redis/go-redis/v9. Things that bite:
| Topic | What to know |
|---|---|
redis.Nil | An error value meaning "key does not exist": check errors.Is(err, redis.Nil) before treating an error as an outage |
| Context | Every command takes context.Context; set deadlines so a stuck Redis does not hang requests; Options.ReadTimeout/WriteTimeout/DialTimeout |
| Pool | PoolSize (default 10 * runtime.GOMAXPROCS(0)), MinIdleConns, PoolTimeout; one client per process, shared by goroutines. See Connection Pooling |
Pipeline vs TxPipeline | Batching only vs batching inside MULTI/EXEC |
Watch | Optimistic transaction; returns redis.TxFailedErr when a watched key changed |
NewScript | Runs EVALSHA, falls back to EVAL on NOSCRIPT |
FunctionLoad / FCall | Redis 7 Functions |
NewFailoverClient | Sentinel-aware client (MasterName, SentinelAddrs) |
NewClusterClient | Follows MOVED/ASK, ReadOnly/RouteByLatency for replica reads; pipelines and transactions still need one slot |
Protocol: 3 | RESP3; required for client-side caching (ClientSideCacheConfig, experimental) |
Wait | WAIT numreplicas timeout |
func Clients() (*redis.Client, *redis.ClusterClient) {
failover := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: "mymaster",
SentinelAddrs: []string{"sentinel-1:26379", "sentinel-2:26379", "sentinel-3:26379"},
})
cluster := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{"redis-1:7000", "redis-2:7001", "redis-3:7002"},
ReadOnly: true, // allow reads from replicas (stale reads possible)
RouteByLatency: true,
})
return failover, cluster
}
// Hash tag: both keys land in the same slot, so MULTI/EXEC works in Cluster.
func AddToCart(ctx context.Context, rc *redis.ClusterClient, userID, sku string) error {
_, err := rc.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HIncrBy(ctx, "cart:{"+userID+"}", sku, 1)
p.Expire(ctx, "cart:{"+userID+"}", 24*time.Hour)
p.SAdd(ctx, "cart-skus:{"+userID+"}", sku)
return nil
})
return err
}Laravel
Before
Cache::get then Cache::put is the same read-modify-write race as the Go version; the hand-rolled Redis::set lock has no expiry, no owner, and a gap between exists and set.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
final class Before
{
// Read-modify-write: two requests can both read 99 and both write 100.
public function hit(int $userId): bool
{
$key = "rate:{$userId}";
$count = (int) Cache::get($key, 0);
if ($count >= 100) {
return false;
}
Cache::put($key, $count + 1, 60);
return true;
}
// Manual lock: no TTL, so a crash before del() leaves it forever, and no
// owner token, so any process can delete somebody else's lock.
public function runExclusive(callable $work): void
{
if (Redis::exists('lock:report')) {
return;
}
// Race: another process can pass exists() before this set() runs.
Redis::set('lock:report', 1);
try {
$work();
} finally {
Redis::del('lock:report');
}
}
}After
RateLimiter::attempt and Cache::lock replace both; the leaderboard uses Redis::zincrby/zrevrange; Redis::transaction wraps MULTI/EXEC and Redis::pipeline batches round trips.
<?php
namespace App\Services;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Redis;
final class After
{
// RateLimiter::attempt increments and checks through the limiter cache
// store (the 'limiter' key in config/cache.php), no get-then-put by hand.
public function hit(int $userId): bool
{
return RateLimiter::attempt("send-message:{$userId}", 100, fn () => true, 60) === true;
}
// Cache::lock stores a random owner token and releases only if it matches.
// Lock for at most 10 seconds, wait at most 5 seconds to get it.
public function runExclusive(callable $work): void
{
$lock = Cache::store('redis')->lock('report', 10);
try {
$lock->block(5);
} catch (LockTimeoutException) {
// Could not get the lock in time: skip or retry later.
return;
}
try {
$work();
} finally {
$lock->release(); // no-op if the owner token no longer matches
}
}
// Non-blocking variant with an owner token handed to a queued job.
public function tryStart(): ?string
{
$lock = Cache::store('redis')->lock('processing', 120);
return $lock->get() ? $lock->owner() : null;
}
public function finish(string $owner): void
{
Cache::store('redis')->restoreLock('processing', $owner)->release();
}
// Sorted Set leaderboard.
public function addScore(string $player, float $points): void
{
Redis::zincrby('leaderboard:global', $points, $player);
}
/** @return array<string, float> player => score, best first */
public function top(int $n): array
{
return Redis::zrevrange('leaderboard:global', 0, $n - 1, ['withscores' => true]);
}
// MULTI/EXEC: all queued commands run as one isolated unit.
// Inside transaction() you queue commands, you cannot read their results.
public function recordVisit(): void
{
Redis::transaction(function ($redis) {
$redis->incr('user_visits');
$redis->incr('total_visits');
});
}
// Pipeline: one round trip, no atomicity guarantee.
public function warm(array $pairs): void
{
Redis::pipeline(function ($pipe) use ($pairs) {
foreach ($pairs as $key => $value) {
$pipe->setex("warm:{$key}", 300, $value);
}
});
}
}The Laravel angle: phpredis vs predis and the facades
| Topic | What Laravel 13 does |
|---|---|
| Client | 'client' => env('REDIS_CLIENT', 'phpredis'); the docs encourage the PhpRedis PECL extension for performance; Predis (composer require predis/predis) is pure PHP and needs no extension |
| Connections | default (db 0) and cache (db 1) in config/database.php; separate them so cache:clear does not wipe sessions or queues |
| Cluster | options.cluster = redis uses native Redis Cluster ("gracefully handles failover"); Predis also supports client-side sharding, which "does not handle failover" |
| Prefix | options.prefix defaults to the app name slug + -database-; cache keys get the cache prefix as well |
Redis facade | Magic methods map to commands (Redis::zincrby), Redis::command('...', [...]), transaction, pipeline, eval, subscribe/psubscribe/publish, throttle |
| Cache | Cache::store('redis'), remember, flexible (stale-while-revalidate), lock/restoreLock, tags (Cache::tags) on Redis |
| Rate limiting | RateLimiter::attempt, tooManyAttempts, hit, remaining, throttle middleware |
| Sessions | SESSION_DRIVER=redis, SESSION_CONNECTION |
| Queues | redis driver with retry_after, block_for, after_commit; on Cluster the queue name needs a hash tag ({default}); see Laravel Queue Internals |
phpredis vs predis in practice:
| phpredis | predis | |
|---|---|---|
| Install | PECL C extension (preinstalled in Sail) | Composer package |
| Speed | Faster, lower CPU per command | Slower, all in PHP |
| Features | Cluster, Sentinel, TLS, serializers and compression (igbinary, lz4/zstd), persistent connections | Cluster, Sentinel, TLS, client-side sharding |
| When | Production default | Where you cannot install extensions |
In production systems
- Redis docs, eviction.
maxmemorywithallkeys-lruis the documented good default for a cache; withnoeviction, writes return errors at the limit, which is what you want for data you cannot lose. - Redis docs, persistence. The page discourages AOF alone and recommends combining it with RDB; since 7.0 the AOF is a base file plus incremental files tracked by a manifest.
- Redis docs, latency. The guide lists slow commands (with
KEYSnamed as a "VERY common source of latency"), fork time (with measured per-GB figures), transparent huge pages and swapping as the main sources, with commands to diagnose each. - Laravel. The queue docs require hash-tagged queue names on Redis Cluster;
Cache::lockexposes owner tokens,refresh()andforceRelease(), the same shape as the token-and-compare lock on the Redis lock page.
Choosing
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Read-heavy cache of DB rows | Redis/Valkey, allkeys-lru or allkeys-lfu, no or RDB persistence | Cache-aside, TTL jitter, rebuild lock | Cheap misses; data can be rebuilt |
| Sessions | Redis Hash per session, AOF everysec, noeviction or volatile policy | Sliding TTL | Losing sessions logs users out |
| Rate limiting | String + INCR or Sorted Set in Lua | One script per check | Atomic, sub-ms |
| Leaderboard / ranking | Sorted Set | Weekly keys + ZUNIONSTORE | O(log N) updates and rank |
| Mutual exclusion for efficiency | SET NX PX + compare-and-delete | Laravel Cache::lock | Simple |
| Mutual exclusion for correctness | Database lock or lock + fencing token | etcd/ZooKeeper | Redis replication is asynchronous |
| Durable queue with acks | Streams consumer groups, or RabbitMQ/Kafka | See messaging pages | Lists lose in-flight work without care |
| Fan-out notifications to online users | Pub/Sub or sharded Pub/Sub | Streams if offline users matter | At-most-once |
| Unique counts at scale | HyperLogLog | PFMERGE for rollups | 12 KB per counter |
| Primary data that must not be lost | PostgreSQL/MySQL; Redis as cache | WAIT + AOF if Redis must hold it | No strong consistency in Redis replication |
| >1 node of memory or CPU | Redis Cluster (hash tags) or client-side sharding | Avoid big/hot keys | One key = one shard |
| Multi-core single node, simple strings | Memcached, or Redis with io-threads | Command execution is single-threaded | |
| Licence must be OSI open source, BSD | Valkey | Redis 8 offers AGPLv3, not BSD |
In architecture: from a single process to a distributed system
Redis is almost always a second store next to a database. The architecture question is what happens when the two disagree, and what happens when Redis is empty, slow or failing over.
Monolith: one process, one database
How it shows up: one Redis next to one PostgreSQL or MySQL. Laravel uses it for cache, sessions, queue and rate limiting at once; a Go service uses it for cache and locks.
Simplest correct usage: separate logical databases or, better, separate instances for cache (evictable, allkeys-lru, no persistence) and for sessions/queues (noeviction, AOF). Cache-aside with TTL jitter; invalidate after commit; atomic commands for counters.
Example (simple): a shop caches product pages for 10 minutes ± 2 and deletes product:42 after the price update commits.
Example (complex): a flash sale keeps the authoritative stock in PostgreSQL (UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock > 0), uses a Redis Lua script as a fast pre-check that rejects 99% of requests once a counter reaches zero, and rate-limits per user with a sliding window. Redis protects the database; the database guarantees correctness.
Modular monolith and multiple databases
How it shows up: modules share one Redis. Collisions and noisy neighbours appear: the reporting module's KEYS blocks checkout; two modules use user:42 for different shapes and get WRONGTYPE.
Rules: key prefix per module (billing:, catalog:), ACL users per module restricted to their prefix (~billing:*), a policy that cache data and durable data do not share an instance with allkeys-* eviction, and no cross-module reads of another module's keys.
Example: Catalog owns catalog:product:* cache keys and publishes "ProductChanged" through the outbox; Search invalidates its own search:* keys from that event rather than deleting catalog: keys directly.
Microservices: shared cache, idempotency and events
What survives: per-service Redis for caching and rate limiting; idempotency keys (SET idem:<request-id> <result> NX EX 86400) so retried requests and redelivered messages apply once; distributed rate limits at the gateway. What does not: transactions across services (Redis MULTI covers only that Redis), and a Redis lock protecting another service's database without fencing.
API gateway Order service Payment service
1 INCR rl:{client42}:min -> 57 (allowed)
2 ─▶ POST /orders (Idempotency-Key: k1)
3 SET idem:k1 "pending" NX EX 86400 -> OK (first time)
4 BEGIN; INSERT order; INSERT outbox; COMMIT
5 SET idem:k1 '{"order":9001}' XX
6 client retries POST (timeout) with k1
7 GET idem:k1 -> '{"order":9001}' -> return same response, no second order
8 consume OrderCreated; its own idem:<msg-id> checkSee Idempotent Consumers & the Inbox Pattern and Saga Pattern.
Distributed data: replicas, failover, Cluster and multi-region
Replica reads are stale by replication lag; route read-your-writes paths to the master. Failover can lose acknowledged writes (asynchronous replication); WAIT narrows the window, min-replicas-to-write stops a partitioned master from accepting writes it will lose. Cluster shards by slot: design keys so each operation's keys share a hash tag, and accept that a hot key stays on one shard. Cache coherence with the database is never transactional: delete after commit, short TTLs, versioned values, or invalidation driven by CDC. Multi-region: Redis open source has no multi-master; options are a regional cache per region invalidated by events, or Redis Enterprise Active-Active (CRDT-based, commercial). Consistency vocabulary: Eventual Consistency in Database Systems.
region EU (writes) region US (cache only)
1 UPDATE price (PostgreSQL primary)
2 COMMIT; outbox -> "PriceChanged"
3 DEL product:42 (EU Redis) consume PriceChanged -> DEL product:42 (US Redis)
4 next read misses -> reads US replica of PostgreSQL (may lag)Scaling path: 1×, 10×, 100×
| Load | What changes | Redis consequence |
|---|---|---|
| 1× (one instance) | Cache, sessions, locks on one node; maxmemory set; persistence chosen | Watch SLOWLOG, used_memory, hit ratio (keyspace_hits/keyspace_misses) |
| 10× (replicas, Sentinel, pools) | Replica + 3 Sentinels for HA; read replicas for heavy reads; pipelining; io-threads on big boxes | Fork latency on large datasets (persist on replica), big keys found with --bigkeys, client pools sized |
| 100× (Cluster, many services) | Redis Cluster with hash-tagged keys; separate clusters per workload; client-side caching for hot keys; sharded counters | Resharding with --cluster reshard online; CROSSSLOT design reviews; hot-key detection with LFU/Top-K; capacity per shard, not per cluster |
Lab
Docker only. Every step below was run on Redis 8.10.3 in Docker on a laptop; comments marked "measured" are real output from that run, other comments show the expected shape. Your numbers will differ.
Setup.
docker network create redislab
docker run -d --name r1 --network redislab -p 6379:6379 redis:8 redis-server --appendonly yes --latency-monitor-threshold 50
# terminal A and B: docker exec -it r1 redis-cli1. Throughput and pipelining with redis-benchmark.
docker exec r1 redis-benchmark -t set,get -n 100000 -q
# measured (Redis 8.10.3 in Docker on a laptop): SET: 243902.44 requests per second, p50=0.103 msec
docker exec r1 redis-benchmark -t set,get -n 100000 -P 32 -q
# measured with -P 32 (pipeline 32 commands): SET: 2564102.50 requests per second, ~10x
docker exec r1 redis-benchmark -t set -n 200000 -c 200 -d 1024 -q # 200 clients, 1 KB values2. Big key latency: DEL vs UNLINK.
# terminal B: watch latency continuously
docker exec -it r1 redis-cli --latency-history -i 1
# terminal A: build a 2-million-member set with ONE long Lua script (deliberately blocking)
docker exec r1 redis-cli EVAL "for i=1,2000000 do redis.call('SADD', KEYS[1], i) end return 1" 1 big:set
# (B shows a spike while the script runs: SLOWLOG recorded it at ~732000 microseconds)
docker exec r1 redis-cli MEMORY USAGE big:set # measured: 65666194 bytes (~65 MB)
docker exec r1 redis-cli OBJECT ENCODING big:set # "hashtable" (way past set-max-intset-entries 512)
docker exec r1 redis-cli --bigkeys # reports big:set as the biggest set
docker exec r1 redis-cli DEL big:set # measured: SLOWLOG shows DEL at ~73000 microseconds
# rebuild it, then:
docker exec r1 redis-cli UNLINK big:set # not in SLOWLOG (< 10 ms): freed in a background thread
docker exec r1 redis-cli SLOWLOG GET 5 # entries: id, timestamp, microseconds, command, client
docker exec r1 redis-cli LATENCY DOCTOR3. MONITOR, and why not in production.
# terminal B
docker exec -it r1 redis-cli MONITOR
# terminal A
docker exec r1 redis-cli SET a 1 ; docker exec r1 redis-cli INCR a
# B prints (measured): 1795614205.191095 [0 127.0.0.1:60828] "SET" "a" "1"
# 1795614205.243351 [0 127.0.0.1:60830] "INCR" "a"
# the MONITOR page: "running a single MONITOR client can reduce the throughput by more than 50%."
docker exec r1 redis-benchmark -t set -n 100000 -q # run with and without MONITOR attached: compare4. Encodings and transactions.
1 HSET h f1 v1 -> OBJECT ENCODING h = "listpack"
2 DEBUG is disabled by default (enable-debug-command no); use a loop instead to grow h past 512 fields
3 WATCH n ; GET n ; MULTI ; INCR n ; (terminal B: SET n 100) ; EXEC -> (nil)
4 MULTI ; SET s x ; LPUSH s y ; EXEC -> 1) OK 2) WRONGTYPE ... (no rollback: s = "x")5. Cluster and resharding in Docker.
for p in 7000 7001 7002 7003 7004 7005; do
docker run -d --name c$p --network redislab redis:8 redis-server --port $p \
--cluster-enabled yes --cluster-config-file nodes.conf --appendonly yes
done
docker exec c7000 redis-cli --cluster create \
c7000:7000 c7001:7001 c7002:7002 c7003:7003 c7004:7004 c7005:7005 \
--cluster-replicas 1 --cluster-yes
docker exec -it c7000 redis-cli -c -p 7000
# > CLUSTER KEYSLOT foo -> 12182 (owned by the third master)
# > SET foo bar prints "-> Redirected to slot [12182] located at <ip>:7002" (-c follows MOVED)
# > MSET a 1 b 2 -> (error) CROSSSLOT Keys in request don't hash to the same slot
# > MSET {u}a 1 {u}b 2 -> OK (hash tag)
docker exec c7000 redis-cli -p 7000 CLUSTER SHARDS
# move 1000 slots from the first master to the second, non-interactively:
docker exec c7000 redis-cli --cluster reshard c7000:7000 \
--cluster-from <node-id-of-c7000> --cluster-to <node-id-of-c7001> --cluster-slots 1000 --cluster-yes
# Redis 8.x prints "Waiting for migration task ... to complete." while slots move
docker exec c7000 redis-cli --cluster check c7000:7000
# without -c: redis-cli -p 7000 GET foo -> measured: MOVED 12182 172.22.0.4:70026. Failover loses writes (Sentinel-free demo, run as written). Cut the replica off, write on the master, kill the master, promote the replica. Gotcha: WAIT counts acknowledgements of the writes made on its own connection; sent from a fresh redis-cli that wrote nothing, it returns the full replica count immediately and fools you.
docker run -d --name r2 --network redislab redis:8 redis-server --replicaof r1 6379
printf 'SET before 1\nWAIT 1 2000\n' | docker exec -i r1 redis-cli # OK, 1 (one replica acked)
docker network disconnect redislab r2
printf 'SET lost 1\nWAIT 1 500\n' | docker exec -i r1 redis-cli # OK, 0 (no replica acked)
docker kill r1
docker exec r2 redis-cli REPLICAOF NO ONE
docker exec r2 redis-cli GET before # "1"
docker exec r2 redis-cli EXISTS lost # 0: an acknowledged write is goneCleanup: docker rm -f r1 r2 c7000 c7001 c7002 c7003 c7004 c7005 && docker network rm redislab.
Common misconceptions
| Belief | Reality |
|---|---|
| Redis is single-threaded, so my code is race-free | Each command is atomic; sequences of commands interleave. Use one command, Lua/Functions or WATCH |
| Redis 6+ is multi-threaded | I/O threads move socket work; commands still execute on one main thread |
MULTI/EXEC rolls back on error | No rollback; runtime errors fail only that command |
| A pipeline is atomic | It only saves round trips; use MULTI/EXEC or a script for atomicity |
AOF everysec means zero loss | Up to about a second, plus anything an asynchronous replica had not received at failover |
WAIT makes Redis strongly consistent | It counts acknowledgements; acknowledged writes can still be lost in a failover |
KEYS is fine on a small database | Small today, big tomorrow; use SCAN everywhere |
| Expired keys free memory immediately | Lazy + sampled active expiry; untouched expired keys linger |
volatile-lru protects my data | Keys without TTL are never evicted, so writes fail with OOM when none have a TTL |
| Deleting keys lowers RSS | jemalloc keeps freed pages; RSS stays near peak; defrag or restart to shrink |
| Cluster spreads a hot key | One key is in one slot on one master; use replicas, sharded keys or client-side caching |
| A Redis lock with TTL is safe for correctness | Pauses beyond the TTL and failover break it; add fencing tokens or use a consensus/DB lock |
| Valkey, Dragonfly and Memcached are drop-in Redis 8 | Protocol-compatible subsets; types, commands and licences differ |
| The 2024 licence change forbids using Redis in my product | Internal use is unaffected; restrictions target competing hosted offerings; AGPLv3 is an option since Redis 8 |
Cheat sheet
| Topic | Remember |
|---|---|
| Execution | One main thread runs every command; I/O threads only for sockets |
| Latency | Slow commands, big keys, fork, THP, swap; SLOWLOG, LATENCY DOCTOR, --intrinsic-latency |
| Atomic counter | INCR/HINCRBY/ZINCRBY, never GET+SET |
| Read-decide-write | Lua EVAL / Functions FCALL, or WATCH + MULTI/EXEC + retry |
| Round trips | Pipeline; TxPipeline for MULTI/EXEC |
| Keys | SCAN not KEYS; prefixes; hash tags in Cluster |
| Delete big | UNLINK, FLUSHALL ASYNC, lazyfree-* |
| Expiry | Lazy + active; TTL jitter; SET drops TTL unless KEEPTTL |
| Eviction | Cache: allkeys-lru/allkeys-lfu; durable data: noeviction |
| Memory | listpack/intset when small; OBJECT ENCODING, MEMORY USAGE; provision for peak RSS |
| Persistence | RDB + AOF everysec with RDB preamble; always only if you pay for it |
| Replication | Asynchronous; PSYNC partial resync; WAIT narrows, does not close, the loss window |
| HA | ≥ 3 Sentinels on separate hosts; quorum detects, majority authorizes |
| Cluster | 16384 slots, CRC16; MOVED permanent, ASK one-shot; CROSSSLOT without hash tags |
| Locks | SET NX PX + token + compare-and-delete; fencing tokens for correctness |
| Security | Private network, ACL users, -@dangerous, TLS, protected mode |
| Licence | Redis 8: RSALv2/SSPLv1/AGPLv3; Valkey: BSD |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Two clients run GET counter then SET counter <value+1>. What can go wrong and what are two fixes? Must-know
Answer
Answer: A lost update: both read the same value and one increment disappears. Use INCR, or a Lua script / WATCH + MULTI/EXEC with retry when logic is needed. See String and Transactions.
2 — You enable io-threads 4. Does a 2-second Lua script stop blocking other clients? Important
Answer
Answer: No. I/O threads only read, parse and write sockets; scripts and commands still run on the main thread. See I/O threads.
3 — p99 latency spikes every few minutes on a 30 GB instance with RDB save points. Name the likely cause and two mitigations. Important
Answer
Answer: fork() for BGSAVE (page-table copy on the main thread, worse with transparent huge pages). Disable THP, reduce save frequency or move persistence to a replica, use smaller shards. See Latency sources.
4 — A cache instance uses volatile-lru and starts returning OOM errors. Why? Must-know
Answer
Answer: Volatile policies evict only keys with a TTL; if most keys have none, nothing can be evicted and writes fail. Use allkeys-lru/allkeys-lfu or set TTLs. See Eviction policies.
5 — Inside MULTI, SET s x succeeds and LPUSH s y fails with WRONGTYPE. What is the value of s after EXEC? Important
Answer
Answer: "x": Redis does not roll back; only the failing command fails. See Transactions.
6 — What is the difference between MOVED and ASK? Important
Answer
Answer: MOVED says the slot permanently belongs to another node; the client updates its slot map. ASK is a one-time redirect during migration: send ASKING and the command to the target without updating the map. See Cluster.
7 — Why does MSET a 1 b 2 fail on Cluster and how do you make it work? Important
Answer
Answer: The keys hash to different slots (CROSSSLOT). Use a hash tag so both share a slot, e.g. {u}a and {u}b, or split the command per slot. See Cluster.
8 — A master acknowledges SET, then crashes, and Sentinel promotes a replica. Is the write guaranteed to exist? Does WAIT 1 100 change that? Important
Answer
Answer: No: replication is asynchronous. WAIT tells you how many replicas acknowledged, reducing the chance of loss, but the docs say acknowledged writes can still be lost during failover. See Replication.
9 — Why is a Redis TTL lock not enough to protect writes to a database for correctness, and what fixes it? Must-know
Answer
Answer: The holder can pause past the TTL, another client acquires the lock, and both write. A fencing token that increases on each acquisition and is checked by the database (WHERE fence < $token) rejects the stale writer. See Distributed lock.
10 — You deleted half of your keys but used_memory_rss did not drop. Is that a leak? Important
Answer
Answer: Usually not: jemalloc keeps freed memory for reuse; RSS reflects the peak and the fragmentation ratio looks high. Active defragmentation or a restart reclaims it. See Memory.
11 — Which Redis licences can you choose from for Redis 8, and what is Valkey? Good to know
Answer
Answer: RSALv2, SSPLv1 or AGPLv3. Valkey is the Linux Foundation fork of Redis 7.2.4 under BSD 3-clause, started in March 2024. See Licences and forks.
Glossary
| Term | Meaning |
|---|---|
| Event loop | The main thread's loop that multiplexes sockets (epoll/kqueue) and runs commands one at a time |
I/O threads (io-threads) | Optional helper threads for socket reads, RESP parsing and writes; not for command execution |
hz | Frequency of the server's background cron (expiry, eviction, stats), default 10 |
| Intrinsic latency | Latency of the host itself, measured with redis-cli --intrinsic-latency |
| SLOWLOG | Log of commands slower than slowlog-log-slower-than µs |
| LATENCY DOCTOR | Report from the latency monitor (enabled by latency-monitor-threshold) |
| Big key | A key whose size makes single operations on it slow (millions of elements or hundreds of MB) |
| Hot key | A key receiving a disproportionate share of traffic, pinned to one shard |
| Copy-on-write | After fork(), pages are duplicated only when the parent writes them |
| Transparent huge pages | Linux 2 MB pages that make copy-on-write after fork expensive; disable for Redis |
String / embstr / int / raw | The byte-string type and its three encodings |
| BITFIELD / BITOP / BITCOUNT | Bit-level operations on Strings (packed integers, set algebra, population count) |
Hash / HEXPIRE | Field-value map in one key; per-field TTL since 7.4 |
| List / quicklist | Double-ended list; stored as linked listpack nodes |
BLMOVE | Blocking atomic move between lists; basis of the reliable-queue pattern |
| Set / intset | Unique members; small all-integer sets use the intset encoding |
| Sorted Set / skiplist | Members ordered by score; large ones use a skiplist plus hash table |
| listpack | Compact serialized encoding for small hashes, lists, sets and sorted sets (7.0+, replaced ziplist) |
| HyperLogLog | Approximate distinct counter, ≤ 12 KB, 0.81% standard error |
| Geo | Coordinates stored as geohash scores in a Sorted Set; GEOSEARCH |
| Bloom / Cuckoo filter | Probabilistic membership; Cuckoo supports delete |
| Count-min sketch / Top-K / t-digest | Approximate frequency, heavy hitters, quantiles |
| Redis Stack | The former distribution bundling JSON, search, time series and probabilistic modules; folded into Redis 8 |
| JSON.SET / TS.ADD | Commands of the JSON and time series types |
Vector set (VADD/VSIM) | Redis 8 type for embeddings with HNSW similarity search |
| HNSW | Hierarchical Navigable Small World graph for approximate nearest neighbours |
| Active / lazy expiration | Background sampling of TTL keys vs deletion on access |
active-expire-effort | 1–10 knob trading CPU for fewer lingering expired keys |
| maxmemory / maxmemory-policy | Memory limit and the eviction rule applied at it |
| noeviction / allkeys-lru / allkeys-lfu / allkeys-lrm / volatile-ttl | Eviction policies (refuse writes; least recently used; least frequently used; least recently modified; shortest TTL) |
| maxmemory-samples | Keys sampled per eviction decision (approximate LRU/LFU) |
| jemalloc | Memory allocator bundled with Redis on Linux; enables active defrag |
| Fragmentation ratio | RSS divided by used memory |
| activedefrag | Background defragmentation of jemalloc memory |
| UNLINK / lazyfree | Non-blocking delete; background freeing of values |
| OBJECT ENCODING / MEMORY USAGE | Inspect a key's internal encoding and its bytes |
| RDB / BGSAVE | Point-in-time snapshot file; background save via fork |
| AOF / appendfsync / everysec | Append-only log of writes and its fsync policy |
| BGREWRITEAOF | Rewrites the AOF from memory to shrink it |
| aof-use-rdb-preamble | AOF base file in RDB format: hybrid persistence |
| Multi-part AOF | Base + incremental files + manifest (Redis 7.0+) |
| Replication ID / offset | Identity of a data history and position in it |
| PSYNC | Replica command to resume replication; partial or full resync |
Replication backlog (repl-backlog-size) | Master buffer that makes partial resync possible |
| Diskless replication | Full-sync RDB streamed over the socket without a disk file |
| WAIT | Blocks until N replicas acknowledge previous writes |
| min-replicas-to-write | Master refuses writes without enough fresh replicas |
| replica-read-only | Replicas reject writes with READONLY |
| Sentinel / quorum / SDOWN / ODOWN | HA monitors (port 26379); agreement threshold; subjectively / objectively down |
| Redis Cluster / hash slot / CRC16 | Built-in sharding; 16384 slots; slot = CRC16(key) mod 16384 |
| Hash tag | The {...} part of a key that alone is hashed to choose the slot |
| MOVED / ASK / ASKING | Permanent redirect; one-shot migration redirect; flag to accept it |
| Resharding / MIGRATING / IMPORTING | Moving slots between nodes and the slot states during the move |
| CROSSSLOT / TRYAGAIN / CLUSTERDOWN | Cluster errors: keys in different slots; retry during migration; slot unavailable |
| Cluster bus | Node-to-node gossip port (data port + 10000) |
| MULTI / EXEC / DISCARD / WATCH / EXECABORT | Transaction commands, optimistic check-and-set and the queue-error reply |
| EVAL / EVALSHA / NOSCRIPT | Lua script execution, by-SHA execution, and the cache-miss reply |
| Functions / FUNCTION LOAD / FCALL | Named, persisted Lua libraries (7.0+) |
| BUSY | Reply while a script exceeds busy-reply-threshold |
| Pipelining / RTT | Sending many commands before reading replies; network round-trip time |
| Client-side caching / CLIENT TRACKING | Local cache with server-pushed invalidation; default and broadcasting modes |
| RESP3 | Redis protocol v3 with push messages (used for invalidations) |
| SCAN / KEYS | Cursor-based incremental iteration vs blocking full listing |
| Keyspace notifications | Pub/Sub events for key changes (notify-keyspace-events) |
| Cache-aside / stampede / jitter | Lazy-loading cache; many misses at once; randomised TTL |
| Rate limiter | Fixed window, sliding log or token bucket implemented with atomic commands/scripts |
| Distributed lock / Redlock / fencing token | Mutual exclusion via Redis; majority-of-masters algorithm; monotonic number checked by storage |
| Leaderboard | Ranking built on a Sorted Set |
| Session store | Per-session Hash with sliding TTL |
| Pub/Sub | At-most-once fan-out to connected subscribers |
| ACL / ACL SETUSER | Users with command, key and channel permissions |
| Protected mode / requirepass / rename-command | Loopback-only default without password; legacy password; legacy command hiding |
| TLS | Encrypted client, replication and cluster-bus connections |
| MONITOR | Streams every command; costly (can halve throughput) |
| redis-benchmark | Bundled load generator (-c, -n, -d, -P, -t, --threads) |
--bigkeys / --hotkeys / --memkeys | redis-cli scans for biggest, hottest (LFU) and most memory-hungry keys |
| WRONGTYPE / OOM / READONLY / LOADING / MISCONF / MASTERDOWN | Common error replies (type mismatch, memory limit, replica write, loading data, failed save, replica cut off) |
| Memcached | Multi-threaded string cache, no persistence or structures |
| Valkey | Linux Foundation BSD fork of Redis 7.2.4 (March 2024) |
| Dragonfly | Multi-threaded Redis/Memcached-compatible store under the DSAL licence |
| KeyDB | Snap's multithreaded BSD fork of Redis |
| RSALv2 / SSPL / AGPL / BSD | Licences: source-available (Redis), source-available copyleft (MongoDB-style), OSI copyleft, permissive |
| go-redis / redis.Nil / TxPipeline | Official Go client; "key missing" sentinel error; pipeline wrapped in MULTI/EXEC |
| phpredis / predis | C extension vs pure-PHP Redis clients used by Laravel |
| Redis facade / Cache::lock / RateLimiter / Cache::flexible | Laravel APIs for raw commands, atomic locks, rate limiting, stale-while-revalidate |
References
- Redis docs: Data types, Probabilistic, Vector sets, Streams
- Redis docs: Transactions, Scripting with EVAL, Functions, Pipelining, Client-side caching, Pub/Sub
- Redis docs: Key eviction, EXPIRE, SCAN, OBJECT ENCODING, MONITOR
- Redis docs: Diagnosing latency issues, Memory optimization, Benchmarks (redis-benchmark)
- Redis docs: Persistence, Replication, Sentinel, Scale with Redis Cluster, Cluster specification
- Redis docs: Security, ACL, Distributed locks
- Redis source: redis.conf (unstable)
- Redis blog: Redis Adopts Dual Source-Available Licensing (20 March 2024), Redis is now available under the AGPLv3 (1 May 2025)
- Linux Foundation: Linux Foundation Launches Open Source Valkey Community (28 March 2024); valkey.io
- Dragonfly README and LICENSE.md; KeyDB README; Memcached README
- Martin Kleppmann, "How to do distributed locking", 8 February 2016. martin.kleppmann.com
- Laravel 13: Redis, Cache, Rate Limiting, Session, Queues
- go-redis: github.com/redis/go-redis, pkg.go.dev