Tags: redis, nosql, cache, key-value, in-memory, pubsub
Level: intermediate
TL;DR: Open-source, in-memory data structure store used as a highly performant database, cache, and message broker.
In-memory key-value store ensuring sub-millisecond read and write latency.
Single-threaded event loop architecture avoids context switching and locking overhead.
Relies on I/O multiplexing (epoll/kqueue) to handle multiple concurrent connections.
Supports rich data structures: Strings, Lists, Sets, Sorted Sets (ZSET), and Hashes.
RDB persistence: Point-in-time snapshots for efficient backups and fast restarts.
AOF persistence: Logs every write operation to disk for maximum data durability.
Eviction policies (e.g., LRU, LFU, TTL) automatically manage memory when full.
Pub/Sub mechanism enables fast, fire-and-forget message broadcasting.
Redis Sentinel handles monitoring, notifications, and automatic failover.
Redis Cluster enables horizontal scaling through automatic data sharding.
Q: How does Redis handle concurrent requests if it is single-threaded?R: It uses I/O multiplexing to track multiple connections, executing commands sequentially in memory incredibly fast without thread-locking overhead.
Q: What is the tradeoff between RDB and AOF?R: RDB is faster to load but risks losing recent data if a crash occurs. AOF provides better durability but consumes more disk I/O and space.
Q: When would you choose to use a Sorted Set?R: I typically use Sorted Sets for leaderboards or rate-limiting windows, where elements must be continuously ordered by a specific score.
Executing the KEYS * command in production, which blocks the single thread entirely. Always use SCAN instead.
Forgetting to set an expiration (TTL) on temporary cache keys, leading to Out of Memory (OOM) crashes.
Creating massive keys (e.g., Hashes with millions of fields), causing severe latency spikes during retrieval or deletion.
# Basic key operations with 1-hour expiration
SET user:session:123 "active" EX 3600
GET user:session:123
# Safely iterate over keys without blocking the server
SCAN 0 MATCH user:session:* COUNT 100
# Sorted Sets (Leaderboard example)
ZADD leaderboard 100 "Alice"
ZADD leaderboard 150 "Bob"
ZREVRANGE leaderboard 0 -1 WITHSCORES
# Use Lists as a simple queue
LPUSH jobs_queue "job1"
RPOP jobs_queue