Data types
Redis exposes five primary data types. Each is implemented with a purpose-built internal encoding that makes common operations O(1) or O(log n).String
The simplest type. A string key holds a single value up to 512 MB — arbitrary bytes, a serialized object, or a counter.SET key value NX EX seconds.
List
An ordered collection of strings, implemented as a doubly-linked list. You push and pop from either end in O(1).Hash
A map of string fields to string values stored under a single key. Ideal for representing objects without serializing to JSON.Set
An unordered collection of unique strings. Add, remove, and check membership are all O(1). Set operations (union, intersection, difference) run in O(N).Sorted set
Like a set, but every member carries a floating-point score. Members are ordered by score. Range lookups by score or rank run in O(log N).Why Redis is fast
Redis consistently delivers sub-millisecond response times for five compounding reasons:- In-memory storage. Every read and write targets RAM, which is three to four orders of magnitude faster than SSD and six orders of magnitude faster than spinning disk. The CPU, not storage, is the limiting factor.
-
Efficient internal data structures. Each Redis type maps to a space- and time-optimized encoding (e.g.,
ziplistfor small hashes,skiplist+hashtablefor sorted sets). The engine automatically upgrades encodings as a collection grows. - Single-threaded command execution. Redis processes one command at a time in a single event loop thread. There are no context switches, no mutex contention, and no deadlocks on the data-path. Background threads handle AOF flushing, RDB snapshotting, and freeing memory, so they never stall the main thread.
-
Non-blocking I/O multiplexing. The event loop uses
epoll(Linux) orkqueue(macOS) to monitor thousands of sockets with a single system call. A single thread handles many concurrent clients without spawning per-connection threads. - Efficient memory management. Redis proactively reclaims memory through a configurable eviction policy (LRU, LFU, TTL-based) and lazy deletion of expired keys, keeping allocator fragmentation low.
Redis 6.0 introduced multi-threaded network I/O for parsing requests and writing responses. Command execution remains single-threaded. You may see “Redis is multi-threaded” in recent docs — this refers only to the I/O layer.
Persistence
Redis offers three persistence strategies with different durability-vs-performance trade-offs.RDB (Redis Database snapshot)
RDB writes a point-in-time binary snapshot of all data to disk. Thebgsave command (the default) forks a child process that serializes the snapshot while the main thread continues serving requests. The copy-on-write mechanism ensures the child sees a stable memory image even as the parent writes new data.
- Pros: compact file format; fast startup (load binary directly into memory); minimal main-thread impact.
- Cons: data written after the last snapshot is lost on crash; snapshot generation is CPU- and memory-intensive for large datasets.
AOF (Append-Only File)
AOF records every write command in text format after it executes. On restart, Redis replays the file to restore state. Threeappendfsync strategies control when the OS flushes the AOF buffer to disk:
AOF rewrite (triggered automatically when the file grows too large) forks a child process that writes a compact representation of current state to a new file. The main thread continues appending to the old buffer; the child appends any new commands to a separate rewrite buffer, then swaps the files atomically.
- Pros: minimal data loss; human-readable log; can recover from partial writes.
- Cons: larger file than RDB; slower restart for very large datasets.
Mixed persistence (Redis 4.0+)
The AOF file begins with an RDB binary block (fast bulk load) followed by AOF command records for changes since the snapshot. This combines RDB’s fast startup with AOF’s low data-loss guarantee.Comparison
Clustering
Master-slave replication
One primary node accepts reads and writes. One or more replica nodes receive a copy of every write command asynchronously. Replicas are read-only and serve read traffic to reduce primary load. Replication is asynchronous: the primary does not wait for replicas to acknowledge before returning to the client. This means replicas may lag behind the primary by a small window, and strong consistency is not guaranteed.Sentinel
Redis Sentinel adds automatic failover on top of master-slave replication. You run at least three Sentinel processes that continuously monitor the primary and replica nodes. When a Sentinel detects the primary is unavailable (subjective down), it asks the other Sentinels to vote. Once a quorum of Sentinels agrees (objective down), the Sentinel leader:- Selects the best replica based on replication lag, priority, and node ID.
- Promotes it to primary by sending
SLAVEOF NO ONE. - Reconfigures remaining replicas to follow the new primary.
- Notifies clients of the new primary address via the pub/sub mechanism.
- Master-slave
- Sentinel
- Cluster mode
Simple primary + one or more replicas. Manual failover only. Suitable when you need read scaling and can tolerate manual recovery from a primary failure.
Cache consistency
When you use Redis as a cache in front of MySQL, every write to MySQL must be reflected in Redis quickly enough that readers do not see stale data for too long. The challenge is that writing to two systems is never atomic.Cache-aside (lazy loading)
The application manages the cache directly. On a cache miss, the application fetches from MySQL and populates Redis. On a write, the application updates MySQL and then invalidates (deletes) the cache entry rather than updating it.Write order matters
“Update MySQL first, then delete cache” is the recommended pattern. A TTL on cached keys acts as a safety net for the rare cases where the delete fails.
Handling delete failures
If the cache delete fails after a successful MySQL write, the cache holds stale data until the TTL expires. Two async remediation patterns:- Retry via message queue: enqueue the cache key for deletion; a consumer retries until the delete succeeds.
- Subscribe to MySQL binlog (CDC): tools like Canal read the MySQL binlog and emit change events. Your application deletes the cache key in response to the binlog event, decoupling cache invalidation from the write path entirely.
Delayed double-delete
For “delete first, then update” workloads, delayed double-delete reduces the stale window:- Delete the cache key.
- Update MySQL.
- Sleep briefly (long enough for any in-flight cache-aside read to complete).
- Delete the cache key again.
Redis as a message queue
Redis supports three queue patterns, each with different reliability and feature trade-offs.List queue
UseRPUSH to enqueue and BLPOP to dequeue (blocking pop waits until a message is available). Data is globally ordered within the list.
Pub/Sub
Producers publish messages to a channel; all current subscribers receive a copy. Messages are not persisted — a subscriber that is offline at publish time misses the message.Stream
Redis Streams (added in Redis 5.0) provide a durable, consumer-group-aware append log with message acknowledgement semantics.XCLAIM.