Caching & in-memory store comparison

Redis vs Memcached

Both are in-memory stores used to speed up applications by caching expensive computations or database queries. Redis has grown into a full data structure server with persistence, pub/sub, and scripting; Memcached remains a focused, blazing-fast key-value cache.

TL;DR

  • Memcached — simple string key-value store, multi-threaded, very fast for basic caching, no persistence, no advanced data types. Best when you only need a fast, ephemeral cache and nothing else.
  • Redis — rich data structures (strings, lists, sets, sorted sets, hashes, streams), optional persistence via RDB and AOF, pub/sub, Lua scripting, and cluster mode. Best for caching plus any additional use case.
  • Redis is the default choice today for most new projects. Memcached wins only on raw multi-threaded throughput for pure string-cache workloads.

Side-by-side comparison

AspectRedisMemcached
Data typesString, List, Set, Sorted Set, Hash, Stream, Bitmap, HyperLogLogString (byte array) only
PersistenceRDB snapshots + AOF append-only logNone — data lost on restart
Pub/SubBuilt-in channels and pattern subscriptionsNot supported
ScriptingLua scripts (EVAL) for atomic operationsNot supported
ClusteringRedis Cluster (hash slots) + Sentinel for HAClient-side consistent hashing only
Threading modelSingle-threaded event loop (I/O threads in v6+)Multi-threaded — uses all CPU cores natively
Max value size512 MB per string value1 MB per value
TTL per keyYes — EXPIRE / EXPIREAT commandsYes — set at write time
Eviction policies8 policies (LRU, LFU, random, volatile/allkeys variants)LRU only
Use casesCache, session store, leaderboard, rate limiting, queues, pub/subSimple object or page cache

What is Redis?

Redis (Remote Dictionary Server) was released in 2009 by Salvatore Sanfilippo. It stores data in memory and supports a wide variety of data structures, making it far more than a cache. A single Redis instance can act as a session store, a leaderboard (sorted sets), a job queue (lists with LPUSH/BRPOP), a real-time pub/sub broker, and a rate limiter — all at the same time.

Two persistence modes protect data across restarts. RDB (Redis Database) saves a point-in-time snapshot to disk at configurable intervals — fast to restore, but you can lose the last few minutes of writes. AOF (Append-Only File) logs every write command sequentially; on restart Redis replays the log to recover state. You can combine both for maximum safety. Disabling persistence entirely gives you the fastest possible throughput for pure cache workloads.

Redis 6 introduced I/O threads to handle network reads and writes on multiple cores while keeping the command execution single-threaded. Redis 7 added Redis Functions, a more robust alternative to Lua scripting. Redis Cluster shards data across nodes using 16,384 hash slots and handles automatic failover when paired with Redis Sentinel.

What is Memcached?

Memcached was created in 2003 by Brad Fitzpatrick for LiveJournal and has powered high-traffic sites like Facebook, YouTube, and Wikipedia. Its design philosophy is radical simplicity: one data type (byte strings), one eviction policy (LRU), no persistence, no replication — just an extremely fast distributed hash map accessible over the network.

Because Memcached is multi-threaded, it can exploit all available CPU cores on a single machine, which gives it an edge over Redis on machines with many cores when serving simple GET/SET operations at scale. Horizontal scaling is achieved by running multiple nodes and distributing keys across them using consistent hashing in the client library. If a node goes down, its keys are simply lost — no failover, no replica promotion.

Memcached's simplicity is both its greatest strength and its greatest limitation. There is nothing to configure beyond memory size, eviction policy, and connection limits. If you only need to cache serialised blobs and never need persistence, queues, or pub/sub, Memcached is a very appealing choice.

Code examples

Caching a database result with TTL, and building a leaderboard — two everyday tasks that show where each tool fits:

Basic cache: set and get with TTL

Redis (Node.js ioredis)

{`import Redis from 'ioredis';
const redis = new Redis();

// Cache an API response for 60 seconds
await redis.set(
  'user:42:profile',
  JSON.stringify(userData),
  'EX', 60,          // TTL in seconds
);

const cached = await redis.get('user:42:profile');
const user = JSON.parse(cached);`}

Memcached (memjs)

{`import Memjs from 'memjs';
const mc = Memjs.Client.create();

// Cache a serialised object for 60 seconds
await mc.set(
  'user:42:profile',
  JSON.stringify(userData),
  { expires: 60 },
);

const { value } = await mc.get('user:42:profile');
const user = JSON.parse(value);`}

Leaderboard using a Redis sorted set

Memcached has no equivalent — you would need a separate database query.

{`// Add or update a player's score
await redis.zadd('game:leaderboard', 4250, 'alice');
await redis.zadd('game:leaderboard', 3100, 'bob');
await redis.zadd('game:leaderboard', 5900, 'carol');

// Top 3 players with scores (highest first)
const top3 = await redis.zrevrange(
  'game:leaderboard', 0, 2, 'WITHSCORES'
);
// → ['carol', '5900', 'alice', '4250', 'bob', '3100']

// Atomic rate limiter: increment + set expiry
const count = await redis.incr('rate:user:42');
if (count === 1) await redis.expire('rate:user:42', 60);
if (count > 100) throw new Error('Rate limit exceeded');`}

