Background
Sections
IntroductionRequirements & Problem AnalysisConstraints & AssumptionsEstimation TechniquesFunctional vs Non-Functional RequirementsMoSCoW PrioritizationSystem Design FundamentalsArchitecture DiagramClass DiagramComponent DiagramData Flow Diagram (DFD)ER Diagram (Entity-Relationship Diagram)High Level Design (HLD)Low Level Design (LLD)Sequence DiagramState DiagramUse Case DiagramData StorageDocument StoresFile StorageGraph DatabasesIn-Memory DatabasesKey-Value StoresNewSQLNoSQL DatabasesObject StorageSQL Databases (RDBMS)Time-Series DatabasesWide-Column StoresDatabase ConceptsACID PropertiesCAP TheoremConsistency ModelsIndexingNormalization & DenormalizationReplicationSharding & PartitioningTransactions & Isolation LevelsScalabilityAuto-Scaling & ElasticityConsensus & Leader ElectionLoad BalancingReplication & Read ReplicasSharding & PartitioningVertical vs Horizontal ScalingAvailability & ReliabilityBackup & Data DurabilityCircuit BreakerData ConsistencyDisaster RecoveryFault Tolerance & FailoverGraceful DegradationHigh AvailabilityNetworkingCDNDNSFirewalls & VPNHTTP & HTTPSLoad Balancer & Reverse ProxyTCP/IP & UDPWebSocketsCachingCache InvalidationCache Read/Write PatternsCaching LayersEviction PoliciesRedis vs MemcachedMessaging & CommunicationDead-Letter QueueIdempotencyKafka vs RabbitMQ vs SQSMessage QueuesPub/SubCompute & ServicesAPI GatewayContainers & OrchestrationMonolith vs MicroservicesServerlessService DiscoveryService MeshWeb Server & App ServerAPI DesignAPI Versioning & IdempotencyAuthentication & AuthorizationGraphQLgRPCPaginationRate Limiting & ThrottlingRESTSecurityAuthentication & AuthorizationData PrivacyEncryptionInput Validation & InjectionOAuth2 & JWTSecrets ManagementXSS & CSRFStorage & File SystemsBackup & RetentionBlock vs File vs Object StorageData Lakes & WarehousesDistributed File SystemsEphemeral StorageObservability & MonitoringDistributed TracingHealth ChecksLoggingMetricsSLI, SLO, SLADesign PatternsBulkhead PatternCircuit Breaker PatternCreational PatternsRate Limiter PatternRetry PatternStructural & Behavioral Patterns

Redis vs Memcached

7 min read

In a Nutshell

When you need a fast, in-memory, distributed cache, the two classic choices are Redis and Memcached. Both store data in RAM and serve it in well under a millisecond, and for pure key-value caching they perform similarly. The difference is scope: Memcached is a deliberately simple, multi-threaded key-value cache that does one thing extremely well. Redis is a richer "data structures server" — it offers lists, sets, sorted sets, hashes, pub/sub, persistence, replication, transactions, and more, making it useful for far more than caching. For most new systems Redis is the default because its versatility rarely hurts and often helps; Memcached shines for the narrow case of a simple, huge, multi-core cache.

2D minimalistic side-by-side comparison diagram: left panel labeled "Memcached" shows a simple key-value box with multiple threads and the label "simple, multi-threaded, strings only"; right panel labeled "Redis" shows a richer box containing multiple data-structure icons (list, set, sorted set, hash) plus pub/sub and a persistence disk icon, labeled "data structures + persistence + replication"

How It Actually Works

Feature Comparison

Feature Memcached Redis
Data types Strings/blobs only Strings, lists, sets, sorted sets, hashes, streams, bitmaps, HLL, geo
Threading Multi-threaded (scales across cores) Mostly single-threaded core (6.0+ adds I/O threads)
Persistence None (pure cache) Optional (RDB snapshots + AOF log)
Replication No (client-side sharding only) Yes (primary-replica)
High availability External tooling Redis Sentinel / Cluster
Clustering Client-side sharding Built-in Redis Cluster
Pub/Sub & streams No Yes
Transactions / scripts No MULTI/EXEC, Lua scripting
Eviction policies LRU Many (LRU, LFU, TTL variants)
Max value size 1 MB (default) 512 MB

When Memcached's Simplicity Wins

Memcached's multi-threaded design lets it fully use many CPU cores on a single large node, and its lack of features means less overhead and a smaller memory footprint per item. It's ideal when:

  • You need a simple, large, pure cache of string values (HTML fragments, serialized objects, session blobs).
  • You want to scale vertically across many cores on big machines.
  • You don't need persistence, replication, or data structures.

Its LRU is simpler and its memory model (slab allocation) is predictable for uniform object sizes.

When Redis's Richness Wins

Redis is more than a cache — its data structures let you push logic into the datastore:

Redis Capability Enables
Sorted sets Leaderboards, rate limiters, priority queues, time-ordered feeds
Lists Simple queues, recent-activity streams
Hashes Storing objects field-by-field (partial updates)
Sets Unique tracking (unique visitors, tags), set operations
Pub/Sub & Streams Real-time messaging, WebSocket backplanes, event pipelines
INCR / atomic ops Counters, distributed locks, rate limiting
Persistence Warm restarts (cache survives a reboot); lightweight datastore
Replication + Cluster HA and horizontal scaling built in

Because of this, Redis often serves double duty — cache and session store and rate limiter and pub/sub backplane — reducing the number of systems you operate.

The Threading Nuance

Redis's single-threaded core is a feature, not a bug: it means atomic operations without locks and predictable performance, and it's rarely the bottleneck (network and memory usually saturate first). Memcached's multithreading helps when you're CPU-bound on a single huge node with simple gets/sets. In practice both are extremely fast; the choice is driven by features, not raw throughput.

Persistence: Cache vs Data Store

Memcached: pure cache. Restart = empty cache = a cold-start stampede
           on the origin as everything reloads.

Redis:     optional persistence.
  RDB → periodic point-in-time snapshots (compact, some data loss window)
  AOF → append-only log of every write (durable, larger, replayable)
  → cache survives restarts (warm), and Redis can act as a lightweight DB.
  ⚠️ Persistence adds overhead; for a pure cache you may disable it.

2D minimalistic decision-tree diagram: start node "Need a cache?" branching on questions — "Need data structures, pub/sub, or persistence?" → Yes → Redis; "Just simple key-value at huge scale across many cores?" → Yes → Memcached; with Redis shown as the more common default path and Memcached as the specialized branch

Seeing It in Action

Scenario: Choosing between them for different needs — and why Redis usually wins.

Use case 1 — Session store:
  Redis. Sessions benefit from persistence (survive a Redis restart →
  users don't all get logged out) and TTL-based expiry. Memcached would
  lose all sessions on restart.

Use case 2 — Leaderboard (top 100 players by score, live):
  Redis sorted sets. ONE data structure does it:
    ZADD leaderboard 4200 "player:7"
    ZREVRANGE leaderboard 0 99 WITHSCORES   → top 100 instantly
  Memcached can't do this — you'd rebuild ranking in app code.

Use case 3 — Rate limiting (100 req/min per user):
  Redis atomic INCR + EXPIRE, or a sorted-set sliding window.
  Memcached's lack of atomic multi-step ops makes this fragile.

Use case 4 — Simple huge fragment cache on one big multi-core box:
  Memcached. Pure string blobs, no features needed, and its
  multi-threading fully uses the machine's cores. A legitimate win.

Default recommendation for a new system:
  Start with Redis. Its versatility means one system often covers
  cache + sessions + rate limiting + pub/sub, and its features rarely
  get in the way. Reach for Memcached only for the narrow simple-cache-
  at-scale case where its multi-threaded simplicity is a real advantage.

The bottom line: for pure key-value caching they're comparable, so the decision hinges on whether you'll benefit from Redis's data structures, persistence, and replication. Since most systems eventually want some of those, Redis is the pragmatic default — but Memcached remains an excellent, lean choice for a simple, massive, multi-core cache.

Interview Questions

  1. Q: What are the main differences between Redis and Memcached? Hint: Memcached is a simple, multi-threaded, strings-only key-value cache with no persistence or replication. Redis is a single-threaded-core "data structures server" offering lists/sets/sorted-sets/hashes/streams, pub/sub, optional persistence (RDB/AOF), replication, clustering, transactions, and Lua scripting. For pure key-value caching they perform similarly; Redis wins on versatility, Memcached on lean multi-core simplicity.

  2. Q: When would you specifically choose Memcached over Redis? Hint: For a simple, very large, pure key-value cache of string/blob values where you don't need data structures, persistence, or replication — and you want to fully utilize many CPU cores on big machines (Memcached is multi-threaded). Its predictable slab memory model suits uniform object sizes. It's a deliberately narrow, do-one-thing-well tool.

  3. Q: Redis's core is single-threaded. Why isn't that a problem? Hint: The single-threaded core gives lock-free atomic operations and predictable performance, and Redis is rarely CPU-bound — network and memory usually saturate first. Redis 6+ adds I/O threads for network handling. You scale Redis horizontally via Cluster/sharding rather than threads. Memcached's multithreading only helps in CPU-bound single-node simple-cache scenarios.

  4. Q: How does Redis persistence work and why does it matter for a cache? Hint: RDB takes periodic point-in-time snapshots (compact, small data-loss window); AOF logs every write for durability (larger, replayable). For a cache, persistence means it survives restarts "warm" — avoiding a cold-start stampede where an empty cache dumps all traffic onto the origin. Memcached has no persistence, so a restart empties it entirely.

  5. Q: Give an example where a Redis data structure replaces application logic. Hint: A live leaderboard with sorted sets: ZADD to set scores and ZREVRANGE 0 99 to get the top 100 instantly — ranking maintained by Redis, not rebuilt in app code. Others: atomic INCR+EXPIRE for rate limiting, sets for unique-visitor counting, lists for simple queues, pub/sub for a WebSocket backplane. Memcached would push all this into the application.

References

Dive Deeper