AlgoViz

Memcached or Redis

easy 25 min

Memcached and Redis both keep data in memory and answer in well under a millisecond on the server.

Video lesson · Chapter 1 of 5

The same profile lookup hides different work

0:00 / 4:27

Theory

Read or listen first. About 2 min.

What it is

Memcached is a server that stores values under keys in memory. A value is a block of bytes: the server does not look inside it. You can get, set, delete, count up or down, and replace a value only if nobody changed it since you read it.

Redis is a data structure server. A value can be a string, a list, a set, a sorted set, a hash, a stream and more, and the server has commands that work on the inside of each one. It can also write data to disk, copy it to other servers and pass messages between clients.

Why it exists

Reading from memory saves the database from repeating the same work. Both products do that job well, so the first question is not which is faster. The first question is whether you need anything more than get and set.

Extra features cost something: more settings to understand, more memory use to plan, and data that somebody may start to treat as permanent. A smaller tool is easier to run, and a richer tool can save many trips over the network.

A short history

  1. 2003

    Brad Fitzpatrick releases Memcached, first written for the website LiveJournal.

  2. 2009

    Salvatore Sanfilippo releases the first version of Redis.

  3. 2015

    Redis 3.0 is released in April with Redis Cluster, which spreads keys over several servers.

  4. 2024

    Redis changes its licence, and the Linux Foundation announces Valkey, a fork of the last version under the BSD licence.

  5. 2025

    From Redis 8, the AGPLv3 open source licence is one of the three licences a user can pick.

Words to know

Round trip
One request to the server and its answer. Over a network this usually costs more than the command itself.
Data structure
A value with a shape the server understands, such as a list or a sorted set.
Slab
A block of memory Memcached cuts into equal chunks, so it does not fragment.
RDB
A Redis snapshot of all data at one moment.
AOF
Append-only file: Redis logs every write so it can replay them.
CAS
Check and set: store a value only if it has not changed since you read it.

How it works

Step through the idea, or press Play.

Step 1 of 3

List what the data must do. Only get and set, or rank, count, queue and expire parts of it

Understand it

Start here

A tray and a tool belt

Two helpers work at a craft fair. One carries a plain tray: put a thing on it, take a thing off. The other wears a tool belt with several tools, each made for one job.

Two helpers at the fair

A tray is not worse than a belt. If all you do is carry cups, the belt is in the way.

The first one

Memcached on its own

Memcached runs several worker threads, four by default. Each thread serves many connections, so one server can use several processor cores. Memory is cut into slabs of equal chunks, and old items leave by a least recently used rule kept per slab class, in several segments.

One Memcached machine

An application sends keys to one Memcached machine. Inside the machine a set of worker threads reads and writes one memory area made of slabs. On a miss the application reads the database.
Threads share one table of keys. Nothing is written to disk in this picture: the database holds the truth.
  • Many threads

    Four by default. Useful when one machine has spare cores and many connections.

  • Whole values

    Keys up to 250 bytes. Values are bytes up to 1 MB by default. No fields, no ranks.

  • Counters and CAS

    It can count up and down in one step, and replace a value only if it is unchanged.

  • Empty after a normal restart

    Data is in memory. A clean warm restart is possible from version 1.5.18 if you set it up, but a crash still empties it.

Memory a chunk wastes

waste=1−item sizechunk size1−100120≈17%\text{waste} = 1 - \frac{\text{item size}}{\text{chunk size}} \qquad 1 - \tfrac{100}{120} \approx 17\%
An item sits in the smallest chunk that holds it. The sizes here are an example. Chunk sizes grow by a factor you can tune, 1.25 by default.

The second one

Redis on its own

Redis runs commands one at a time on a main thread, so each single command is atomic. Threads for network input and output can be switched on, and they read requests and write replies while commands still run one after another.

A Redis primary with disk and a replica

An application sends commands to a primary Redis machine. The command thread works on data structures in memory and writes a snapshot and a log to disk. A second machine, a replica, receives a copy of the writes.
The snapshot, the log and the replica are choices. Turn on what you need and no more.

Six structures and what they are for

TypeExample commandGood for
StringSET user:123 AnaSimple values, sessions
ListLPUSH tasks t1Recent items, simple queues
SetSADD tags redisUnique items, tags, followers
Sorted setZADD board 100 p1Leaderboards, priority queues
HashHSET user:123 age 30Objects such as profiles
StreamXADD events * type clickEvent logs with readers that keep a position
Redis has more, such as bitmaps and geospatial indexes. Memcached stores any of these only as bytes your program packs and unpacks.

Four more features

  • Pub/Sub

    Clients publish and subscribe. A message is delivered at most once: a client that is away misses it.

  • Lua scripts

    A small program runs on the server as one step. Good for a rate limit counter.

  • Transactions

    MULTI and EXEC run queued commands together. There is no rollback of those that worked.

  • Cluster

    Keys are spread over servers by 16,384 hash slots.