Redis pub/sub: live notifications

{`// Publisher (in one service)
await publisher.publish('notifications', JSON.stringify({
  userId: 42,
  message: 'Your order has shipped',
}));

// Subscriber (in another service or process)
subscriber.subscribe('notifications', (err, count) => {
  console.log(\`Subscribed to \${count} channel(s)\`);
});
subscriber.on('message', (channel, message) => {
  const data = JSON.parse(message);
  sendPushNotification(data.userId, data.message);
});`}

How engineers talk about Redis vs Memcached

These phrases come up in design reviews, architecture discussions, and code reviews. Understanding them will help you follow — and contribute to — real engineering conversations.

Redis phrases

  • "We cache the API response in Redis with a 60-second TTL." (standard cache-aside pattern)
  • "The leaderboard uses a sorted setZADD scores, ZREVRANGE for the top ten." (describing a specific Redis data structure)
  • "We do an atomic INCR and EXPIRE for the rate limiter." (highlighting that both operations are safe together)
  • "We set up Redis Sentinel for automatic failover to the replica." (high-availability setup)
  • "The session data survives restarts because AOF persistence is enabled." (explaining why Redis was chosen over Memcached)

Memcached phrases

  • "We store serialised objects in Memcached to skip the DB on every request." (classic cache-aside pattern)
  • "Memcached is multi-threaded so it saturates all eight cores." (justifying Memcached for a CPU-bound cache tier)
  • "When the node restarted, the cache was cold — expect a DB spike." (describing the risk of no persistence)
  • "We use consistent hashing across three Memcached nodes." (client-side sharding strategy)
  • "The hit rate is 96% — almost no queries reach the database." (cache effectiveness metric)
  • "We had a cache stampede after the deploy — all keys expired at once." (a common pitfall with synchronised TTLs)

Key vocabulary

TTL (Time To Live)
The expiry time set on a cache key — after this duration the key is automatically deleted. Both Redis and Memcached support per-key TTLs.
RDB (Redis Database snapshot)
A point-in-time binary dump of all Redis data, written to disk at configurable intervals. Fast to restore; may lose the last few minutes of writes.
AOF (Append-Only File)
Redis persistence mode that logs every write command to disk. On restart, Redis replays the log. More durable than RDB, but produces a larger file.
Sorted set
A Redis data structure that stores unique members each with a floating-point score. Enables efficient range queries — the backbone of leaderboards and priority queues.
Eviction policy
The strategy a cache uses when it runs out of memory. Redis offers eight policies (e.g. allkeys-lru, volatile-lfu). Memcached uses LRU only.
Cache stampede
A thundering herd problem where many requests hit the database simultaneously because a popular cache key expired. Mitigated with probabilistic early expiry or a distributed lock.
Consistent hashing
A client-side sharding algorithm that maps keys to nodes such that adding or removing a node only remaps a small fraction of keys. Used by Memcached clients for horizontal scaling.

Decision guide: which should you choose?

Ask yourself these questions in order:

  • Do you need data structures beyond plain strings (lists, sets, sorted sets, hashes)? → Redis
  • Do you need data to survive a restart? → Redis (enable RDB and/or AOF)
  • Do you need pub/sub or lightweight message streaming? → Redis
  • Are you building a leaderboard, rate limiter, or job queue? → Redis
  • Is this a new project with no legacy constraint? → Redis
  • Do you only need a simple string cache at very high throughput on a multi-core machine, and you already operate Memcached? → Memcached
  • Are you running a large PHP application that has used Memcached for a decade? → Keep Memcached unless you need Redis features

The honest summary: for any greenfield project, Redis is the sensible default. Memcached is a legitimate choice only when you have a specific, measured throughput problem that Redis cannot solve, or when you are maintaining an existing Memcached deployment that works well.

Both tools deal with in-memory data, but they sit at a different level from your primary store. If you are deciding between relational and document databases for primary storage, see the SQL vs NoSQL guide. For a deeper look at storing structured data, compare microservices vs monolith to understand how caching strategy changes with architecture.

Frequently asked questions

What is the main difference between Redis and Memcached?

Memcached is a simple, fast key-value cache — strings only, no persistence, multi-threaded. Redis is a richer in-memory data structure store supporting strings, lists, sets, sorted sets, hashes, streams, and more; it offers optional persistence to disk, pub/sub messaging, Lua scripting, and cluster mode. Redis does nearly everything Memcached does, plus a great deal more.

Is Redis faster than Memcached?

For simple string GET/SET operations, Memcached can be marginally faster because it is single-purpose and its multi-threaded architecture utilises multiple CPU cores natively. Redis uses a single-threaded event loop (I/O threads were added in Redis 6+) and is slightly slower on raw throughput. In practice, both handle hundreds of thousands of operations per second and the difference rarely matters for typical applications.

Does Redis persist data to disk?

Yes. Redis offers two persistence options: RDB (point-in-time snapshots at configurable intervals) and AOF (Append-Only File — logs every write command for near-complete durability). You can use both, one, or neither (pure cache mode). Memcached has no persistence — all data is lost on restart.