Library / Blogs
Redis Blog
Redis features, data structures and use cases.
By Redis engineers · Redis Ltd. · Added 2026-10-12
All content belongs to Redis engineers / Redis Ltd.. We only link to it and give credit. Report a problem
Learn this article
About 37 min left. Your work is saved as you go.
What you are about to study
Redis Ltd. wrote this to explain how they thought about a problem. You should know the basics: caching, queues and replication.
Ideas you will meet
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Core Concepts: How Things Actually Work · 8 minWhy Redis is fast, and Redis versus MemcachedIn-memory storage, a single-threaded event loop and rich data structures, plus how persistence and replication work.Read here
Why it is fast
- Everything lives in memory. No disk seek on the read path.
- Simple, efficient data structures (hash tables, skip lists, compact encodings) with predictable costs.
- A single-threaded event loop for command execution: no locks between threads, no context switching, and each command runs atomically. I/O multiplexing lets one thread serve thousands of connections.
- A lean protocol and in-process memory management.
(Newer versions use extra threads for network I/O, but command execution stays ordered.)
Image: Mixabest · Public domain · Source · Wikimedia Commons: Dual-channel DDR memory use 6026How the pieces fit
100%Figure SDA-CORE-09-1 · Redis: event loop, memory, persistence and replication · © forcsguy.com
More than a cache
Redis stores typed values:
Type Use String cached values, counters, flags Hash objects with fields (a user profile) List queues, recent items Set unique members, tags, set maths Sorted set leaderboards, priority queues, time-ordered data Others streams, bitmaps, HyperLogLog, geospatial Because operations run on the server, you can increment, push, pop or intersect without a read-modify-write race.
100%Figure SDA-CORE-09-2 · Redis data types and what they are for · © forcsguy.com
Durability options
Memory is volatile, so Redis offers:
- Snapshots (RDB): periodic point-in-time dumps. Compact, but recent writes can be lost.
- Append-only file (AOF): logs every write; replays on restart. Safer, bigger and a little slower.
- Or none at all when it is purely a cache.
Scaling and availability
- Replication: a primary copies to replicas (asynchronously), serving reads and enabling failover.
- Sentinel / managed failover promotes a replica when the primary dies.
- Cluster: splits keys across nodes by hash slot, for data larger than one machine.
Redis versus Memcached
Redis Memcached Data types many strings only Persistence optional none Replication yes not built in Threading one for commands multi-threaded Best for cache plus data structures, queues, counters a very simple, large, pure cache For most new projects Redis is the more flexible choice. Memcached remains fine for a straightforward cache that must use many CPU cores.
Pitfalls
- Memory is finite: set a maxmemory and an eviction policy (for example LRU).
- Avoid slow commands on huge collections.
- A very hot key still concentrates load on one node.
More on this site
Related reading
- Redis DocumentationRedis · Redis Ltd.Documentation
- Redis BlogRedis engineers · Redis Ltd.Blogs
- Redis UniversityRedis · Redis Ltd.Courses
- RedisRedis · Redis Ltd.GitHub
Show 6 moreShow fewer
- Redis persistenceRedis · Redis Ltd.Documentation
- Memory Optimization in Redis at WattpadWattpad engineers · WattpadCase Studies
- Scale with Redis ClusterRedis · Redis Ltd.Documentation
- Scaling Job Queue with Redis at SlackSlack engineers · SlackCase Studies
- Moving persistent data out of Redis at GithubGithub engineers · GithubCase Studies
- PayPal Developer Community BlogPaypal engineers · PaypalBlogs
Advanced Distributed Systems · 12 minRedis: persistence, replication, Sentinel and ClusterWhat keeps an in-memory database from losing data and from being a single point of failure: snapshots, the append-only file, replicas, Sentinel and hash slots.Read here
Fast because it is in memory, durable because of logs
Redis keeps its dataset in RAM (the reason it is so fast; see the Redis and Memcached lesson). To survive a restart it offers two persistence mechanisms, which can be combined.
Snapshots (RDB)
Redis periodically writes a point-in-time snapshot of the whole dataset to disk, using a forked child process so the main process keeps serving. Snapshots are compact and quick to load, but anything written since the last snapshot is lost on a crash.
Append-only file (AOF)
Redis appends every write command to a log. On restart it replays the log. The fsync policy sets the loss window:
Policy Behaviour Risk alwaysFlush after every command Slowest, almost no loss everysecFlush once per second At most about a second lost (common default) noLet the OS decide Fastest, larger loss The AOF grows, so Redis periodically rewrites it into a compact form. Many deployments use AOF with
everysec, sometimes plus snapshots for fast backups.100%Figure SDA-ADS-04-1 · Redis persistence choices · © forcsguy.com
Replication and Sentinel
A Redis primary replicates to one or more replicas asynchronously. Replicas serve reads (possibly slightly stale) and can take over. Sentinel is a small set of monitor processes that:
- watch the primary and replicas,
- agree by quorum that the primary is down,
- promote a replica and tell clients where the new primary is.
100%Figure SDA-ADS-04-2 · Sentinel failover · © forcsguy.com
Because replication is asynchronous, a failover can lose the last few acknowledged writes. Redis offers settings to reduce this (for example requiring a minimum number of replicas to acknowledge), at the cost of availability.
Redis Cluster: sharding
When data or traffic outgrow one node, Redis Cluster shards the keyspace into 16,384 hash slots. A key's slot is a hash of the key modulo that number; each node owns a range of slots, and each primary has replicas. Clients learn the slot map and talk to the right node; a wrong guess gets a redirect.
- Resharding moves slots (and their keys) between nodes while the cluster runs.
- Multi-key operations only work when all keys are in the same slot. Hash tags (a
{tag}part of the key) force related keys into one slot. - Failover is built in: replicas of a failed primary are promoted by the cluster.
- This is the "fixed number of slots" cousin of consistent hashing (see the consistent-hashing lesson).
Which setup when
Need Choice Pure cache, loss acceptable Single node or replicas, little or no persistence Must survive restart AOF (everysec) and snapshots Must survive node loss Replica plus Sentinel Data larger than one node, or very high throughput Redis Cluster Also keep memory in mind: set a max memory and an eviction policy (see the caching lessons) so Redis behaves predictably when full, and watch for large keys and slow commands, which block a single-threaded executor.
Real-world reading
Related reading
- Redis DocumentationRedis · Redis Ltd.Documentation
- Redis persistenceRedis · Redis Ltd.Documentation
- Redis UniversityRedis · Redis Ltd.Courses
- Redis BlogRedis engineers · Redis Ltd.Blogs
Show 6 moreShow fewer
- Scale with Redis ClusterRedis · Redis Ltd.Documentation
- RedisRedis · Redis Ltd.GitHub
- Failover with Redis Sentinel at VintedVinted engineers · VintedCase Studies
- Memory Optimization in Redis at WattpadWattpad engineers · WattpadCase Studies
- Speeding Up Redis with Compression at DoorDashDoorDash engineers · DoorDashCase Studies
- Availability in Globally Distributed Storage Systems at GoogleGooglePapers
System Design Foundations · 11 minCachingHow keeping popular data in fast memory makes systems quicker, and the invalidation problems that come with it.Read here
Why a cache helps
Reading from memory is thousands of times faster than a database round trip (lesson 3). A cache keeps copies of frequently needed data in fast storage so most requests never reach the slower source. The results: lower latency, less load on the database, and lower cost.
100%Figure SDA-FND-06-1 · Cache-aside read path · © forcsguy.com
Before: every read hits the database
100%After: a cache answers most reads
100%What changed
- Most reads never reach the database
- Responses are faster because memory is quicker than disk
- The cache can be stale, so you decide how long is acceptable
Where caches live
- In the browser: controlled with HTTP headers such as
Cache-Control. - At the edge (CDN): copies of pages and files near the user (lesson 9).
- In the application tier: a shared cache like Redis or Memcached.
- Inside the database: buffer pools and query caches.
You can use several at once, each answering whatever it can.
Common strategies
Strategy How it works Good for Cache-aside App checks cache, on miss reads the database and fills the cache the default for most read-heavy data Read-through The cache itself loads from the database on a miss simpler app code Write-through Writes go to the cache and the database together data you read right after writing Write-behind Writes go to the cache first and reach the database later very high write rates, if you can risk losing a little Write-behind is fast but dangerous: if the cache fails before it flushes, writes are lost.
Writes can use the cache in three different ways. The sequence shows when the database learns about the change:
100%Figure SDA-FND-06-2 · Write-through: update the cache and the database together · © forcsguy.com
100%Figure SDA-FND-06-3 · Write-back: acknowledge first, save later · © forcsguy.com
100%Figure SDA-FND-06-4 · Write-around: skip the cache on writes · © forcsguy.com
Watch one read with and without a warm cache. Press Play both together, and use the Simulate tab to slow the network and see the gap grow.
Before: no cache
100%After: cache hit
100%What changed
- The database is not asked at all
- Two network hops disappear from the request
- The saving grows as the network gets slower
The hard part: invalidation
There are only two hard things in computer science: cache invalidation and naming things.
A cache holds a copy, and copies go stale. Your options:
- Time to live (TTL): entries expire after a set time. Simple, but data can be stale until then.
- Explicit invalidation: delete or update the cache entry when the source changes. Fresher, but you must never forget a code path.
- Versioned keys: put a version in the key (
product:42:v7) so a change simply starts using a new key.
Most real systems combine a TTL (a safety net) with explicit invalidation on writes.
100%Figure SDA-FND-06-5 · Defending the database from lookups of keys that do not exist · © forcsguy.com
Eviction: what to drop when full
Memory is limited, so a cache removes items when it fills. Common policies: LRU (least recently used), LFU (least frequently used) and FIFO. LRU is a good default.
Failure modes to know
- Cache stampede: a hot key expires and many requests rebuild it at once. Fix with a lock, request coalescing, or adding random jitter to expiry times.
- Cache penetration: requests for keys that do not exist always miss and reach the database. Fix by caching "not found" briefly, or with a Bloom filter.
- Cold start: after a restart the cache is empty and the database takes the full load. Warm the cache or ramp traffic up.
- Inconsistency: two writers update the cache and database in different orders. Prefer deleting the cache entry on write over updating it.
A worked example: what a cache is really worth
Suppose a product page reads from a database in 20 ms and from a cache in 1 ms, and the site serves 10,000 reads per second.
Cache hit rate Average latency Reads reaching the database 0% (no cache) 20 ms 10,000 per second 50% 10.5 ms 5,000 per second 90% 2.9 ms 1,000 per second 99% 1.2 ms 100 per second The average latency is
hit x 1 + (1 - hit) x 20. Notice two things. First, going from 90% to 99% barely changes the average (2.9 to 1.2 ms) but cuts database load ten times. That is usually the real prize: a cache is a way to protect the database. Second, the first 50% is cheap and the last 9% is expensive: it needs a much bigger cache, because the remaining misses are the long tail of rarely requested items.How big should it be? Traffic is usually skewed: a small share of items gets most requests (often described as "80% of requests go to 20% of items", and for popular content it is more extreme). Estimate your working set: the items requested within your cache lifetime. If 2 million product pages exist but 100,000 get 90% of the traffic, a cache that holds 150,000 of them at about 5 KB each needs only 750 MB. Measure the hit rate while changing the size, and stop growing when the curve flattens.
100%Figure SDA-FND-06-6 · Hit rate rises quickly, then flattens · © forcsguy.com
Stampedes: when a popular key expires
Take a homepage fragment read 5,000 times a second and cached for 60 seconds. At the moment it expires, thousands of requests miss at once, and every one of them rebuilds it from the database. The database, which was lightly loaded because of the cache, suddenly takes a spike. If the rebuild is slow, requests pile up, the spike lasts longer, and the system can fall over exactly when it is busiest.
Ways to defend:
- Request coalescing (single flight). Let one request rebuild the value while the others wait for its result.
- A short lock on rebuild. The first request takes a lock and rebuilds; the rest either wait briefly or serve the old value.
- Stale-while-revalidate. Keep serving the expired value for a few more seconds while one background request refreshes it. Users see slightly old data and never see a spike.
- Jittered expiry. Add a random amount to each TTL (for example 60 seconds plus up to 10) so thousands of keys written together do not all expire together.
- Refresh ahead. For a handful of known-hot keys, refresh them on a schedule before they expire.
100%Figure SDA-FND-06-7 · One request rebuilds, the others wait or use the old value · © forcsguy.com
Mistakes people make
- Caching without a plan for invalidation. "Cache it for an hour" is a promise that users may see hour-old data. Decide what staleness each kind of data tolerates (a like count: minutes; a price or permission: seconds or never).
- Caching per-user data under a shared key. If a personalised page is cached under a key that does not include the user, the next visitor sees someone else's data. Include everything that changes the response in the key, or do not cache it.
- Treating the cache as the source of truth. Caches lose data on restart or eviction. The database must be able to rebuild everything.
- Ignoring the hot key. One enormously popular key can overload a single cache node. Replicate that key across nodes or add a small in-process cache in front.
- Not measuring. Track hit rate, evictions, memory use and the latency of misses. A cache you do not measure is a guess.
Try it yourself
In the System Builder, open "The database becomes the bottleneck". Run it without a cache and watch the database turn red, then add a cache and try different sizes. In the sandbox, raise the "popular-item skew" slider and notice how much a small cache helps when a few items dominate. You can also open the cached design on the free canvas and try wiring the cache in front of different parts.
More on this site
Related reading
- Flannel: An Application-Level Edge Cache to Make Slack ScaleSlack Engineering · SlackCase Studies
- Redis UniversityRedis · Redis Ltd.Courses
- Redis BlogRedis engineers · Redis Ltd.Blogs
- RedisRedis · Redis Ltd.GitHub
Show 6 moreShow fewer
- Redis DocumentationRedis · Redis Ltd.Documentation
- TAO: Facebook's Distributed Data Store for the Social Graph (paper)Bronson et al. · Meta (Facebook)Papers
- Build Your Own XCodeCrafters · GitHubGitHub
- Memory Optimization in Redis at WattpadWattpad engineers · WattpadCase Studies
- Redis Fleet at HerokuHeroku engineers · HerokuCase Studies
- Redis at TrivagoTrivago engineers · TrivagoCase Studies
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Redis Blog.
Warm upGet the vocabulary first.
Documentation
Redis Documentation
Data types, persistence, replication, clustering and caching patterns.
Redis Ltd.Beginner
Courses
Redis University
Free courses on Redis data structures, search, and caching patterns.
Redis Ltd.Beginner
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs · Free from the author · Read here
Scalable Web Architecture and Distributed Systems
A full chapter on the building blocks of large websites: availability, performance, reliability, scalability, caches, proxies, indexes, load balancers and queues. Free to read here under CC BY 3.0.
The Architecture of Open Source ApplicationsBeginner40 min
Blogs
High Scalability
Long-running blog dissecting the architectures of large internet companies.
High ScalabilityIntermediate
See it in another companyThe same ideas, a different system.
Case Studies · Read here
Moving persistent data out of Redis at Github
Historically, we have used Redis in two ways at GitHub: We used it as an LRU cache to conveniently store the results of expensive computations over data originally persisted in…
GithubIntermediate
Case Studies · Read here
Optimizing Redis Storage at Deliveroo
Counting unique users, checking if a credit card has already been used, or checking if this is a mobile user’s first visit ever — all of these require maintaining a large set of fingerprints (unique visitor ID, card f...
DeliverooIntermediate
Read the codeSee how it looks when it is real.
GitHub
Redis
The source of the in-memory data store, a compact C codebase worth reading.
Redis Ltd.Advanced
GitHub
Awesome Scalability
Curated reading list of articles on the architecture of scalable, reliable systems.
binhnguyennusIntermediate
Keep learning
Loading community…