DEV Community

Mubashir Taj
Mubashir Taj

Posted on

Redis vs Memcached: Picking Your Cache

Almost every backend system eventually needs a cache. A database that answers every read directly becomes the bottleneck sooner or later, so teams put a fast in-memory store in front of it. The two names that come up in that conversation are Redis and Memcached. Both are in-memory key value stores, both are fast, and both have been running in production for well over a decade. They are not interchangeable, though. They were built for different jobs, and the differences show up in data structures, persistence, clustering, and eviction. This article compares the two engines directly, so you can make the choice with the trade-offs in front of you.

What each engine is

Memcached started in 2003 as a cache for LiveJournal. Its job was simple: keep frequently read database rows in memory so the database did fewer reads. That narrow job is still its whole design. Memcached stores opaque blobs under string keys. It does not know what is inside a value, it does not offer data structures, and it does not persist anything to disk. If a node restarts, its cache is empty, and the database takes the load again until the cache warms up.

Redis arrived in 2009 with a wider ambition. It is a data structure server that happens to be excellent as a cache. Strings, hashes, lists, sets, sorted sets, streams, and geospatial indexes are all native. Values have types, and the server understands them, so operations like incrementing a counter or adding a member to a set happen atomically on the server instead of in a read, modify, write round trip from the client. Redis can also persist data to disk, replicate it, and run as a primary store for some workloads, which is a different job from pure caching.

Data structures and operations

The data model is the biggest difference between the two, and it decides most of the rest.

  1. Memcached has exactly one data type: a byte string. Your application serializes a value, usually JSON or a binary format, and stores it under a key. The server never inspects the contents. That simplicity is a strength when all you need is a dumb, fast lookup. It is a weakness when you need to change part of a value, because the only option is to fetch the whole blob, modify it, and write it back, which is slower and racy under concurrency.

  2. Redis has a typed data model. A string can be a counter you increment with INCR. A hash can hold the fields of a user session, and you can update one field with HSET without touching the rest. A sorted set can hold a leaderboard, ordered by score, and you can fetch the top ten with a single command. A list can act as a queue, a set can hold unique tags, and a stream can hold an append-only log. These operations run on the server, atomically, which removes whole classes of race conditions that client side read-modify-write cycles introduce.

  3. Redis also supports Lua scripting and, in recent versions, a functions API, so small pieces of logic can run on the server next to the data. Memcached has no equivalent. If your access pattern is plain get and set of whole values, the extra machinery in Redis buys nothing. If your access pattern involves counters, rankings, queues, or partial updates, Redis removes work from your application code.

Persistence

Memcached keeps everything in RAM and nothing on disk. A restart, a crash, or a deployment that replaces the node wipes the cache completely. For a pure cache this is acceptable by design: the database still holds the truth, and the cache refills as requests arrive. The cost is a cold start. After a restart, every request misses until the working set is rebuilt, and the database absorbs a surge of reads during that window.

Redis offers two persistence mechanisms. RDB snapshots write the whole dataset to disk at intervals, and AOF logs every write operation so the dataset can be replayed. You can run with both, one, or neither. With persistence enabled, a Redis node can restart and reload its data instead of starting empty. That is also why Redis is sometimes used as a primary store for data that can tolerate some loss, such as sessions or job queues. Persistence is not free. Snapshots and write logs add disk I/O and configuration surface, and AOF replay on a large dataset can take minutes. If you only need a cache, you can disable persistence entirely and Redis behaves like Memcached in this respect, with a warm restart as the only thing you give up.

Eviction policies

Both engines evict data when memory fills up, but Redis gives you more control over how it happens.

Memcached uses a slab allocator with LRU eviction inside each slab class. When a slab class is full, the least recently used item in that class is evicted. The behavior is predictable and simple, but it is one policy for everything. You cannot treat session keys differently from rendered page fragments, except by setting TTLs per key.

Redis lets you pick a policy per instance. The common options are no eviction, which returns errors on writes when memory is full, allkeys-lru, which evicts the least recently used key across the whole dataset, volatile-lru, which only evicts keys that have a TTL set, allkeys-random, and volatile-ttl, which evicts the key with the shortest remaining TTL. This matters in practice. A cache that holds both permanent reference data and short lived session tokens should not evict reference data to make room for sessions. With volatile-lru, the permanent keys are safe and only expiring keys compete for space. Memcached cannot express that distinction.

