Skip to content

How it works

The application computes a cache key, checks Memcached, and either serves the cached value or falls back to the source, computes the result, and stores it for next time.

The mechanism is a classic cache-aside pattern. The application owns the logic. On read: build a deterministic key from the request, ask Memcached for the value, and if it is there, serve it. If it is not there, query the backend, store the result in Memcached with a TTL, and serve it. On write: update the backend, then either delete the affected cache entry (recommended) or update it (harder, races exist). On miss storms: use a lock or a "single flight" pattern so only one request recomputes the value while others wait or serve stale data.

graph TD
  R[Read request] --> K[Build key]
  K --> C{Memcached?}
  C -->|hit| S[Serve cached value]
  C -->|miss| D[Query backend]
  D --> W[Store in Memcached with TTL]
  W --> S
  U[Write request] --> B[Update backend]
  B --> I[Delete cache entry]

Memcached itself is deliberately simple. It speaks a text and a binary protocol over TCP (or UDP for legacy clients). It has no concept of a schema, no access control, no clustering protocol of its own. Distribution is handled entirely by the client: each client hashes the key with a consistent hashing function and chooses which Memcached server to talk to. That means Memcached scales horizontally by adding servers and updating the client's server list. It is a design choice that has aged very well: Memcached servers are stateless to each other, so a failed server loses its keys and nothing else.

Deploying Memcached correctly

  1. Put it close to the application

    Network latency dominates Memcached performance. Put the Memcached server in the same rack or the same availability zone as the application, not across the internet.

  2. Size by working set, not by total data

    Memcached should hold the data that is read most often. If your working set is 8GB, a 16GB Memcached server has plenty of headroom. Sizing for the entire dataset wastes RAM.

  3. Use a namespace prefix per environment

    Prefix keys with the environment and service ("prod:users:42"). This prevents cross-environment collisions when servers are shared.

  4. Monitor hit rate, evictions, and memory

    A hit rate below 80% usually means the working set does not fit or the TTLs are too short. High evictions mean the cache is too small. Both are actionable.

The hit rate is the single most important operational metric. A hit rate above 90% means the cache is doing its job; below 70% means the backend is doing most of the work anyway, and the cache is overhead rather than savings. Evictions indicate the cache is too small or the TTLs are too long. Memory usage close to the limit is normal; growth without bound is not.