SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Caching Basics

Redis vs Memcached

Two popular in-memory caches: a simple fast one, and a richer one with data structures.

โฑ 12 min readBeginnerInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Redis and Memcached are the two best-known in-memory caches. Both keep data in RAM and answer in a fraction of a millisecond.

  • Memcached is simple: keys and values, spread across many cores, with nothing else.
  • Redis is richer: lists, sets, sorted sets, hashes, streams, saving to disk, copies for safety, and pub/sub.
  • If you only cache simple values, either works. If you need anything more, Redis is usually the answer.

02Concept: What is it?

Reading from a database costs milliseconds. Reading from memory costs microseconds. A cache server puts popular data in RAM on a separate machine, so many app servers can share it. Redis and Memcached are the usual choices.

Memcached was built to do one job very well: store a value under a key, return it quickly and forget it when memory is full (least recently used items go first). It does not save data to disk, and it has no built-in copies. If a node dies, its data is gone, and the cache refills from the database.

Redis looks like a key-value store, but a value can be a data structure: a list, a set, a sorted set, a hash and more. That lets the server do work for you, such as โ€œgive me the top 10 scoresโ€. It can also save data to disk, copy it to other nodes, and fail over automatically.

Two ways to be a cache
Memcached
๐Ÿ–ฅ๏ธApp
โ†’โ†“get / set
๐Ÿ“ฆMemcachedkey โ†’ blob
๐ŸงตMany threadsuses many cores
Redis
๐Ÿ–ฅ๏ธApp
โ†’โ†“rich commands
๐ŸงฐRedisstrings, sets, sorted setsโ€ฆ
๐Ÿ’พDiskoptional
๐ŸชžReplicacopy + failover
Memcached is a plain shelf. Redis is a shelf with tools attached.
๐Ÿง Both lose data if you treat them as the database
A cache holds copies. Even with Redis persistence, the safe design is that the real data lives elsewhere, and the cache can be rebuilt.

03Real-Life Example

๐ŸตA plain shelf and a workshop
Imagine a shop that keeps its most-requested items close to the counter. Memcached is a plain shelf: you put a box on it with a label, and you take it off by label. It holds a lot, and many assistants can grab boxes at the same time. Redis is a small workshop: it can also keep a sorted list of the best sellers, sort or count things for you, and make a backup copy of the room in case of fire.
Shop
Cache servers
A label on a box
A key
The box
A value (a blob or a data structure)
Many assistants grabbing boxes together
Memcachedโ€™s multi-threaded design
A sorted best-seller board
A Redis sorted set
A photocopy of the room in a safe
Redis persistence (RDB and AOF)
A twin shop that can take over
A Redis replica and failover
A shelf that is empty after a power cut
Memcached after a restart

04Why Do We Need It?

โšกMemory speed
Both answer far faster than a database, which takes pressure off it.
๐ŸคShared by many servers
Every app server sees the same cache, so a value is stored once.
๐ŸงฐDo more than store
Redis can rank, count, queue and publish, so you need fewer separate systems.
๐ŸชถKeep it simple
Memcached has few settings and few ways to go wrong.
๐Ÿ“ˆScale out
Add nodes. Memcached clients spread keys over them. Redis Cluster does it for you.
โณAutomatic expiry
Both support a time-to-live on each key.
Pick the simplest tool that covers your needs. Memcached for plain cached values at big scale. Redis when you need structures, safety or extra features.

05Where Do We Use It?

๐Ÿ—‚๏ธDatabase result cache
Store query results or objects under a key, with a TTL.
๐ŸงพSession storage
Keep user sessions in a shared store, so any server can serve any user.
๐Ÿ†Leaderboards
Redis sorted sets rank scores in memory.
๐ŸšฆRate limiting
Count requests per user with a counter and a TTL (Redis).
๐Ÿ“ฃPub/sub and queues
Redis can publish messages and hold simple queues.
๐Ÿ–ผ๏ธRendered pages and fragments
Memcached is a classic home for HTML fragments and small blobs.

06Types / Parts / How It Works

Side by side