Clustering and scaling

Memcached scales by adding nodes and letting the client decide which node holds a key. The standard approach is consistent hashing on the client side. The server has no knowledge of the cluster, which keeps the design simple and fast, but it also means the client library owns sharding, and adding or removing a node reshuffles some keys. There is no replication, no failover, and no built-in way to move data between nodes. If a node dies, its keys are gone until they are rebuilt from the database.

Redis Cluster shards data across nodes with hash slots, and the cluster itself knows the mapping, so clients can ask any node where a key lives. Redis also supports replication, with replicas that can be promoted when a primary fails, and Sentinel or cluster mode for automatic failover. A Memcached fleet is a set of independent nodes, and your application must tolerate losing any of them at any time. A Redis deployment can be built for high availability, with data surviving a single node failure. The price is operational complexity: cluster setup, slot migration, and failover behavior all need understanding and testing.

For a single node, the two engines are comparable in raw throughput, both comfortably handling tens of thousands of operations per second. Redis is single threaded for command execution, which keeps its behavior simple and deterministic, while Memcached is multithreaded and can use multiple cores on one box. In practice, network and client overhead dominate long before either engine saturates.

Protocol and clients

Memcached speaks a simple text and binary protocol that is easy to implement, and clients exist for every language. Redis speaks RESP, its own text based protocol, and also has clients for every language. Both are straightforward to use from Go or Node, and both have mature client libraries with connection pooling and cluster support.

A quick comparison in Go shows how similar the basic usage looks:

// Redis with go-redis
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
ctx := context.Background()
rdb.Set(ctx, "user:42", `{"name":"Sara","plan":"pro"}`, time.Hour)
name, err := rdb.Get(ctx, "user:42").Result()
count, err := rdb.Incr(ctx, "pageviews:home").Result()
Enter fullscreen mode Exit fullscreen mode
// Memcached with gomemcache
mc := memcache.New("localhost:11211")
item := &memcache.Item{Key: "user:42", Value: []byte(`{"name":"Sara","plan":"pro"}`), Expiration: 3600}
mc.Set(item)
cached, err := mc.Get("user:42")
Enter fullscreen mode Exit fullscreen mode

The Redis snippet does one thing the Memcached snippet cannot: increment a counter on the server. Everything else is the same shape, a client, a key, and a value. The choice between them is not about the API. It is about whether your workload needs the server to understand your data.

When to pick each

Choose Memcached when the job is strictly caching whole values in front of a database. It is the simplest tool for that job, it is battle tested, its multithreaded design scales well on a single box, and its lack of features is a feature: there is less to misconfigure. Typical fits are rendered HTML fragments, serialized API responses, and database query results that are fetched whole and invalidated by TTL or by explicit deletion. If you can describe your cache as a map from string keys to opaque blobs, Memcached is enough, and the extra machinery of Redis is cost without benefit.

Choose Redis when you need anything beyond a dumb key value lookup. Counters, leaderboards, rate limiters, queues, session stores with field level updates, pub/sub messaging, and geospatial queries all map naturally onto Redis data structures. Choose Redis when persistence matters, because a restart should not empty the cache, or when you need replication and failover rather than accepting that a dead node means a cold cache. The operational cost is real, so do not choose Redis by default for every project. Choose it when a concrete requirement points at it.

One last consideration is team knowledge. Both engines are simple to start with, but Redis has more features to learn and more ways to misconfigure, from eviction policies to persistence settings to cluster topology. If the team already runs Redis in production, using it for caching too is usually the right call, because one system to operate beats two. If the team runs neither, and the workload is plain caching, Memcached is the smaller thing to learn and operate.

Conclusion

Redis and Memcached solve overlapping problems from different starting points. Memcached is a purpose built cache: simple, fast, and deliberately limited. Redis is a data structure server that can act as a cache, with typed values, server side operations, persistence, replication, and clustering. The right choice follows from the workload. Whole value caching with no extra requirements points to Memcached. Counters, rankings, queues, partial updates, persistence, or failover point to Redis. Either engine serves a plain cache well. The expensive mistake is picking the simple one and then rebuilding the missing features in application code, or picking the powerful one and paying its operational cost for a job the simple one already did.

Top comments (0)