Disk

Persistence: what survives

Redis persistence choices

ChoiceHow it worksWhat a crash can lose
NoneMemory onlyEverything
RDB snapshotWrites all data at chosen times. Restarts quicklyWrites since the last snapshot
AOF, sync each secondLogs every write. Slower to loadAbout one second of writes
RDB and AOFBoth togetherAs for AOF
Memcached has no such log. Its optional warm restart helps planned restarts only.

A restart, side by side

A cache miss is normal and safe. Lost data that had no other home is not.

Compare

Feature by feature

FeatureMemcachedRedis
Plain valuesYesYes
Lists, sets, sorted sets, hashes, streamsNoYes
Expiry time per keyYesYes
Counters in one stepYesYes
Check and setYesYes, with WATCH or a script
Snapshots and a write logNoYes, optional
Copies on other serversNot in the server itselfYes, asynchronous
Sharing keys over serversClient or proxy decidesRedis Cluster, or the client
Pub/Sub, scripts, transactionsNoYes
ThreadsMany worker threadsOne for commands, optional input and output threads
Largest value1 MB by default512 MB for a string
How keys are shared over servers is the subject of distributed caching.

Memcached fits when

  • You need simple key-value caching only
  • You want high throughput for simple operations
  • You have many cores to use on one machine
  • Memory per key matters and values are small and plain
  • Losing everything on a restart is fine
  • You already run it well

Memcached does not fit when

  • You need ranks, queues or fields inside a value
  • Data must survive a restart
  • You need messages between clients
  • You need built-in replicas or a cluster
  • Several keys must change as one step
  • You need a script on the server

Speed

Count trips, not microseconds

For a plain get, both servers spend very little time, and the network is the larger part. Differences between them depend on value size, cores, connections and settings. So benchmark with your own traffic. What you can predict is the number of round trips.

Cost of adding one point to a player

T=n×RTTTget, change, cas=2×0.5=1 msTone command=0.5 msT = n \times RTT \qquad T_{\text{get, change, cas}} = 2 \times 0.5 = 1\,\text{ms} \qquad T_{\text{one command}} = 0.5\,\text{ms}
Assume a round trip of 0.5 ms. The first way also sends the whole board both ways, and repeats when another client got there first.

Adding a score to a leaderboard

Memcached can do it, but the app carries the work and the risk of a lost update.

Who tends to come out ahead

WorkUsually betterWhy
Very many small plain gets on a big machineMemcachedThreads share the work
Change part of a valueRedisThe value never leaves the server
Several keys as one stepRedisA script or a transaction
Fetch 100 keysEitherBoth can answer many keys in one trip

Memory

What fills up and what leaves

Memcached has a memory limit and removes old items when a class is full. Redis removes nothing by default: with a limit and the noeviction policy, writes fail when it is full. As a cache, set maxmemory and an eviction policy. See cache eviction and expiry times.

What happens when memory is full

Redis samples a few keys to find old ones, so its LRU is close to exact but not exact.

Decide

A decision you can draw

Which one do I need?

Use cases

JobPickNote
Database query resultsMemcached or RedisWhole values, short life
HTML fragments and API responsesMemcached or RedisSame
SessionsEitherWith Memcached a lost session means signing in again
LeaderboardRedisSorted set
Simple job listRedisList, or a stream if jobs must not be lost
Rate limitRedisA counter and its expiry in one script
Live notificationsRedisPub/Sub, if missing one is fine
Real-time countsRedisCounters and sorted sets

Pitfalls

Four things people get wrong

  1. 1

    Treating a cache as the only copy

    Even with the log, replication is asynchronous. Keep the source of truth in a database.

  2. 2

    Believing one thread removes all races

    One command is atomic. Two commands with your own code in between are not.

  3. 3

    Counting a transaction as a rollback

    If one queued command fails, the others still run.

  4. 4

    Forgetting the eviction policy

    A Redis cache without one refuses writes when full.

Remember

SIMPLE and RICH

Memcached is SIMPLERedis is RICH
Stores plain valuesRich data types
In memoryIn-server logic: scripts and atomic commands
Many threadsClustering and copies built in
Performance for plain getsHas a snapshot and a log
Light to run
Efficient memory for plain values

Summary

The whole topic in one minute.

Memcached does one job: keep bytes under a key, on many threads, with little to configure. Redis understands what is stored, so one command can do work that takes several trips with Memcached, and it can persist and replicate.

Pick Memcached for a pure cache of whole values that can all be lost. Pick Redis when you need a structure, an atomic step over several values, replicas, or data that should survive a restart. Measure with your own sizes before you argue about speed.

  • Both hold data in memory, and a plain get is fast on either.
  • Memcached: whole values, many threads, no built-in copies.
  • Redis: structures, scripts, optional disk and replicas, commands one at a time.
  • Count round trips: one Redis command can replace several steps.
  • Set a memory limit and an eviction policy, and never keep the only copy in a cache.

Sources