Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Everything here runs for free on your own computer with Docker: one Redis container is enough until stage 4, where you start replicas and a small cluster.
Stage 1 · Beginner Redis fundamentals
Redis is a server that keeps data structures in memory and lets clients change them with small, fast commands. Learn the five core types well: picking the right one is most of what "knowing Redis" means, and every later topic builds on them.
What Redis is and when to use it
Redis is an in-memory data store. Instead of tables, it gives you keys that hold strings, hashes, lists, sets, sorted sets, streams, JSON documents and more, and commands that work on them in place: "add 50 points to Ravi's score", "push this job onto the queue", "give me the 10 newest items". Because the data lives in RAM and commands run one at a time on a single main thread, most operations take well under a millisecond and never see each other half-done.
That makes Redis the usual choice for caching, sessions, rate limits, leaderboards, counters, queues, real-time messaging and, more recently, vector search for AI apps. It is usually a companion to your main database, not a replacement: RAM is expensive, and although Redis can save to disk, it is not built for large data sets or complex queries across many tables.
A little history you will meet in docs and job ads: in 2024 Redis changed from the BSD licence to source-available licences, and the Linux Foundation forked the last BSD version as Valkey. In May 2025 Redis 8 added the open source AGPLv3 as a third licence option. For learning, both behave the same for everything in stages 1 and 2.
What to learn
- What "in-memory data structure store" means, and why it is fast
- Single-threaded command execution: every command is atomic, and one slow command blocks everyone
- Typical uses: cache, sessions, counters, rate limits, leaderboards, queues, pub/sub, vector search
- When Redis is the wrong tool: your main system of record, data much bigger than RAM, ad-hoc reporting queries
- Redis Open Source, Redis Software/Cloud and Valkey: what each one is
Free resources
Practice
Take an app you know (a shop, a news site, a chat app). List five things it could keep in Redis and five it should keep in its main database, with one sentence each on why. Note which Redis items could be lost in a crash without real harm.
Prerequisites: terminal, Docker and one language
You will run Redis in a container, poke at it with redis-cli and then call it from code. Be comfortable in a terminal, able to start containers, and able to write small programs in one language (the examples here use Python because it reads easily; Node.js, Java, Go and .NET clients work the same way). Skip this topic if that is already familiar.
What to learn
- Terminal basics: running commands, environment variables, reading output
- Docker: images, containers, published ports and volumes
- Docker Compose for starting several containers together
- One programming language well enough to install a package and write a small script
- JSON, and the idea of turning objects into strings and back
Free resources
Practice
Start any small container with a published port and a named volume, stop it, start it again and check that the data in the volume survived. You'll reuse the pattern for Redis persistence in stage 4.
Run Redis locally: Docker, redis-cli and Redis Insight
The quickest start is the official Docker image. It runs Redis Open Source with every built-in data type, including JSON, search and vector sets. redis-cli is the command-line client; it ships inside the image, so you don't need to install anything else. Redis Insight is a free desktop GUI for browsing keys, running commands and profiling, which helps a lot while learning.
# start Redis 8.10 in the background, port 6379
docker run -d --name redis -p 6379:6379 redis:8.10
# open the CLI inside the container
docker exec -it redis redis-cli
127.0.0.1:6379> PING
PONG
127.0.0.1:6379> INFO server
What to learn
- Start, stop and remove a Redis container; publish port 6379 only on your own machine
- Use redis-cli: interactive mode, one-shot commands,
HELP and command tab completion
- Read
INFO server and INFO memory to see the version and memory use
- Connect Redis Insight and browse keys
- Find any command in the command reference and read its time complexity
Free resources
Practice
Start Redis in Docker, run PING, INFO server and DBSIZE, then open the command reference for SET and list every option it takes. Connect Redis Insight to the same server and find the key you create in the next topic.
Keys and strings
Every value in Redis lives under a key. Keys are binary-safe strings; the convention is object-type:id:field, such as user:42:name, which keeps them readable and lets you scan by prefix. The simplest value type is the string: text, a number or any bytes up to 512 MB. Strings can also act as counters: INCR adds one atomically, so two clients can never both read 5 and write 6.
SET user:42:name "Asha"
GET user:42:name # "Asha"
SET user:42:name "Someone" NX # (nil): NX = only if missing
INCR page:home:views # 1, then 2, 3...
INCRBY cart:42:items 3 # 3
MSET color:1 red color:2 blue
MGET color:1 color:2 # "red" "blue"
TYPE user:42:name # string
SCAN 0 MATCH user:* COUNT 100 # walk keys safely
What to learn
- Key naming conventions with colons, and keeping keys short but readable
- SET with its options (NX, XX, GET, EX, PX, KEEPTTL), GET, MSET and MGET
- Atomic counters with INCR, INCRBY, DECR and INCRBYFLOAT
- DEL versus UNLINK, EXISTS, TYPE and RENAME
- Why
KEYS * blocks the server and SCAN doesn't
Free resources
Practice
Build a page-view counter in redis-cli: one key per page per day (views:/pricing:2026-11-05). Increment a few, read them back with MGET, then use SCAN with MATCH to list every page counted today. Explain why INCR is safe with many web servers and "GET, add one, SET" is not.
Expiry and TTLs
Any key can have a time to live. When it runs out, Redis deletes the key for you, which is what makes caches, sessions, one-time codes and rate-limit windows so easy. Set the TTL in the same command as the value (SET ... EX) so there's never a moment where the key exists without one. Since Redis 7.4 you can also expire individual fields inside a hash.
SET session:abc "u42" EX 1800 # expires in 30 minutes
TTL session:abc # 1800 (seconds left)
EXPIRE session:abc 3600 # extend it
PERSIST session:abc # remove the TTL
TTL session:abc # -1 = no expiry (-2 = no key)
SET otp:42 "917324" EX 300 NX # one-time code, 5 minutes
What to learn
- EX, PX, EXPIRE, PEXPIRE, EXPIREAT, TTL, PTTL and PERSIST
- What TTL returns: seconds left, -1 for no expiry, -2 for a missing key
- Which commands keep or clear a TTL (SET without KEEPTTL clears it)
- How expiry works: lazily when a key is touched, plus a background sweep
- Per-field expiry in hashes with HEXPIRE and HTTL
Free resources
Practice
Write a "verify your email" flow in redis-cli: store a 6-digit code with a 5-minute TTL and NX so it can't be overwritten, check the TTL counting down, and delete the key once the code is used. Then convert a TTL's expiry moment to a readable date.
Hashes
A hash is a small map of fields to values under one key, the natural fit for an object such as a user or a product. You can read or change one field without touching the rest, and counters work per field. Small hashes are stored in a compact encoding, so a hash per object is usually cheaper than a string key per field.
HSET user:42 name Asha plan pro visits 0
HGET user:42 plan # "pro"
HINCRBY user:42 visits 1 # 1
HGETALL user:42 # every field and value
HSET user:42 otp 123456
HEXPIRE user:42 60 FIELDS 1 otp # only this field expires
HTTL user:42 FIELDS 1 otp # 60
What to learn
- HSET, HGET, HMGET, HGETALL, HDEL, HEXISTS, HLEN and HINCRBY
- Hash or JSON-in-a-string: when partial updates matter
- HGETALL on huge hashes is slow; HSCAN walks them in pieces
- Field expiry: HEXPIRE, HPERSIST, HTTL and HGETEX
- Why small hashes use little memory (listpack encoding)
Free resources
Practice
Store three products as hashes (name, price, stock). Sell one unit with HINCRBY on stock, add a "sale_price" field that expires in 10 minutes, and use HMGET to read only the name and price for a product listing.
Lists
A list is an ordered sequence of strings, fast to push and pop at both ends. That makes it a good fit for "latest N items" feeds (push, then trim) and simple job queues: producers RPUSH, workers block on BLPOP or move jobs to a processing list with BLMOVE so a crashed worker doesn't lose them. Reading by index in the middle of a long list is slow, so don't treat it like an array.
LPUSH recent:42 "page:/pricing" "page:/docs"
LPUSH recent:42 "page:/blog"
LTRIM recent:42 0 49 # keep the newest 50
LRANGE recent:42 0 -1 # blog, docs, pricing
RPUSH jobs:email '{"to":"a@example.com"}'
LMOVE jobs:email jobs:email:processing LEFT RIGHT
What to learn
- LPUSH, RPUSH, LPOP, RPOP, LRANGE, LLEN and LTRIM
- Capped lists: push, then trim in the same pipeline
- Blocking pops (BLPOP, BLMOVE) for workers
- The reliable-queue pattern: move to a processing list, remove when done
- Why LINDEX and LSET in the middle of big lists are O(N)
Free resources
Practice
Open two redis-cli windows. In one, run BLPOP jobs:email 0 and watch it wait. In the other, RPUSH a job and see the first window return it instantly. Then rebuild it with BLMOVE and a processing list, and decide what should happen to a job that sits in "processing" for 10 minutes.
Sets
A set is an unordered collection of unique strings. Adding the same member twice does nothing, and checking membership is O(1), which fits tags, "who liked this", unique visitors (for small numbers) and deduplication. Sets can also be combined: intersection, union and difference, either returned or stored under a new key.
SADD tags:post:1 redis cache nosql
SADD tags:post:2 redis streams
SISMEMBER tags:post:1 cache # 1
SINTER tags:post:1 tags:post:2 # redis
SCARD tags:post:1 # 3
SUNIONCARD 2 tags:post:1 tags:post:2 # 4 (new in 8.10)
What to learn
- SADD, SREM, SISMEMBER, SMISMEMBER, SMEMBERS and SCARD
- SINTER, SUNION and SDIFF, and their STORE variants
- Random members with SRANDMEMBER and SPOP (raffles, sampling)
- SSCAN instead of SMEMBERS on big sets
- When a set gets too big and HyperLogLog or a Bloom filter is the better tool
Free resources
Practice
Model "follows" for four users with one set per user (following:asha). Find mutual follows with SINTER, "people you may know" with SDIFF, and pick a random winner from a set of contest entries with SPOP.
Sorted sets
A sorted set is a set where every member has a numeric score, kept in order at all times. It's the data type people miss most in other databases: leaderboards, "top 10 by price", priority queues, time-ordered indexes (use a timestamp as the score) and sliding-window rate limiters all fall out of it. Adds and rank lookups are O(log N).
ZADD leaderboard 1500 asha 1320 ravi 1710 mei
ZINCRBY leaderboard 50 ravi # 1370
ZRANGE leaderboard 0 2 REV WITHSCORES
# mei 1710, asha 1500, ravi 1370
ZREVRANK leaderboard ravi # 2 (0-based, highest first)
ZRANGE leaderboard 1400 +inf BYSCORE # asha, mei
What to learn
- ZADD (with NX, XX, GT, LT), ZINCRBY, ZSCORE and ZREM
- ZRANGE with REV, BYSCORE, BYLEX and LIMIT (it replaced ZREVRANGE and friends)
- ZRANK, ZREVRANK and ZCOUNT for "where am I?" questions
- ZPOPMIN, BZPOPMIN and timestamps as scores for delayed jobs
- Trimming with ZREMRANGEBYRANK and ZREMRANGEBYSCORE
Free resources
Practice
Build a game leaderboard: add 20 players with random scores, show the top 10, show one player's rank and the 2 players above and below them, and keep a separate weekly board whose key expires after 8 days. Then build a delayed-job queue where the score is the Unix time the job should run.
Am I ready? Stage 1 quiz
Ten web servers each count page views by running GET views, adding one in code, then SET views. Views go missing. What is the fix?
- Use MSET instead of SET
- Give the key a TTL
- Use
INCR views, which reads and writes in one atomic command - Run SCAN before every SET
Two servers can both read 5 and write 6. INCR runs as one command on Redis's single main thread, so no update is lost.
You need the top 10 players by score, updated as games finish. Which type fits best?
- A sorted set: ZINCRBY on each game, ZRANGE 0 9 REV to read
- A list sorted in your application code
- A set of player names
- One string key per player
Sorted sets keep members ordered by score at all times, so the top 10 is one cheap command.
What does TTL session:abc return when the key exists but has no expiry?
- 0
- -2
- The number of seconds since it was created
- -1
-1 means "exists, no expiry"; -2 means the key doesn't exist.
Why should you avoid KEYS user:* on a production server?
- It returns keys in random order
- It walks every key in one go and blocks all other clients until it finishes
- It deletes the keys it matches
- It only works on hashes
With millions of keys, KEYS can block Redis for seconds. SCAN returns the same keys in small batches with a cursor.
You store a user object and often change only their plan. Which is the most natural choice?
- A list with one element per field
- A set of "field=value" strings
- A hash, so HSET can change one field
- A sorted set scored by field number
Hashes map fields to values under one key and let you read or update a single field.
Stage 2 · Beginner → Intermediate Redis in your applications
Now use Redis from code. Most real Redis bugs are not in Redis: they're stale caches, race conditions between two app servers, locks that expire too early and queues that lose jobs when a worker dies. Every topic here comes with the failure you should test, not just the happy path.
Client libraries and connections
Every popular language has an official or well-maintained client: redis-py (Python), node-redis and ioredis (Node.js), Jedis and Lettuce (Java), go-redis (Go) and StackExchange.Redis / NRedisStack (.NET). They all speak RESP, Redis's simple text protocol. What matters in production is the boring part: one client per process with a connection pool (or a multiplexed connection), sensible timeouts, retries, and TLS and a password outside your laptop.
import redis
# One client per process: it keeps a pool of connections.
r = redis.Redis(host="localhost", port=6379,
decode_responses=True, # str instead of bytes
socket_timeout=2, socket_connect_timeout=2)
r.set("greeting", "hello", ex=60)
print(r.get("greeting")) # hello
r.hset("user:42", mapping={"name": "Asha", "plan": "pro"})
print(r.hgetall("user:42")) # {'name': 'Asha', 'plan': 'pro'}
What to learn
- Install and connect the client for your language; read the connection URL format
- Connection pools versus multiplexing, and why you create the client once
- Timeouts, retries with backoff, and what happens when Redis restarts
- Bytes versus strings (decode_responses and its equivalents)
- RESP2 and RESP3, at the level of "what does my client speak?"
Free resources
Practice
Write a tiny API (any framework) with one endpoint that increments and returns a visit counter in Redis. Read the connection URL from an environment variable. Stop the Redis container while the API runs, call the endpoint, and make sure it returns a clean error within 2 seconds instead of hanging; start Redis again and check it recovers without a restart.
Data modelling and key design
Redis has no schema and no joins, so you design keys around the questions your app asks. A common shape is a hash per object (product:7) plus extra structures that act as indexes: a sorted set of product ids by price, a set of ids per category. Think about how keys grow: a single key with ten million members is slow to read, delete and copy, and in a cluster it lives on one node.
What to learn
- Namespaced key names and a written list of key patterns for your app
- Choosing the type from the access pattern, not from the data
- Secondary indexes by hand with sets and sorted sets, and keeping them in sync
- Avoiding "big keys" and "hot keys" by splitting data (per day, per user, per shard)
- Versioning keys (
v2:user:42) so a format change doesn't break old readers
Free resources
Practice
Design the keys for a small blog: posts, comments per post, tags, "latest 20 posts", "most liked posts this week" and a per-user feed. Write each key pattern, its type, the commands that read and write it, and when it expires. Then implement "list posts tagged redis, newest first".
Caching patterns
The most common Redis job. In cache-aside the app checks Redis first, and on a miss reads the database and stores the result with a TTL. Writes go to the database and then delete the cache key, so the next read fills it again. The hard parts are what to do when the cache is stale, and what happens when a popular key expires and a thousand requests hit the database at once (a cache stampede). Random jitter on TTLs, a short lock around the refill, or serving stale data while one request refreshes are the usual fixes.
import json, random
import redis
r = redis.Redis(decode_responses=True)
def get_product(product_id):
key = f"cache:product:{product_id}"
cached = r.get(key)
if cached is not None: # hit
return json.loads(cached)
product = load_product_from_db(product_id) # miss
ttl = 300 + random.randint(0, 60) # jitter
r.set(key, json.dumps(product), ex=ttl)
return product
def update_price(product_id, price):
# ...write to the database first, then:
r.delete(f"cache:product:{product_id}")
What to learn
- Cache-aside, read-through, write-through and write-behind, and their trade-offs
- Invalidation: delete on write, short TTLs, and why "update the cache on write" races
- Stampedes: TTL jitter, a refill lock, early refresh
- Caching "not found" results so missing ids don't hammer the database
- Measuring hit rate (keyspace_hits and keyspace_misses in INFO stats)
Free resources
Practice
Put a cache-aside layer in front of a slow endpoint (add a 200 ms sleep to fake the database). Load-test it before and after, record the hit rate, then make the key expire while 50 requests are in flight and count how many reach the "database". Add a refill lock and measure again.
Pipelining and round trips
A Redis command often takes microseconds, but the network round trip takes far longer, so sending 1,000 commands one by one is slow even on a fast server. Pipelining sends many commands without waiting for each reply, then reads all the replies together. It is not atomic (other clients' commands can run in between); for that you want a transaction or a script. Multi-key commands such as MGET and MSET are another way to cut round trips.
import redis
r = redis.Redis(decode_responses=True)
# 1,000 commands, one network round trip per batch.
pipe = r.pipeline(transaction=False)
for i in range(1000):
pipe.set(f"item:{i}", i, ex=3600)
results = pipe.execute()
print(len(results), results[0]) # 1000 True
What to learn
- Round-trip time versus command time, and why it dominates
- Pipelines in your client, and batching very large ones (a few thousand commands each)
- Multi-key commands: MGET, MSET, HMGET, and variadic SADD or ZADD
- Pipelining is not atomic; transactions and scripts are
- Benchmarking with redis-benchmark and its pipeline option
Free resources
Practice
Time 10,000 SET commands three ways: one by one, in one pipeline, and in pipelines of 500. Repeat with Redis on another machine (or add network delay with tc) and see the gap grow.
Transactions: MULTI, EXEC and WATCH
MULTI starts queueing commands and EXEC runs them all at once, with no other client's command in between. There is no rollback: if one command fails at run time (say, INCR on a non-number), the others still run. For "check, then change" logic you add WATCH: if a watched key changes before EXEC, the whole transaction is cancelled and you retry. This is optimistic locking.
SET stock:sku1 10
WATCH stock:sku1
GET stock:sku1 # "10": enough stock, go on
MULTI
DECRBY stock:sku1 1 # QUEUED
RPUSH orders:new sku1 # QUEUED
EXEC # 9, 1 (or nil if stock changed)
What to learn
- MULTI, EXEC and DISCARD, and what "atomic" means here
- No rollback: errors at queue time versus errors at run time
- WATCH for optimistic locking, and the retry loop around it
- Transactions in your client (pipelines with transaction=True)
- When a Lua script or function is simpler than WATCH
Free resources
Practice
Implement "buy one item" with WATCH and a retry loop: only decrement stock when it's above zero. Start 20 buyers in parallel against a stock of 5 and prove you never sell more than 5. Then try the same without WATCH and watch it oversell.
Lua scripts and Redis functions
When several commands must run as one step with logic in between, run them inside Redis. EVAL sends a Lua script that runs atomically: no other command runs until it finishes. Pass key names in KEYS and values in ARGV (Redis Cluster needs to know the keys). Functions (Redis 7+) are the managed version: you load a library once with FUNCTION LOAD, it survives restarts and replicates, and you call it by name with FCALL.
# delete the lock only if it still holds my token
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end" 1 lock:report token-7f3a
What to learn
- EVAL, EVALSHA and script caching; register_script and its equivalents in clients
- KEYS versus ARGV, and why every key a script touches must be passed in
- Scripts block the server: keep them short; SCRIPT KILL and busy timeouts
- FUNCTION LOAD, FCALL and libraries, and when to prefer them over EVAL
- Error handling with redis.call versus redis.pcall
Free resources
Practice
Rewrite the "buy one item" transaction from the previous topic as a Lua script that checks and decrements stock in one step and returns 1 or 0. Then move it into a function library with FUNCTION LOAD, restart Redis with persistence on, and check FCALL still works.
Pub/sub and keyspace notifications
Pub/sub sends a message to everyone subscribed to a channel right now. It's fire-and-forget: nothing is stored, so a subscriber that is offline or slow simply misses messages. That's fine for live updates (chat typing indicators, "refresh your cache" signals, fanning WebSocket messages out across servers) and wrong for anything that must not be lost; use streams for that. Keyspace notifications publish events such as "this key expired" on special channels.
What to learn
- SUBSCRIBE, PUBLISH, PSUBSCRIBE (patterns) and UNSUBSCRIBE
- At-most-once delivery: what is lost when a subscriber disconnects
- A subscribed connection can't run normal commands; use a separate connection
- Sharded pub/sub (SSUBSCRIBE, SPUBLISH) in Redis Cluster
- Keyspace notifications (notify-keyspace-events) and their limits
Free resources
Practice
Build a two-instance WebSocket or SSE chat where each server subscribes to chat:room1 and publishes the messages it receives, so users on different servers see each other. Stop one subscriber for 10 seconds and list which messages it missed.
Streams and consumer groups
A stream is an append-only log of entries, each with an id (a timestamp plus a sequence number) and a few fields. Unlike pub/sub, entries are kept, so readers can catch up after a restart. Consumer groups split the work: each entry goes to one consumer in the group, stays "pending" until that consumer acknowledges it with XACK, and can be claimed by another consumer if the first one dies. It's a small, simple version of the Kafka model that lives inside Redis.
XADD orders * order_id 42 status paid
XGROUP CREATE orders billing 0
XREADGROUP GROUP billing worker-1 COUNT 10 STREAMS orders >
XACK orders billing 1793861697127-0
XPENDING orders billing # what is still unacked
# take over entries idle for 60 s (a dead worker's)
XAUTOCLAIM orders billing worker-2 60000 0-0 COUNT 10
What to learn
- XADD, XRANGE, XREAD and entry ids; capping with MAXLEN or MINID
- Consumer groups: XGROUP CREATE, XREADGROUP with the > id, XACK
- The pending entries list, XPENDING, XCLAIM and XAUTOCLAIM for dead workers
- At-least-once delivery: make handlers idempotent
- Streams versus lists versus pub/sub versus Kafka
Free resources
Practice
Build a "send welcome email" worker: the sign-up endpoint does XADD, two workers in one consumer group read and XACK. Kill one worker after it reads but before it acks, and have the other pick up its entries with XAUTOCLAIM. Make the handler idempotent so a retried entry doesn't send two emails.
Rate limiting
Redis is the standard place to count requests across many app servers. The simplest limiter is a fixed window: one counter per client per minute, created with INCR and given a TTL. It allows bursts at the window edge, so for smoother limits use a sliding window (a sorted set of request timestamps, or two weighted counters) or a token bucket in a Lua script. Whatever you choose, do the check and the update atomically.
import time
import redis
r = redis.Redis(decode_responses=True)
def allowed(client_ip, limit=100, window=60):
bucket = int(time.time() // window)
key = f"rl:{client_ip}:{bucket}"
pipe = r.pipeline() # MULTI ... EXEC
pipe.incr(key)
pipe.expire(key, window, nx=True) # set the TTL only once
count, _ = pipe.execute()
return count <= limit
What to learn
- Fixed window with INCR plus EXPIRE ... NX
- Sliding window log with a sorted set (ZADD, ZREMRANGEBYSCORE, ZCARD)
- Token bucket and leaky bucket in a Lua script
- Answering 429 Too Many Requests with a Retry-After header
- Choosing the key: per IP, per user, per API key, per route
Free resources
Practice
Add a limiter of 5 login attempts per minute per IP to an API. Hit it with the load tester and check you get exactly 5 successes and then 429s with Retry-After. Then replace it with a sliding-window version and show the burst at the window edge is gone.
Distributed locks
A lock in Redis is a key: SET lock:report <random-token> NX PX 30000 succeeds for exactly one client, and the TTL frees it if that client crashes. Release it with a script that deletes the key only if it still holds your token, or you may delete someone else's lock. The catch: if your process pauses longer than the TTL (a long garbage-collection pause, a slow network), the lock expires and two workers run at once. Use Redis locks for efficiency ("don't do this work twice"), and protect correctness-critical data with fencing tokens or database constraints as well.
import uuid
import redis
r = redis.Redis(decode_responses=True)
RELEASE = r.register_script("""
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
""")
token = str(uuid.uuid4())
if r.set("lock:report", token, nx=True, px=30000):
try:
build_report()
finally:
RELEASE(keys=["lock:report"], args=[token])
What to learn
- SET NX PX with a random token, and a compare-and-delete release script
- Choosing the TTL, and extending a lock while long work runs
- The Redlock algorithm across several independent Redis servers
- Why pauses and clock jumps break lock safety, and what fencing tokens are
- When to use your database (row locks, unique constraints) instead
Free resources
Practice
Run a nightly-report job on three workers so that only one builds it. Then add a 40-second sleep inside the lock (longer than its 30-second TTL), and show that a second worker starts while the first is still running. Fix it by extending the lock while working, and write down what still could go wrong.
Am I ready? Stage 2 quiz
In cache-aside, what should your app do after it updates a product's price in the database?
- Nothing: the TTL will fix it eventually, and that's always fine
- Delete the cached product key so the next read loads the new value
- Read the cache, change the price in it and write it back
- Flush the whole cache with FLUSHALL
Deleting is simple and safe: the next reader refills the cache from the database. Updating the cached copy can race with other readers and writers.
Inside MULTI ... EXEC, the second of three commands fails at run time (INCR on a string that isn't a number). What happens?
- All three are rolled back
- EXEC returns nil and nothing runs
- Redis stops after the failing command
- The other two commands still run; the reply for the second is an error
Redis transactions are atomic (nothing interleaves) but have no rollback. Only WATCH conflicts or queue-time errors cancel the whole thing.
A worker reads a stream entry with XREADGROUP and crashes before XACK. What happens to the entry?
- It stays in the group's pending list, and another consumer can take it with XCLAIM or XAUTOCLAIM
- It's deleted from the stream
- It's lost because streams are fire-and-forget
- Every consumer in the group receives it again automatically
Entries stay pending until acknowledged, which is what gives streams at-least-once delivery.
Why does a lock release script compare the stored token before deleting?
- Because DEL is slow
- To make the lock work in Redis Cluster
- If my lock already expired and another client took it, a plain DEL would delete their lock
- To reset the TTL
Only the owner should release a lock. Comparing and deleting in one script makes that check atomic.
You send 5,000 SET commands from an app server 2 ms away from Redis. What is the biggest easy speed-up?
- Switching to Lua for every SET
- Pipelining, so you don't wait one round trip per command
- Adding more RAM to Redis
- Using KEYS to check them first
5,000 round trips of 2 ms is 10 seconds. Pipelined, it's a handful of round trips.
Stage 3 · Intermediate Beyond the core types: JSON, search and vectors
Since Redis 8, Redis Open Source includes what used to be separate modules: JSON documents, a query engine with full-text, numeric, tag, geo and vector search, time series and probabilistic structures, plus the newer vector sets. Learn what each is for, so you can reach for them before building something by hand.
Bitmaps, HyperLogLog and geospatial
Three compact tools for big numbers of things. A bitmap is a string you treat as bits: one bit per user id per day stores "who logged in" for ten million users in about 1.2 MB. HyperLogLog counts unique items (visitors, search terms) in 12 KB per counter with about 0.81% error, no matter how many items. Geospatial indexes store longitude and latitude in a sorted set and answer "what's within 5 km of here?".
SETBIT login:2026-11-05 42 1 # user 42 logged in today
BITCOUNT login:2026-11-05 # how many logged in
PFADD visitors:2026-11-05 u1 u2 u3 u2
PFCOUNT visitors:2026-11-05 # 3 (approximate)
GEOADD shops 73.8567 18.5204 pune 72.8777 19.0760 mumbai
GEOSEARCH shops FROMLONLAT 73.85 18.52 BYRADIUS 200 km ASC WITHDIST
What to learn
- SETBIT, GETBIT, BITCOUNT, BITOP and BITPOS; bitfields for packed small counters
- PFADD, PFCOUNT and PFMERGE, and the error you accept
- GEOADD, GEOSEARCH, GEODIST, and that longitude comes first
- Choosing between a set, a bitmap and a HyperLogLog by size and accuracy
Free resources
Practice
For 100,000 fake users, record daily logins for a week as bitmaps, then answer "who logged in every day this week" with BITOP AND and "how many unique users this week" with both a set and a HyperLogLog. Compare their memory with MEMORY USAGE.
Probabilistic structures: Bloom, Cuckoo, Top-K and more
These answer questions about huge data sets in a small, fixed amount of memory, in exchange for a known chance of being slightly wrong. A Bloom filter says "definitely not seen" or "probably seen" (great for "is this username taken?" before hitting the database). A Cuckoo filter is similar but supports deletes. Count-min sketch estimates how often each item appears, Top-K tracks the most frequent items, and t-digest estimates percentiles such as p99 latency.
BF.RESERVE usernames 0.001 1000000 # 0.1% false positives, 1M items
BF.ADD usernames asha
BF.EXISTS usernames asha # 1 (probably)
BF.EXISTS usernames zed # 0 (definitely not)
TOPK.RESERVE trending 3
TOPK.ADD trending redis kafka redis go redis kafka
TOPK.LIST trending # redis, kafka, go
What to learn
- False positives versus false negatives, and which each structure allows
- Sizing a Bloom filter: capacity and error rate
- Cuckoo filters when you need deletes
- Count-min sketch and Top-K for "heavy hitters"
- t-digest for percentiles over a stream of numbers
Free resources
Practice
Load 1 million fake usernames into a Bloom filter sized for 0.1% error. Test 100,000 names you never added and count the false positives: is it close to 100? Then feed fake API latencies into a t-digest and read p50, p95 and p99.
JSON documents
The JSON type stores a whole document under one key and lets you read and change parts of it with JSONPath, atomically, without fetching and rewriting the whole thing. It's the natural choice for nested objects (a user with addresses and preferences, a product with variants), and combined with the query engine in the next topic it turns Redis into a fast document store.
JSON.SET user:1 $ '{"name":"Asha","city":"Pune","age":31,"skills":["go"]}'
JSON.GET user:1 $.skills # [["go"]]
JSON.ARRAPPEND user:1 $.skills '"kafka"'
JSON.NUMINCRBY user:1 $.age 1 # [32]
What to learn
- JSON.SET, JSON.GET, JSON.MGET, JSON.DEL and JSON.TYPE
- JSONPath:
$, child and array paths, wildcards and filters
- Atomic partial updates: JSON.NUMINCRBY, JSON.ARRAPPEND, JSON.STRAPPEND
- JSON type versus a JSON string versus a hash
- Using JSON from your client library
Free resources
Practice
Store a shopping cart as one JSON document per user. Add and remove items, change quantities with JSON.NUMINCRBY, and read just the item count with a path. Compare it with the same cart stored as a JSON string, and list what becomes harder.
The query engine: indexes, search and aggregation
The Redis Query Engine (the FT.* commands, formerly RediSearch) builds secondary indexes over hashes or JSON documents with a given key prefix and keeps them updated automatically as you write. You can then search by full text, tags, numeric ranges, geography and vectors, sort and page results, and run aggregations (group, count, sum) without hand-built index sets.
FT.CREATE idx:users ON JSON PREFIX 1 user: SCHEMA
$.name AS name TEXT
$.city AS city TAG
$.age AS age NUMERIC SORTABLE
FT.SEARCH idx:users "@city:{Pune} @age:[25 40]" RETURN 2 name age
FT.AGGREGATE idx:users "*" GROUPBY 1 @city REDUCE COUNT 0 AS users
# (type FT.CREATE on one line in redis-cli)
What to learn
- FT.CREATE on hashes or JSON, prefixes, and field types TEXT, TAG, NUMERIC, GEO and VECTOR
- Query syntax: full text,
@tag:{a|b}, numeric ranges, negation and prefixes
- SORTBY, LIMIT, RETURN and highlighting
- FT.AGGREGATE with GROUPBY, REDUCE, APPLY and FILTER
- FT.INFO, index size, and changing a schema with FT.ALTER or aliases
Free resources
Practice
Load 10,000 fake products as JSON (name, description, category, price, rating). Index them and build: search by words in the description, filter by category and price range, sort by rating, page 20 at a time, and an aggregation of average price per category. Time a query, then add 10,000 more products and time it again.
Vector search and vector sets
An embedding turns text or an image into a list of numbers so that similar things end up close together. Redis can find the nearest vectors to a query vector in two ways: a VECTOR field in a query engine index (FLAT for exact search, HNSW for fast approximate search) that you can combine with tag and numeric filters, or the newer vector set type, a sorted-set-like structure where VADD adds an element with its vector and VSIM returns the most similar ones. This is the base of semantic search, recommendations and retrieval for AI apps.
VADD docs:vec VALUES 3 0.1 0.9 0.2 doc:1
VADD docs:vec VALUES 3 0.8 0.1 0.1 doc:2
VADD docs:vec VALUES 3 0.2 0.8 0.3 doc:3
VSIM docs:vec VALUES 3 0.15 0.85 0.25 WITHSCORES COUNT 2
# doc:3 0.9975, doc:1 0.9972 (real embeddings have
# hundreds of dimensions, made by an embedding model)
What to learn
- What embeddings are and where they come from (an embedding model or API)
- Distance metrics: cosine, inner product and Euclidean (L2)
- FLAT versus HNSW indexes: exact versus approximate, memory and speed
- Vector fields with filters in FT.SEARCH (hybrid queries)
- Vector sets: VADD, VSIM, VCARD, VREM and quantisation options
Free resources
Practice
Embed 200 short FAQ answers with any free embedding model, store them as hashes with a VECTOR field plus a "category" tag, and build a search that returns the 3 closest answers to a question, optionally filtered by category. Then store the same vectors in a vector set and compare the code and the results.
Time series
The time series type stores (timestamp, number) samples efficiently, with retention, labels for querying many series at once, and compaction rules that roll raw data up into averages per minute or hour automatically. It suits metrics, IoT sensors and prices when you already run Redis and don't want a separate time series database.
What to learn
- TS.CREATE with RETENTION and LABELS, TS.ADD and TS.MADD
- TS.RANGE with AGGREGATION (avg, max, count) and buckets
- TS.CREATERULE for downsampling into another series
- TS.MRANGE with label filters across many series
- Duplicate policies and out-of-order samples
Free resources
Practice
Simulate 5 temperature sensors sending a reading every second for an hour. Keep raw data for 1 day and per-minute averages for 30 days with compaction rules, and query "average temperature per 5 minutes for all sensors in room 1".
Client-side caching
Even a sub-millisecond Redis call is slower than reading your own memory. With client-side caching, the client keeps hot values locally and Redis tells it when one of them changes (CLIENT TRACKING, using RESP3 push messages), so the local copy is dropped instead of going stale. Several official clients support it with a single option. It helps most for small, very hot, rarely changing keys such as feature flags or configuration.
What to learn
- CLIENT TRACKING in default and broadcasting (BCAST) modes
- Invalidation messages and RESP3
- Turning it on in your client and limiting the local cache size
- Which keys benefit, and what happens on reconnects
Free resources
Practice
Turn on client-side caching in your client for a "feature flags" hash. Read it 100,000 times and count how many requests reach Redis (watch INFO commandstats). Change a flag from redis-cli and confirm the app sees the new value at once.
Redis for AI apps: RAG, semantic caching and memory
AI apps use Redis in three main ways. As the vector store for retrieval-augmented generation (RAG): find the chunks of your documents closest to a question and pass them to the model. As a semantic cache: if a new question is close enough to one answered before, return the stored answer and skip a slow, paid model call. And as memory for chat sessions and agents: recent messages in a list or stream, long-term facts as vectors. RedisVL is the official Python library that wraps these patterns.
What to learn
- Chunking documents, storing chunk text, metadata and vectors together
- A RAG query: embed the question, run a filtered vector search, build the prompt
- Semantic caching: the similarity threshold and the risk of wrong cache hits
- Chat history and agent memory with TTLs per session
- RedisVL for indexes, queries and caches from Python
Free resources
Practice
Build a small "ask the docs" bot over 20 pages of any documentation: chunk, embed and store in Redis, answer questions with the top 4 chunks, and add a semantic cache. Ask 10 rephrased versions of the same question and log which ones hit the cache; tune the threshold until no wrong answers come back.
Am I ready? Stage 3 quiz
You want an exact-enough count of unique daily visitors for 50 million visits, using as little memory as possible. Which fits?
- A set of visitor ids
- A list of visitor ids
- A HyperLogLog
- A sorted set scored by time
A HyperLogLog uses at most 12 KB per counter, with about 0.81% standard error, however many visitors there are.
A Bloom filter answers "yes" for a username. What do you know?
- The name was probably added; check the database to be sure
- The name was definitely added
- The name was definitely never added
- Nothing: Bloom filters only count items
Bloom filters can give false positives but never false negatives. "No" is certain; "yes" means "probably".
What does FT.CREATE idx:users ON JSON PREFIX 1 user: ... do with keys added later under user:?
- Nothing: you must call FT.CREATE again
- It indexes them only after a restart
- It copies them into a separate index database you must sync
- It indexes them automatically as they are written
The index follows every write to matching keys, so queries see new and changed documents straight away.
Why choose an HNSW vector index over FLAT for 5 million vectors?
- HNSW always returns the exact nearest neighbours
- HNSW is approximate but much faster on large sets, at the cost of extra memory
- FLAT doesn't support cosine distance
- HNSW stores no vectors at all
FLAT compares the query with every vector; HNSW walks a graph to find very close (usually the closest) neighbours far faster.
You need to change one field deep inside a nested document without race conditions. Which storage makes that easiest?
- A JSON string under a plain key, read and rewritten by the app
- A list with one element per field
- The JSON type, updated with JSON.SET and a JSONPath
- A set of "path=value" members
The JSON type changes just the addressed part, atomically, inside Redis.
Stage 4 · Advanced Redis in production
Running Redis well is mostly about memory, durability and failure. Decide what happens when memory fills up, how much data you can afford to lose in a crash, what happens when the primary dies, and how you'll know before your users do. Build a small replicated setup and a 6-node cluster in Docker Compose, and break them on purpose.
Memory and eviction
All your data has to fit in RAM, so memory is the first thing to plan. Set maxmemory so Redis never pushes the machine into swap, and pick a maxmemory-policy for what happens when it's full: a pure cache should evict (allkeys-lru or allkeys-lfu), while a store you can't lose data from should refuse writes (noeviction, the default) and alert you. Learn to find what's using the memory: big keys, keys without TTLs and fragmentation.
CONFIG SET maxmemory 100mb
CONFIG SET maxmemory-policy allkeys-lru
INFO memory # used_memory, fragmentation
MEMORY USAGE user:42 # bytes for one key
OBJECT ENCODING user:42 # listpack, hashtable...
# from your shell: sample the keyspace for big keys
redis-cli --bigkeys
redis-cli --memkeys
What to learn
- maxmemory and every maxmemory-policy (noeviction, allkeys-lru/lfu, volatile-*, random)
- INFO memory: used_memory, used_memory_rss, mem_fragmentation_ratio and peak
- MEMORY USAGE, OBJECT ENCODING and the compact encodings for small values
- Finding big keys and keys without TTLs; deleting big keys safely with UNLINK
- Memory for replication buffers, client buffers and forks during saves
Free resources
Practice
Set maxmemory to 50 MB and fill Redis with keys until it's full, once with noeviction (watch the OOM errors) and once with allkeys-lru (watch evicted_keys in INFO stats grow). Then create one hash with a million fields, find it with --bigkeys and remove it with UNLINK.
Persistence: RDB and AOF
Redis keeps data in memory but can save it to disk in two ways. RDB snapshots write the whole data set every so often: compact and fast to restart from, but you lose everything since the last snapshot. The AOF (append-only file) logs every write; with appendfsync everysec you lose at most about a second of writes. Most setups that care about data use both. A pure cache can turn persistence off entirely. Either way, copy the files somewhere else: persistence is not a backup.
# redis.conf
save 3600 1 300 100 60 10000 # the default RDB schedule
appendonly yes # off by default
appendfsync everysec # fsync once a second
dir /data # mount a volume here
What to learn
- RDB snapshots: save rules, BGSAVE, and the fork that makes them
- AOF: appendfsync always / everysec / no, and what each can lose
- AOF rewrites and the multi-part AOF directory
- Restart behaviour: which file is loaded and how long it takes
- Backups: copying RDB files off the server and testing a restore
Free resources
Practice
Run Redis in Docker with a volume. Write a counter every 10 ms from a script, then kill the container with docker kill (no clean shutdown) and count how many writes were lost: first with RDB only, then with AOF everysec. Finally restore yesterday's RDB into a fresh container.
Replication and Sentinel
A replica keeps a copy of a primary's data, streamed over the network. Replicas give you read scaling and a warm standby, but replication is asynchronous: if the primary dies, the last writes may not have reached the replica yet (WAIT narrows the gap but doesn't remove it). Redis Sentinel watches the primary, agrees with other Sentinels that it is really down, promotes a replica and tells clients the new address. Run at least three Sentinels on separate machines.
What to learn
- REPLICAOF, full and partial resync, the replication backlog and INFO replication
- Asynchronous replication and what you can lose on failover; the WAIT command
- Read replicas and stale reads
- Sentinel: quorum, failover, and Sentinel-aware clients
- Testing a failover end to end with your app connected
Free resources
Practice
With Docker Compose, run one primary, two replicas and three Sentinels. Point a small app at Sentinel, write continuously, stop the primary and time how long writes fail until a replica is promoted. Count writes lost in the failover, then bring the old primary back and check it rejoins as a replica.
Redis Cluster and sharding
When data or traffic outgrows one server, Redis Cluster splits the keyspace into 16,384 hash slots spread over several primaries, each with its own replicas and automatic failover. A key's slot is CRC16 of the key modulo 16384, and clients learn which node owns which slot, following MOVED and ASK redirects. The big rule for developers: commands and scripts that touch several keys only work if all the keys are in the same slot, which you arrange with hash tags: only the part inside {…} is hashed.
# needs a server started with cluster-enabled yes
CLUSTER KEYSLOT user:42 # 15880
CLUSTER KEYSLOT {user:42}:cart # 15880 (hash tag)
CLUSTER KEYSLOT {user:42}:profile # 15880: same slot
CLUSTER KEYSLOT user:43 # 11817: another slot
# from your shell: 3 primaries + 3 replicas
redis-cli --cluster create 10.0.0.1:6379 10.0.0.2:6379 \
10.0.0.3:6379 10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379 \
--cluster-replicas 1
What to learn
- Hash slots, how keys map to them, and cluster-aware clients
- MOVED and ASK redirects, and why your client must handle them
- Hash tags for multi-key commands, transactions and scripts (CROSSSLOT errors)
- Adding nodes and resharding slots while the cluster serves traffic
- Cluster failover, and when Sentinel with one primary is simpler
Free resources
Practice
Create a 6-node cluster (3 primaries, 3 replicas) in Docker Compose. Run your stage-2 app against it and fix every CROSSSLOT error with hash tags. Add a 4th primary, reshard 1,000 slots to it while writing, then stop a primary and watch its replica take over.
Security: ACLs, TLS and network exposure
Redis was designed to sit on a trusted private network, and thousands of servers left open on the internet have been wiped or turned into crypto miners. The basics: never expose port 6379 publicly, bind to private interfaces, require authentication, and use ACL users so each app can only run the commands and touch the keys it needs. Turn on TLS when traffic leaves a trusted network. Note that the official Docker image turns protected mode off, so a published port is reachable by anyone who can reach the host.
# app user: password, only app:* keys and channels,
# read and write commands, nothing dangerous
ACL SETUSER app on >s3cret-Pa55 ~app:* &app:* +@read +@write -@dangerous
ACL GETUSER app
AUTH app s3cret-Pa55
ACL WHOAMI # "app"
What to learn
- bind, protected-mode and firewalls; never on a public IP
- ACL users: passwords, key patterns, channel patterns and command categories
- Disabling the default user, and an ACL file instead of requirepass
- TLS for clients and replication, and certificate rotation
- Keeping Redis passwords out of code and images
Free resources
Practice
Lock down your Compose setup: an ACL file with an "app" user limited to app:* keys, a read-only "reporting" user and an "admin" user; disable the default user; turn on TLS with a self-signed CA. Prove that the app user can't run FLUSHALL or CONFIG, and that a client without TLS can't connect.
Monitoring and observability
Watch a handful of numbers and alert on them: memory used versus maxmemory, evicted and expired keys, connected and blocked clients, commands per second, cache hit rate, replication lag and link status, and latency. INFO exposes almost all of it, the slow log records commands that took too long, and LATENCY DOCTOR explains spikes. In practice you scrape INFO with a Prometheus exporter and graph it in Grafana.
INFO stats # ops/sec, hits, misses, evictions
INFO replication # role, replicas, offsets
SLOWLOG GET 10 # slowest recent commands
CONFIG SET latency-monitor-threshold 100
LATENCY DOCTOR # human-readable report
CLIENT LIST # who is connected
What to learn
- The INFO sections and the ten fields worth alerting on
- SLOWLOG and slowlog-log-slower-than
- Latency monitoring, LATENCY DOCTOR and redis-cli --latency
- CLIENT LIST, connection counts and output buffer limits
- Prometheus with redis_exporter, Grafana dashboards and alerts
Free resources
Practice
Add redis_exporter, Prometheus and Grafana to your Compose setup. Build a dashboard with memory, hit rate, ops/sec, evictions and replication lag, and alerts for memory above 80% and a replica that is down. Then run a slow command (SORT on a big list) and find it in SLOWLOG.
Performance and latency troubleshooting
Because commands run one at a time, one slow command delays every client. The usual culprits are O(N) commands on big keys (HGETALL, SMEMBERS, LRANGE 0 -1, DEL of a huge key), KEYS, long Lua scripts, hot keys that every request touches, too many round trips, the fork for a snapshot on a large data set, and swapping. Since Redis 6, I/O threads can handle network reading and writing in parallel, which helps busy servers with many connections; command execution stays on the main thread.
What to learn
- Reading time complexity in the command docs and avoiding O(N) on big keys
- Finding hot keys (redis-cli --hotkeys with an LFU policy) and spreading them out
- Fork latency, transparent huge pages and swapping
- io-threads, and when more CPU helps
- Benchmarking with redis-benchmark and with your real workload
Free resources
Practice
Measure p99 latency with redis-cli --latency-history while another client runs HGETALL on a hash with 1 million fields every second. Find the cause with SLOWLOG and LATENCY DOCTOR, fix it with HSCAN or by splitting the key, and measure again.
Managed Redis, Kubernetes and Valkey
Many teams don't run Redis themselves. Redis Cloud is Redis's own service; Amazon ElastiCache and MemoryDB, Google Memorystore and Azure Managed Redis are the big clouds' options, and several of them now default to Valkey, the Linux Foundation fork. The core commands from stages 1 and 2 work the same on all of them, but newer features (JSON, the query engine, vector sets, the latest commands) differ by product and version, so check before you depend on one. On Kubernetes, run Redis with an operator or a well-maintained chart, and give it persistent volumes and anti-affinity.
What to learn
- What a managed service handles for you: failover, patching, backups, scaling
- Redis versus Valkey: history, licences and where features differ
- Checking which commands and modules a service supports
- Running Redis on Kubernetes: StatefulSets, operators and their trade-offs
- Cost: memory sizing, replicas and data transfer
Free resources
Practice
Pick two managed services and write a one-page comparison for a 10 GB cache with one replica: supported version and engine (Redis or Valkey), whether JSON and vector search are available, failover time, backups, and monthly price in your region. Then run your stage-2 app's tests against a Valkey container and note anything that breaks.
Capstone: a production-ready Redis-backed service
Bring it all together in one project you can show in an interview: a small API that uses Redis for a cache, sessions, a rate limiter, a leaderboard, a stream-based job queue and a search or vector-search feature, running against a replicated (or clustered) Redis with persistence, ACLs, TLS and monitoring. Write down the decisions, not only the code: what you cache and for how long, what you can lose in a crash, and what happens when Redis is down.
What to learn
- Picking the right data type and pattern for each feature
- Writing the key-pattern document and the failure plan for the service
- Load-testing and reading your dashboards under load
- Running a failover drill and a restore-from-backup drill
- Preparing for interviews or the Redis certification exam
Free resources
Practice
Build "QuickPoll": create polls, vote once per user (set), live results (sorted set + pub/sub to the browser), rate-limited voting, cached poll pages, a stream that sends "poll closed" emails, and search over poll titles. Deploy it with Compose against Redis with a replica, AOF and ACLs, load-test it, kill the primary during the test, and write a short report of what happened.
Am I ready? Stage 4 quiz
Your Redis is a pure cache in front of a database. Memory is full. Which maxmemory-policy fits?
noeviction, so writes fail and you noticevolatile-ttl with no TTLs set on any key- No policy: add swap space
allkeys-lru or allkeys-lfu, so the least useful keys are evicted
For a cache, losing cold keys is fine and expected. noeviction fits a data store you can't lose data from; volatile-* only evicts keys that have a TTL.
With appendonly yes and appendfsync everysec, roughly how much data can a power cut lose?
- Nothing at all
- About the last second of writes
- Everything since the last RDB snapshot
- The whole data set
The AOF is fsynced to disk once a second, so at most about one second of writes is at risk.
In Redis Cluster, MGET user:1:name user:2:name fails with CROSSSLOT. How do you make related keys work together?
- Use hash tags such as
{user:1}:name so the keys share a slot - Turn off cluster mode for MGET
- Use a longer key name
- Run the command on a replica
Only the part inside braces is hashed, so keys with the same tag land in the same slot. Note that users 1 and 2 would still be in different slots: group keys by what is read together.
The primary dies and Sentinel promotes a replica. Can recent writes be lost?
- No, replication is synchronous
- No, Sentinel copies the missing writes from the dead primary
- Yes: replication is asynchronous, so writes the replica hadn't received yet are gone
- Only if AOF is turned off
Redis replication is asynchronous. WAIT can reduce the window but doesn't make failover lossless.
Every few seconds all clients see a 300 ms spike. SLOWLOG shows HGETALL big:hash. What's the best fix?
- Add more replicas
- Raise the client timeout
- Turn on io-threads
- Stop reading the whole hash at once: use HSCAN or HMGET for the fields you need, or split the key
Commands run one at a time, so one O(N) command on a huge key blocks everyone. I/O threads don't parallelise command execution.