FeatureMemcachedRedis
Data modelKeys to simple values (strings or blobs)Strings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog and more
PersistenceNone. Memory only.Optional: RDB snapshots and an append-only file (AOF)
Replication and failoverNot built inBuilt in. Sentinel or Cluster handle failover and sharding.
ThreadsMulti-threaded, uses many coresCommands mostly run on one main thread. Newer versions add I/O threads, and you can run more instances.
Scaling outThe client spreads keys over nodes (consistent hashing)Redis Cluster shards the keys for you
EvictionLeast recently used (LRU)Several policies, including LRU and LFU, and no eviction
Extra featuresFewPub/sub, Lua scripts, transactions, streams
Operating itVery simpleMore settings to understand

How a key reaches the right node

Client-side sharding vs a cluster
Memcached: the client chooses
๐Ÿ–ฅ๏ธClient libraryhash(key) โ†’ node
๐Ÿ“ฆNode 1
๐Ÿ“ฆNode 2
๐Ÿ“ฆNode 3
Redis Cluster: nodes own slots
๐Ÿ–ฅ๏ธCluster-aware clientkey โ†’ slot โ†’ node
๐ŸงฐNode Aslots 0 to 5460
๐ŸงฐNode Bmore slots
๐ŸงฐNode Cmore slots
Memcached Redis
Memcached relies on the client library to pick a node. Redis Cluster splits keys into slots that nodes own.
VisualizerWhich one fits? And why a sorted set mattersTick what your system needs and compare the fit. Then open the leaderboard demo and raise the number of players to see how much work the app does without a sorted set.
Redis fit
100%
of the points you need
Memcached fit
100%
of the points you need
Redis
  • Yes.Strings with a TTL work fine.
Memcached
  • Yes.This is exactly what it was made for: simple, small and fast.
A tie: both do the job. Then the simpler tool wins. For plain cached values, Memcached has less to run and less to configure, but Redis is also fine and often already in the stack.

A teaching model, not a benchmark. The fit scores count how many of your needs each product covers out of the maximum. The step counts are rough: about log2(N) for a sorted set, and N reads plus Nยทlog2(N) comparisons for sorting in the app. The 50 bytes per score is made up.

07How to Use It / Steps / Implementation

Choosing and using one

  1. 1
    List what the cache must do
    Only cache values with a TTL? Or also ranking, counting, queues, pub/sub or surviving restarts?
  2. 2
    Choose Memcached for plain values at scale
    If you only store blobs and need top multi-core throughput with the least fuss, it is a good fit.
  3. 3
    Choose Redis when you need more
    Data structures, persistence, replication, failover and extra features all point to Redis.
  4. 4
    Set a TTL on every key
    Both support it. It keeps the cache from filling with data nobody reads.
  5. 5
    Pick an eviction policy
    Decide what leaves when memory is full. Read Cache Eviction Policies, then configure it.
  6. 6
    Plan for a lost node
    Expect a cold cache sometimes. Make sure the database can survive the misses.
  7. 7
    Use a managed service if you can
    Cloud services such as Amazon ElastiCache, Google Memorystore and Azure Cache run both and handle patches and failover.
๐Ÿ’กDo not use a cache as your only copy
Even with Redis saving to disk, a crash can lose the most recent writes, depending on settings. Keep the source of truth in a real database.
โš ๏ธBig values and slow commands
A single huge value or a command that walks a million items can block a mostly single-threaded server. Keep values small and avoid commands that scan everything.

08Key Terms to Know

TermMeaning in easy words
In-memory storeA database or cache that keeps its data in RAM
Key-valueData stored and found by a unique key
TTL (time to live)How long a key stays before it is removed automatically
EvictionRemoving items when memory is full
LRULeast recently used: remove what has not been touched for the longest
Sorted setA Redis structure where each member has a score and the set stays ordered
PersistenceSaving data to disk so it survives a restart (RDB snapshots, AOF log)
ReplicationKeeping copies of the data on other nodes
SentinelA Redis tool that watches nodes and promotes a replica after a failure
Redis ClusterRedis mode that splits keys into slots spread over many nodes
Client-side shardingThe client library decides which node holds a key (used with Memcached)

09Pros, Cons and Trade-offs

โœ… Pros
  • Very fast reads and writes from memory
  • Memcached: simple, multi-threaded and easy to scale out
  • Redis: data structures, persistence, replication and failover
  • Both support expiry and are widely used and well documented
  • Managed services remove most of the operating work
โš ๏ธ Cons
  • RAM is expensive compared to disk
  • Memcached: no persistence, no copies, nothing beyond keys and values
  • Redis: more to learn, and the single main thread can be a limit
  • A restart or lost node means a cold cache and a burst of database load
  • Both need care with hot keys and big values

Trade-offs

ChoiceWe gainWe lose
MemcachedSimplicity and raw multi-core speed for plain valuesPersistence, replication and data structures
RedisRich features and built-in safetyMore complexity to operate and understand
Redis persistence onData can survive a restartSome write cost, and disk settings to tune
Redis replicasFailover and extra read capacityA replica may be slightly behind the primary
Client-side shardingNo extra moving partsThe client must handle adding and removing nodes
Managed serviceLess work, built-in failoverCost and less control

10Common Problems and Mistakes

Common mistakes

  1. Treating Redis as the main database. A cache can lose recent data, so the real data must live elsewhere.
  2. No TTL on keys. Memory fills with old data and eviction starts removing useful items.
  3. Huge values. They slow everything else down, especially on a mostly single-threaded server.
  4. Slow commands in production. Commands that scan every key can block other clients.
  5. Adding or removing a Memcached node with plain hashing. Most keys map to a different node, and the cache is suddenly cold. Use consistent hashing.
  6. Sorting in the app. Fetching thousands of values to rank them, when a sorted set could do it.
  7. Forgetting a failure plan. One lost cache node can send a flood of requests to the database.

Things to watch

๐Ÿ“‰Hit rate
A low hit rate means the cache is not helping. Check TTLs and key design.
๐Ÿ”ฅHot keys
One key with huge traffic can overload the single node that holds it.
๐Ÿง Memory use
Watch used memory and evictions. Rising evictions mean you are short of RAM.
๐ŸชžReplica lag
A Redis replica can be a little behind, so reads from it may be slightly old.

11Real-World Examples

๐Ÿ†Gaming and ranking
Redis sorted sets are a common choice for live leaderboards.
๐ŸงพSession stores
Web apps keep login sessions in Redis, so any server can serve any user.
๐ŸšฆAPI rate limits
Counters with a TTL in Redis count requests per user per minute.
๐Ÿ–ผ๏ธWeb page fragments
Large sites have used Memcached for years to cache rendered pieces and database rows.
โ˜๏ธManaged caches
Cloud providers offer both engines as managed services.
๐Ÿ“ฃReal-time features
Redis pub/sub and streams support chat, notifications and simple event feeds.
๐Ÿ“Note
Features and defaults change between versions and between managed offerings. Check the current documentation before relying on a detail.
Mini case: a game with a global leaderboard
๐ŸŽฎGame serversupdate scores
โ†’โ†“ZADD
๐ŸงฐRedis sorted setalways ranked
โ†’โ†“top 10
๐Ÿ“ฑPlayers
Writers Cache Readers
The game server updates one sorted set. Players read the top 10 in one command. The database keeps the permanent record.

12Related Topics to Read Next

Key-Value Databasesโ†’

Redis is both a cache and a key-value database.

Distributed Cache Architectureโ†’

How a cache is spread over many machines.

Cache Eviction Policiesโ†’

What leaves the cache when memory is full.

Consistent Hashingโ†’

How clients spread keys over cache nodes without a big reshuffle.

Replicationโ†’

How Redis keeps copies of data on other nodes.

Caching Strategiesโ†’

Cache-aside and others: how an app uses a cache.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Both: in-memory, sub-millisecond, TTL on keys, used to shield the database.
  • โœ”Memcached: plain key-value, multi-threaded, no disk, no replicas, client-side sharding.
  • โœ”Redis: data structures, optional persistence, replication, failover, pub/sub.
  • โœ”Leaderboard: a Redis sorted set gives the top N directly.
  • โœ”Scale: consistent hashing (Memcached) or Redis Cluster slots.
  • โœ”Safety: a cache is not the source of truth. Plan for a cold start.
  • โœ”Watch: hit rate, memory, evictions, hot keys, slow commands.
  • โœ”One line: โ€œMemcached is a shelf. Redis is a shelf with tools.โ€
โ† Previous
HTTP Caching (Cache-Control, ETag)
Next โ†’
Local Cache vs Distributed Cache