Caching and search
Redis
Redis is a fast in-memory data store used for caching, queues, counters, sessions and leaderboards, with rich data structures.
What it is
Redis keeps data in RAM and serves it in micro- to milliseconds. It is more than key-value: it offers strings, lists, sets, hashes, sorted sets, bitmaps, HyperLogLog, streams and geo indexes.
It usually sits next to the main database as a cache, a session store, a rate-limit counter or a light queue. Data can be persisted with RDB snapshots and an AOF log, but Redis still works mainly from memory.
About the license. In 2024 Redis Ltd moved from BSD to RSALv2 / SSPLv1, which led to the Valkey fork. In 2025 AGPLv3 was added as an option for Redis 8, so the code is again available under an OSI-approved license.
Use it when
- You need a cache in front of a slow database or an external API.
- You store sessions, one-time tokens or counters with a TTL.
- You build leaderboards, job queues or low-latency pub/sub.
- You need atomic operations on counters and sets.
Avoid it when
- It would be the only store of critical data you cannot lose: memory is expensive and persistence is weaker than in a database.
- The data does not fit into RAM at a reasonable price.
- You need complex queries, joins and SQL-level transactions.
Key concepts
- TTL
- Time to live of a key: after it expires Redis deletes the entry on its own.
- Eviction
- The policy for removing keys when memory runs out (for example allkeys-lru).
- RDB / AOF
- Two persistence modes: periodic snapshots and a log of every write.
- Replication / Cluster
- Replicas for reads and failover, Cluster for sharding data across hash slots.
- Single-threaded commands
- Commands run sequentially on one thread, so every single command is atomic.
Example
Cheat sheet
| Command or code | What it does |
|---|---|
redis-cli | Open the Redis console |
SET user:1 "Ann" EX 60 | Set a value with a 60 second TTL |
GET user:1 | Read a value |
DEL user:1 | Delete a key |
TTL user:1 | Seconds left before expiry |
INCR visits | Atomically increment a counter |
HSET user:1 name Ann age 30 | Write fields into a hash |
LPUSH jobs a && RPOP jobs | A list as a simple queue |
ZADD board 100 ann | Sorted set: a leaderboard with scores |
SCAN 0 MATCH user:* COUNT 100 | Safe key iteration (instead of KEYS) |
INFO memory | Server memory usage |
How to learn it
- Run Redis in Docker and connect with
redis-cli: trySET,GET,DEL,TTL. - Learn the core structures: strings, hashes, lists, sets, sorted sets and when to pick each.
- Implement a cache-aside cache with a TTL in front of a database query and measure the speedup.
- Build a counter or rate limiter with
INCRandEXPIRE, then a queue on lists. - Try pub/sub and Streams for simple events between services.
- Understand persistence (RDB and AOF), eviction policies (
maxmemory-policy) and why everything lives in memory. - Connect Redis from an app through a client (ioredis, node-redis) and avoid common traps: huge keys,
KEYS *. - Read about Sentinel, Cluster and distributed locks before taking Redis to production.
Interview questions
1. Why is Redis so fast?
Data lives in memory, structures are optimized for their operations, and a single thread runs commands without locking between them. The network protocol is also lightweight.
2. What is the difference between RDB and AOF?
RDB takes periodic snapshots: compact, but a crash can lose the last minutes. AOF logs every write: safer, but the file is bigger and writes are slower. Many setups enable both.
3. What is a cache stampede and how do you avoid it?
When a hot key expires, many requests hit the database at once. Fix it with a lock for recomputation, TTL jitter and refreshing the cache ahead of expiry.
4. Redis or Memcached?
Memcached is simpler and only caches strings. Redis adds data structures, persistence, replication and pub/sub, so one service covers more tasks.
Interview questions from the bank
- A Socket.IO chat worked on one instance. A second one was added behind a load balancer: users on different instances do not see each other's messages, and some clients cannot connect. Why, and how do you fix it?MiddleHTTP
- A limit of 100 requests per minute is implemented on Redis. What can break here? How is a fixed window worse than a sliding window and a token bucket, and what do you return to the client?MiddleHTTP
- Pick a Redis structure and commands for these tasks: a user session with a TTL, a player leaderboard with the top 100 and a player's rank, the number of unique visitors per day, a rate limit of 100 requests per sliding minute, the last 50 feed events.MiddleDatabases
- Redis was killed with
kill -9. How much data do you lose with default RDB, with AOFeverysecand with AOFalways? Why canBGSAVEon an instance with 20 GB of data on a 32 GB server bring it down?MiddleDatabases - How does Redis Sentinel differ from Redis Cluster? What does each do when a master fails, how many nodes are needed at minimum and when would you choose one or the other?MiddleDatabases
- Code takes a lock with
SET key 1 NX PX 10000and runsDEL keyafter the work. The task sometimes takes 15 seconds, and the logs show two workers running it at once. Find the two mistakes and fix them.MiddleDatabases - A single 4 GB Redis holds the API cache and BullMQ queues. At a peak some tasks vanished without a trace. After a settings change the next day the API started getting
OOM command not allowed when used memory > 'maxmemory'. What happened and how do you separate the load?SeniorDatabases - How does Redis Cluster decide which node a key lives on? What do
MOVEDandASKreplies mean, how do they differ and what does the client do with them?SeniorDatabases
Comparisons with this technology
Related technologies
- ValkeyValkey is an open source fork of Redis under the Linux Foundation, compatible with the Redis protocol and licensed under BSD.
- MemcachedMemcached is a simple distributed in-memory cache that stores key-value pairs with no persistence.
- Redis StreamsRedis Streams is a Redis data type shaped like an event log with consumer groups, usable as a light message queue.
- PostgreSQLA powerful open source relational database with extensions, JSONB, full-text search and strong SQL support.
Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).