Redis Documentation
An in-memory key-value store used for caching, sessions, counters, queues and pub/sub.
Redis is an in-memory key-value data store — extremely fast (sub-millisecond) because data lives in RAM. It is used as a cache in front of databases, for sessions, rate limiting, leaderboards, counters, queues and real-time pub/sub messaging. Values aren't just strings: Redis has lists, sets, sorted sets, hashes, streams and more.
1. Introduction & Installation
- Linux:
sudo apt install redis-server, thensudo systemctl start redis. - macOS:
brew install redisandbrew services start redis. - Windows: use WSL (Ubuntu) or Docker:
docker run -p 6379:6379 redis:7. - Cloud: free tiers on Redis Cloud and Upstash (serverless Redis).
redis-server --version
redis-cli # connect to localhost:6379
redis-cli -h host -p 6379 -a password
redis-cli ping
PONG
⚠️ Common error:
Could not connect to Redis at 127.0.0.1:6379: Connection refused— the server isn't running. Startredis-server(or the Docker container) first.
2. Keys & Strings
Every value is stored under a key. A common naming convention uses colons: user:42:name, session:abc123, cache:courses:page:1.
SET course:1:title "DSA in C++"
GET course:1:title
SET views:home 10
INCR views:home
INCRBY views:home 5
GET missing:key
EXISTS course:1:title
DEL course:1:title
Output:
OK
"DSA in C++"
OK
(integer) 11
(integer) 16
(nil)
(integer) 1
(integer) 1
INCR/DECR are atomic — safe even when thousands of clients increment at the same time (perfect for counters and likes). MSET/MGET set or read several keys at once; APPEND, STRLEN and GETRANGE work on string values.
⚠️ Common error:
KEYS *on a production server scans every key and blocks Redis. UseSCAN 0 MATCH user:* COUNT 100instead.
3. Data Types Overview
| Type | Think of it as | Typical use |
|---|---|---|
| String | a value (text, number, JSON, bytes up to 512 MB) | cache, counters, flags |
| Hash | an object / map of fields | user profile, product |
| List | a linked list (push/pop at both ends) | queues, recent items |
| Set | unique unordered items | tags, online users, "who liked" |
| Sorted set (ZSET) | unique items ordered by a score | leaderboards, priority queues |
| Stream | append-only log with consumer groups | event processing |
| Others | bitmaps, HyperLogLog, geospatial, JSON (module) | analytics, maps |
SET name "Asha"
LPUSH queue "job1"
SADD tags "redis"
TYPE name
TYPE queue
TYPE tags
OK
(integer) 1
(integer) 1
string
list
set
4. Expiration (TTL)
Keys can expire automatically — the core of caching and sessions.
SET otp:9876543210 "482913" EX 300
TTL otp:9876543210
SET session:abc "user:42" PX 1500
EXPIRE views:home 60
PERSIST views:home
TTL views:home
TTL no:such:key
OK
(integer) 300
OK
(integer) 1
(integer) 1
(integer) -1
(integer) -2
TTL returns seconds left, -1 if the key has no expiry and -2 if it doesn't exist. SET key value NX sets only if the key does not exist (used for locks), XX only if it exists.
⚠️ Common error: a later
SETon the same key removes its TTL unless you passEXagain (orKEEPTTL).
5. Hashes
HSET user:1 name "Asha" city "Pune" xp 120
HGET user:1 name
HINCRBY user:1 xp 30
HMGET user:1 name xp
HEXISTS user:1 email
HGETALL user:1
(integer) 3
"Asha"
(integer) 150
1) "Asha"
2) "150"
(integer) 0
1) "name"
2) "Asha"
3) "city"
4) "Pune"
5) "xp"
6) "150"
Hashes are ideal for objects whose fields you update individually (no need to read-modify-write a whole JSON string).
6. Lists
RPUSH tasks "email" "resize" "backup"
LPUSH tasks "urgent"
LRANGE tasks 0 -1
LPOP tasks
RPOP tasks
LLEN tasks
LPUSH recent:views "c1" "c2" "c3" "c4"
LTRIM recent:views 0 2
LRANGE recent:views 0 -1
(integer) 3
(integer) 4
1) "urgent"
2) "email"
3) "resize"
4) "backup"
"urgent"
"backup"
(integer) 2
(integer) 4
OK
1) "c4"
2) "c3"
3) "c2"
LPUSH + LTRIM keeps a "last N items" list. BLPOP queue 5 waits up to 5 seconds for an item — a simple job queue for workers.
7. Sets & Sorted Sets
SADD likes:post:7 "asha" "ravi" "neha"
SADD likes:post:7 "asha"
SCARD likes:post:7
SISMEMBER likes:post:7 "ravi"
SADD likes:post:8 "ravi" "kabir"
SINTER likes:post:7 likes:post:8
(integer) 3
(integer) 0
(integer) 3
(integer) 1
(integer) 2
1) "ravi"
Sorted sets keep members ordered by score — a leaderboard in a few commands:
ZADD leaderboard 120 "asha" 95 "ravi" 140 "neha"
ZINCRBY leaderboard 30 "ravi"
ZREVRANGE leaderboard 0 2 WITHSCORES
ZREVRANK leaderboard "asha"
ZSCORE leaderboard "ravi"
ZCOUNT leaderboard 100 200
(integer) 3
"125"
1) "neha"
2) "140"
3) "ravi"
4) "125"
5) "asha"
6) "120"
(integer) 2
"125"
(integer) 3
(ZREVRANK is 0-based: rank 2 means third place.)
8. Caching Patterns
Cache-aside (lazy loading) — the most common pattern:
import { createClient } from "redis";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
async function getCourse(id) {
const key = `cache:course:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // 1. cache hit
const course = await Course.findById(id).lean(); // 2. miss → read the database
await redis.set(key, JSON.stringify(course), { EX: 600 }); // 3. store for 10 minutes
return course;
}
async function updateCourse(id, data) {
await Course.updateOne({ _id: id }, data);
await redis.del(`cache:course:${id}`); // invalidate on write
}
Other patterns: write-through (write cache and DB together), TTL-based expiry, and stampede protection (a short lock with SET lock:key 1 NX EX 5 so only one request rebuilds a hot key).
Rate limiting — e.g. 5 login attempts per minute per IP:
async function allow(ip) {
const key = `rate:login:${ip}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, 60); // start the 60-second window
return count <= 5;
}
⚠️ Common error: caching without a TTL or invalidation — users then see stale data forever. Always expire or delete cache keys when the source changes.
9. Pub/Sub & Streams
Pub/Sub — fire-and-forget messages to everyone currently subscribed:
SUBSCRIBE chat:room1
In another terminal:
PUBLISH chat:room1 "Hello everyone!"
(integer) 1
The subscriber receives:
1) "message"
2) "chat:room1"
3) "Hello everyone!"
Messages are not stored — offline subscribers miss them. For durable messaging use Streams:
XADD orders * item "book" qty 2
XADD orders * item "pen" qty 5
XLEN orders
"1729400000000-0"
"1729400000001-0"
(integer) 2
(The ids are timestamps generated by Redis, so yours will differ.) Read with XRANGE orders - +, or process with consumer groups (XGROUP CREATE, XREADGROUP, XACK) so several workers share the work and nothing is lost.
10. Advanced Concepts
Transactions — MULTI queues commands and EXEC runs them all at once (no other client runs in between):
SET balance:asha 500
SET balance:ravi 100
MULTI
DECRBY balance:asha 200
INCRBY balance:ravi 200
EXEC
OK
OK
OK
QUEUED
QUEUED
1) (integer) 300
2) (integer) 300
WATCH key before MULTI makes EXEC fail if the key changed (optimistic locking). For complex atomic logic, Lua scripts (EVAL) run entirely on the server.
Persistence — Redis is in memory but can save to disk:
- RDB snapshots every N seconds/changes (
save 60 1000) — compact, may lose the last minutes. - AOF (append-only file) logs every write (
appendonly yes,appendfsync everysec) — safer. - Both can be enabled together.
Memory management — set maxmemory 256mb and an eviction policy like allkeys-lru (evict least recently used keys) for a pure cache.
Scaling and availability — replicas (replicaof), Sentinel for automatic failover, Redis Cluster for sharding data across nodes.
Other features: geospatial (GEOADD, GEOSEARCH — "stores near me"), HyperLogLog (PFADD/PFCOUNT — count unique visitors with ~12 KB), bitmaps (SETBIT — daily active users), and OBJECT, INFO, MONITOR, SLOWLOG for debugging.
11. Examples with Output
Example 1 — Daily unique visitors with a set
SADD visitors:2026-10-20 "u1" "u2" "u3"
SADD visitors:2026-10-20 "u2"
SCARD visitors:2026-10-20
EXPIRE visitors:2026-10-20 172800
(integer) 3
(integer) 0
(integer) 3
(integer) 1
Example 2 — Simple distributed lock
SET lock:report "worker-1" NX EX 30
SET lock:report "worker-2" NX EX 30
GET lock:report
OK
(nil)
"worker-1"
(The second worker didn't get the lock because the key already existed.)
Example 3 — Top 3 of a weekly leaderboard
ZADD lb:week:42 300 "asha" 450 "neha" 120 "ravi" 380 "isha"
ZREVRANGE lb:week:42 0 2
(integer) 4
1) "neha"
2) "isha"
3) "asha"
12. Practice Problems
- Store a user profile in a hash and increase their XP by 50.
- Build a "recently viewed courses" list that keeps only the last 10 items per user.
- Implement a page-view counter that resets every day (use the date in the key and a TTL).
- Create a leaderboard with a sorted set and print the top 5 with scores, and a user's rank.
- Add cache-aside caching to an Express route and measure the speed-up.
- Implement login rate limiting: 5 attempts per 15 minutes per IP.
- Use Pub/Sub to broadcast "new message" events between two terminals.
- Count unique visitors for a month with HyperLogLog and compare memory with a set.
13. Interview Questions
1. Why is Redis so fast? Data is in memory, operations are simple and mostly O(1)/O(log n), it uses an efficient single-threaded event loop for commands (no lock contention) and optimised data structures.
2. Is Redis single-threaded? Command execution is single-threaded (so each command is atomic); newer versions use extra threads for network I/O and background tasks.
3. How does Redis persist data? RDB snapshots and/or AOF logs of every write; you can enable both. Without persistence, data is lost on restart.
4. What eviction policies exist?
noeviction, allkeys-lru, volatile-lru, allkeys-lfu, volatile-ttl, allkeys-random, etc. — chosen with maxmemory-policy.
5. Cache-aside vs write-through? Cache-aside: the app reads the cache, falls back to the DB and fills the cache. Write-through: every write updates the cache and the DB together.
6. What is a sorted set used for? Ordered data by score — leaderboards, priority queues, time-ordered feeds, rate limiting with sliding windows.
7. Pub/Sub vs Streams? Pub/Sub delivers messages only to currently connected subscribers (no storage). Streams store messages and support consumer groups, acknowledgements and replay.
8. How do Redis transactions work?
MULTI queues commands and EXEC runs them atomically in order. There is no rollback on a failing command; WATCH adds optimistic locking.
9. What is cache stampede and how do you prevent it?
Many requests rebuilding the same expired hot key at once. Prevent with a short lock (SET NX), early refresh, or jittered TTLs.
10. What is the difference between EXPIRE and PERSIST?
EXPIRE sets a time-to-live on a key; PERSIST removes it so the key lives forever.
14. Cheat Sheet & References
Connection and keys
# connect with: redis-cli -h host -p 6379
PING
SELECT 1
KEYS user:*
SCAN 0 MATCH user:* COUNT 100
EXISTS k
DEL k
TYPE k
RENAME k k2
FLUSHDB
Strings and TTL
SET k v
SET k v EX 60 NX
GET k
MSET a 1 b 2
MGET a b
INCR n
INCRBY n 5
DECR n
EXPIRE k 60
TTL k
PERSIST k
Hashes and lists
HSET user:1 name Asha xp 10
HGET user:1 name
HGETALL user:1
HINCRBY user:1 xp 5
HDEL user:1 xp
LPUSH q a
RPUSH q b
LPOP q
LRANGE q 0 -1
LTRIM q 0 9
BLPOP q 5
Sets and sorted sets
SADD s a b
SMEMBERS s
SISMEMBER s a
SCARD s
SINTER s1 s2
SUNION s1 s2
ZADD lb 100 asha
ZINCRBY lb 5 asha
ZREVRANGE lb 0 9 WITHSCORES
ZRANK lb asha
ZSCORE lb asha
Pub/Sub, streams, transactions
PUBLISH ch msg
SUBSCRIBE ch
XADD st * field value
XRANGE st - +
MULTI
EXEC
WATCH k
Node.js (redis package)
const redis = createClient({ url: process.env.REDIS_URL }); await redis.connect();
await redis.set("k", "v", { EX: 60 }); await redis.get("k"); await redis.incr("n");
await redis.hSet("user:1", { name: "Asha" }); await redis.zAdd("lb", { score: 10, value: "asha" });
Official documentation