Redis vs Memcached: Caching Solutions Compared
In this tutorial, you'll learn about Redis vs Memcached: Caching Solutions Compared. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Redis offers rich data structures and persistence beyond caching, while Memcached focuses on simplicity and raw throughput for key-value caching — two in-memory data stores with different feature sets.
At a Glance
| Feature | Redis | Memcached |
|---|---|---|
| Data Types | Strings, lists, sets, hashes, sorted sets, streams, bitmaps | Strings only |
| Persistence | RDB snapshots + AOF append-only log | None (ephemeral) |
| Replication | Built-in master-replica | Client-side (no built-in) |
| Clustering | Redis Cluster (automatic sharding) | No (add nodes manually) |
| Pub/Sub | Built-in messaging | Not supported |
| Lua Scripting | Server-side Lua scripts | Not supported |
| TTL Handling | Per-key TTL with eviction policies | Per-key TTL with LRU eviction |
| Memory Eviction | 8 policies (allkeys-lru, volatile-ttl, etc.) | LRU only (when slab limit reached) |
Key Differences
- Data structures: Redis supports strings, lists, sets, sorted sets, hashes, bitmaps, HyperLogLog, streams, and geospatial indexes. Memcached only supports string key-value pairs. If you need atomic increments, list operations, or sorted sets, Redis is required. Memcached is purely a key-value cache — what you store is what you get.
- Persistence: Redis can persist data to disk via RDB snapshots (point-in-time) and AOF (append-only file) for full durability. Memcached is entirely ephemeral — data exists only in memory and is lost on restart. Use Redis when cache data must survive restarts (session stores, leaderboards). Use Memcached when cache data is disposable.
- Replication and clustering: Redis has built-in master-replica Replication and Redis Cluster for automatic sharding across nodes. Memcached has no Replication — you must handle redundancy at the application level or use a proxy like Mcrouter. Redis Cluster provides automatic failover and resharding.
- Memory management: Memcached uses slab allocation — memory is divided into slabs of different chunk sizes. This avoids fragmentation but wastes memory if keys vary in size. Redis uses a simple allocator (jemalloc) with object sharing for small integers and strings. Memcached is slightly more memory-efficient for uniform-sized values.
- Feature scope: Redis is often described as a data structure server — it goes beyond caching to serve as a Message Broker (Pub/Sub), rate limiter, leaderboard, queue (lists + BLPOP), and real-time analytics store. Memcached does one thing — cache key-value data — and does it well.
When to Choose Redis
Choose Redis when you need more than simple caching. Redis's data structures power leaderboards (sorted sets), rate limiters (strings + TTL), job queues (lists), session stores (hashes with TTL), pub/sub messaging, real-time analytics (HyperLogLog), and full-text search (RediSearch). Redis's persistence means your cache can double as a primary database for certain workloads. Redis Cluster provides automatic sharding for horizontal scaling. At DodaTech, Redis powers session storage and real-time analytics across our product suite.
Use Redis for: session stores, Rate Limiting, leaderboards, job queues, pub/sub messaging, real-time analytics, geospatial queries, and applications where cache data must survive restarts or be shared across application servers.
When to Choose Memcached
Memcached is the right choice for pure key-value caching where simplicity and maximum throughput are the priorities. Its multi-threaded architecture (Memcached uses multiple threads, Redis is single-threaded) can outperform Redis for simple get/set operations on large values. If you already use Redis for data structures and just need a separate cache layer, Memcached complements Redis well. Memcached's memory overhead per key is lower than Redis's for simple string values.
Use Memcached for: simple key-value caching (database query results, API responses, rendered page fragments), high-throughput caching of large objects (images, serialized data), and environments where data loss on restart is acceptable.
Side by Side Code Example: Cache Database Query Results
Redis (Node.js with ioredis)
import Redis from "ioredis";
const redis = new Redis();
const cacheKey = "user:profile:42";
// Get from cache or database
async function getUserProfile(userId) {
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// Simulate DB query
const data = { id: userId, name: "Alice", email: "alice@example.com" };
// Cache with TTL of 5 minutes
await redis.setex(cacheKey, 300, JSON.stringify(data));
return data;
}
const profile = await getUserProfile(42);
console.log(profile);
// Output: { id: 42, name: "Alice", email: "alice@example.com" }
Memcached (Node.js with Memcached)
import Memcached from "memcached";
const memcached = new Memcached("localhost:11211");
const cacheKey = "user_profile_42";
// Get from cache or database
function getUserProfile(userId) {
memcached.get(cacheKey, (err, data) => {
if (data) return JSON.parse(data);
// Simulate DB query
const data = { id: userId, name: "Alice", email: "alice@example.com" };
// Cache with TTL of 5 minutes
memcached.set(cacheKey, JSON.stringify(data), 300, () => {});
return data;
});
}
getUserProfile(42);
// Same output: { id: 42, name: "Alice", email: "alice@example.com" }
Both examples cache a database query result for 5 minutes. Redis's setex combines set + expire in one atomic command. Memcached requires separate set with TTL parameter. Redis offers richer data operations (increment, append, set operations) that Memcached cannot match.
Expected Output
# First call: Database query → cache → return
# Second call: Cache hit → return (no database query)
# Both return identical data:
# { id: 42, name: "Alice", email: "alice@example.com" }
FAQ
Related Comparisons
SQL vs NoSQL — MongoDB vs PostgreSQL — MySQL vs PostgreSQL — REST vs gRPC
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro