Memcached is an open-source, distributed in-memory key-value cache that keeps frequently requested data in RAM so applications can avoid repeating expensive work, most often queries against a relational or document database. In database systems, it sits in front of the primary data store as a disposable acceleration layer: it never replaces the database, it only remembers recent answers for a limited time.
Memcached was created in 2003 for a high-traffic web community and became a standard building block of large web architectures. Its design is deliberately minimal: no persistence, no replication, no query language and a flat namespace of keys. That simplicity is the source of both its predictable sub-millisecond latency and its main limitations.
How Memcached stores and serves data
Memcached stores opaque values under string keys in a large hash table held entirely in memory. A client sends a command such as get, set, add, delete or incr, and the server answers in constant average time, independent of how many items it holds. Keys are limited to 250 bytes, and values are limited to 1 MB by default, a ceiling that can be raised with a startup option.
Memory is managed by a slab allocator. The server divides RAM into pages of 1 MB, splits each page into fixed-size chunks, and groups chunks of similar size into slab classes. An item is placed in the smallest chunk that fits, which avoids fragmentation but wastes the unused remainder of each chunk. When memory is full, the server evicts items with a segmented least recently used (LRU) policy within the affected slab class.
Every item can carry an expiration time (TTL). Expired items are not removed instantly; they are reclaimed lazily on access or by a background crawler. The server is multithreaded, so a single instance can use many CPU cores and serve hundreds of thousands of requests per second on commodity hardware.
The table below summarizes the core commands and what each one guarantees.
| Command | Purpose | Notable behavior |
|---|---|---|
| get / gets | Read one or more keys | gets also returns a CAS token |
| set | Store a value unconditionally | Overwrites any existing item |
| add | Store only if the key is absent | Useful as a simple lock |
| cas | Store only if unchanged since read | Optimistic concurrency control |
| incr / decr | Atomic counter change | Works on numeric string values |
| delete | Remove a key | Used for cache invalidation |
Distribution across a Memcached cluster
Memcached servers do not know about each other. Distribution is the responsibility of the client library, which hashes each key to choose one server in the pool. Because the servers share nothing, adding capacity means adding nodes, and each node remains fully independent and stateless from the cluster perspective.
Most clients use consistent hashing, often the ketama algorithm, so that adding or removing one server remaps only a fraction of the keys instead of nearly all of them. With naive modulo hashing, a change from ten to eleven servers would invalidate roughly 90 percent of cached keys and send a wave of misses to the database.
Proxies such as mcrouter, and the built-in proxy in recent Memcached releases, add routing, replication across pools and failover on top of the protocol. The following table compares the main distribution strategies.
| Strategy | Keys remapped on node change | Typical use |
|---|---|---|
| Modulo hashing | Nearly all | Small, static pools only |
| Consistent hashing | About 1/N of keys | Default in most client libraries |
| Proxy routing | Configurable | Large fleets, multi-region setups |
Memcached compared with Redis and database buffers
Memcached is most often compared with Redis, another in-memory store from the same family of database systems. Redis offers rich data structures, persistence and built-in replication, whereas Memcached focuses on a plain string cache with multithreaded throughput. Neither replaces the buffer pool inside a database engine such as PostgreSQL or MySQL, which caches disk pages rather than finished application results.
The comparison below shows where each layer fits.
| Property | Memcached | Redis | Database buffer pool |
|---|---|---|---|
| Data model | Strings and byte blobs | Strings, hashes, lists, sets, streams | Disk pages and index blocks |
| Persistence | None | Optional snapshots and logs | Backed by data files |
| Replication | Client or proxy only | Built-in | Part of the database |
| Threading | Multithreaded | Mostly single-threaded command loop | Engine-specific |
| What is cached | Application results | Results or primary data | Raw storage pages |
In practice, Memcached is the better fit for large, simple caches with high concurrency, while Redis wins when the cache must hold structured data, survive restarts or support features such as sorted sets and pub/sub messaging.
Caching patterns and configuration choices
The dominant pattern is cache-aside, also called lazy loading. The application first asks Memcached for a key; on a cache miss it queries the database, stores the result with a TTL and returns it. On a write, the application updates the database and then deletes the cached key rather than rewriting it, which reduces the risk of storing stale data after concurrent updates.
Several settings decide whether the cache behaves well under load. The decision table below lists common situations and recommended choices.
| Situation | Recommended choice | Reason |
|---|---|---|
| Data changes rarely | Long TTL of hours | Maximizes hit ratio |
| Data changes often | Short TTL plus delete on write | Limits staleness |
| Popular key expires under load | Lease or lock with add | Prevents a thundering herd |
| Values above 1 MB | Split or compress values | Avoids slab waste and limits |
| Network exposed beyond host | Bind to private interface, enable SASL or TLS | Blocks abuse and data leaks |
Operators should watch the hit ratio, eviction count and memory per slab class. A healthy cache for read-heavy workloads often reaches a hit ratio above 90 percent, although the realistic target depends on the key distribution and the TTL policy.
Limitations and common mistakes
The most important rule is that Memcached is not a durable store. A restart, an eviction or a node failure silently drops data, so the application must always be able to rebuild every value from the source of truth. Teams that store sessions or queues only in Memcached eventually lose them.
- Cache stampede: many clients miss the same expired key at once and overload the database; leases, early recomputation or jittered TTLs prevent it.
- Stale data after writes: updating the cache before the database commit, or missing an invalidation path, serves outdated values.
- Slab calcification: memory stays assigned to old slab classes after the value sizes change; the automatic slab rebalancer in modern versions reduces this.
- Open UDP or public ports: exposed servers were abused in 2018 for large amplification DDoS attacks, which is why UDP is now disabled by default.
- Hot keys: a single very popular key concentrates load on one node; local in-process caching or key replication spreads it.
In simple terms
Memcached is like a sticky note on a busy librarian’s desk. Looking up a book in the archive takes time, so after answering a popular question the librarian writes the answer on a note. The next person who asks gets the answer instantly from the note.
The notes are temporary. When the desk fills up, the oldest unused notes go in the bin, and the archive remains the real record. That is the key idea: Memcached makes repeated answers fast, but the database still holds the truth.
A practical example
An online news site serves about 20,000 page views per minute during a breaking story. Each article page needs the article body, author profile and a list of related stories, which together require six MySQL queries taking around 40 milliseconds in total. Under peak load, the database CPU climbs above 95 percent and pages start timing out.
The engineering team places three Memcached nodes with 16 GB of RAM each in front of the database and uses cache-aside with a five-minute TTL for article data. When an editor updates a story, the publishing code deletes the related keys so readers see the correction within seconds. A short lock created with add ensures that only one request rebuilds an expired article.
After the change, the hit ratio settles near 97 percent, median page assembly time falls to a few milliseconds and database CPU drops to roughly 30 percent. The site handles the next traffic spike without adding database hardware.