Skip to content

Caching: Levels, Cache-Aside, Read/Write-Through, Write-Behind, Invalidation, Stampedes, Eviction, Redis Clustering ​

"A thundering herd happens when a specific key undergoes heavy read and write activity. As the write activity repeatedly invalidates the recently set values, many reads default to the more costly path." — Nishtala et al., Scaling Memcache at Facebook, NSDI 2013, section 3.2.1

Summary: A cache keeps a copy of an answer closer to the person asking so that the expensive path (a database query, a remote call, a render) runs less often. The copy is the whole problem: it can be stale, it can disappear at the worst moment, it can be shared with the wrong user, and when it disappears for a popular key every request falls on the database at once. Caching well means choosing where the copy lives, how it gets there, how it is invalidated, what happens when it is missing, and what is evicted when memory is full. Focus: Cache levels (browser/HTTP, CDN, gateway, in-process, distributed, database buffer pool, OS page cache); cache-aside, read-through, write-through, write-behind, refresh-ahead, negative caching; stale reads, read-your-writes, the double write race (delete then write vs write then delete), leases, versioned values and compare-and-set, event-driven invalidation via CDC; TTL, purge, tags and surrogate keys, generational keys; stampedes (locks, singleflight, XFetch, stale-while-revalidate, jittered TTL, warming); hot keys and big keys; LRU, LFU, ARC, TinyLFU, W-TinyLFU and Redis maxmemory-policy; sizing and hit-ratio math; memcached vs Redis vs in-process vs Varnish; Redis Sentinel and Redis Cluster (16384 hash slots, hash tags, MOVED/ASK, resharding, READONLY); client-side caching with CLIENT TRACKING and RESP3; observability and security; with Go and Laravel 13 code and tests. Learning goal: For any read path, place each cache level deliberately, pick the read and write pattern and say what consistency it gives, draw the race that would serve stale data and name the mechanism that closes it, protect a hot key from a stampede, size the cache from the working set and the miss penalty, choose an eviction policy and a Redis topology, and implement it in Go and Laravel without the classic bugs.

This chapter sits in the Traffic & Scale group. It owns caching as a system-design decision: placement, patterns, consistency, stampedes, eviction, sizing and the Redis topology for a cache tier. Siblings own the neighbouring mechanics: CDNs owns edge caching as a product (push vs pull, cache hierarchy, video), Forward vs Reverse Proxies owns the proxy that hosts a gateway cache, Redis: Data Structures, Commands & Patterns owns Redis internals and persistence, Consistent Hashing owns ring and slot math, Replication, Read Replicas & Failover owns replica lag, Change Data Capture owns the log-based pipeline used for invalidation, Distributed Locking owns lock safety and fencing, Consistency Models owns the formal guarantees, Write Buffering & Sharded Counters owns write coalescing, and Capacity Estimation owns the estimation method. Persian version: /fa/system-design/caching.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why caches exist and what they costWhy it exists
Facebook memcache, XFetch, TinyLFU, RFC 9111Where it comes from
Browser, CDN, gateway, L1, L2, buffer pool, page cacheCache levels
Lazy loading, the default patternCache-aside
Cache that loads for youRead-through
Write to cache and database togetherWrite-through
Write to cache, flush laterWrite-behind / write-back
Refresh before expiryRefresh-ahead
Caching "not found"Negative caching
TTL, purge, tags, surrogate keys, generationsInvalidation strategies
Stale reads, read-your-writes, the double write raceConsistency problems
Facebook memcache leasesLeases
Versions, compare-and-setVersioned values
CDC and events as invalidationEvent-driven invalidation
Stampede, dogpile, thundering herdStampedes
One key too popular, one value too largeHot keys and big keys
LRU, LFU, ARC, TinyLFU, W-TinyLFU, Redis policiesEviction
Formats, compression, sizesSerialization and compression
Working set, 80/20, miss penaltySizing and hit-ratio math
memcached vs Redis vs in-process vs VarnishProducts
Single node, Sentinel, ClusterRedis topologies
16384 slots, hash tags, MOVED/ASK, READONLYRedis Cluster
CLIENT TRACKING, RESP3, near cacheClient-side caching
Hit ratio, evictions, latencyObservability
Secrets, tenants, poisoningSecurity
Knobs, errors, INFO fieldsMechanics
CodeGo, Laravel
Classic production failuresSolving the classic problems
Which pattern for which workloadChoosing
Monolith to distributed systemIn architecture
Experiments you can runLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Patterns. Who loads the cache, who writes it, and what you get.

PatternRead pathWrite pathConsistency you getMain risk
Cache-aside (lazy loading)App reads cache, on miss reads DB and fillsApp writes DB, then deletes the keyStale for at most TTL, or until delete landsDouble write race, stampede on miss
Read-throughCache library loads on missUsually paired with write-through or deleteSame as cache-aside, logic centralisedLoader errors cached by mistake
Write-throughReads hit warm cacheWrite goes to cache and DB synchronouslyCache matches DB after each writeWrite latency, caches data nobody reads
Write-behind (write-back)Reads hit cacheWrite to cache, flushed to DB later in batchesDB lags; cache is the truth for a whileData loss if the cache dies before flush
Refresh-aheadReads hit cacheBackground refresh before expiryBounded staleness, no miss latencyRefreshes data nobody will read again
Negative caching"Not found" is cached brieflyCreate must delete the markerAbsent rows absorbedA new row invisible until marker expires

Failure modes. Every row is unpacked below.

ProblemPlain wordsTiny exampleWhat stops it
Stale readCache says A, database says BPrice changed, page shows old priceTTL, delete on write, events, versions
Double write raceTwo writers or a reader and a writer interleave and the older value is cached lastReader loads Ann, writer commits Bob and deletes, reader sets AnnDelete (not set) on write, leases, versioned compare-and-set
Stampede / dogpile / thundering herdA hot key expires and every request recomputes it2,000 requests per second all run a 300 ms querySingleflight, lock or lease, XFetch, stale-while-revalidate, jitter
Hot keyOne key gets more traffic than one node can serveCelebrity profile on one Redis shardLocal L1 cache, key splitting, read replicas
Big keyOne value is huge40 MB JSON list in one keySplit, paginate, compress, store a pointer
Cache penetrationRequests for ids that do not existScraper loops over random idsNegative caching, Bloom filter, validation
AvalancheMany keys expire together, or the cache tier diesWarm-up after deploy, all TTLs equalJittered TTL, warming, Gutter-style fallback pool

Eviction policies. What leaves when memory is full.

PolicyKeepsWeak againstWhere you meet it
LRURecently usedOne-off scans flush itRedis allkeys-lru (approximated), memcached per slab class, lru in Go below
LFUFrequently usedOld popularity never fades without decayRedis allkeys-lfu/volatile-lfu (Morris counter + decay)
ARCBalance of recency and frequency, self-tuningPatent history kept it out of many productsZFS, research baseline
TinyLFU / W-TinyLFUAdmits a new key only if it is likely more popular than the victimPure recency bursts (the window fixes that)Caffeine (Java), ristretto and otter (Go)
RandomNothing in particularSkewed workloadsRedis allkeys-random, cheap baseline
TTL-firstKeys closest to expiry leave firstKeys without TTL never leaveRedis volatile-ttl
No evictionEverything; writes fail when fullA cache that must keep servingRedis default noeviction

Redis topologies for a cache tier.

TopologyWhat it givesFailoverScaleLimits
Single nodeSimplest, lowest latencyNoneOne CPU core for commands, one machine's RAMRestart empties a non-persistent cache
Primary + replicas + SentinelHA with automatic promotion; Sentinel is the "configuration provider" for clientsSentinel quorum promotes a replicaReads scale on replicas; writes on one primaryAsync replication loses recent writes on failover
Redis ClusterSharding over 16384 hash slots, each primary with replicasBuilt in, majority of primariesLinear to about 1,000 nodes per the specMulti-key commands only within one slot, database 0 only
Client-side sharding (Predis, mcrouter-style)Many independent nodesNone by itselfAdd nodes, rehash keysA dead node is a cold slice of the keyspace

Why it exists ​

A database query that takes 5 ms and a page that runs 30 of them cost 150 ms and 30 round trips per view. Most of those queries return the same bytes they returned a second ago. A cache turns repeated work into a memory read: microseconds in process, well under a millisecond over a local network to Redis or memcached. It also turns a database that would need ten replicas into one that needs two, because the database only sees the misses.

The trade is simple to state and hard to manage:

Without a cacheWith a cache
One source of truth, always currentTwo copies; the second can be stale
Load on the database grows with trafficLoad grows with misses: (1 - hit ratio) x traffic
Failure of the database is the only failureFailure of the cache can push full traffic to a database sized for misses
Latency is the query latencyLatency is bimodal: fast hits, slow misses (plus the cache hop)
No invalidation logicInvalidation logic in every write path
Memory spent on the database onlyMemory spent twice, plus eviction policy decisions

Everyday picture. A busy café keeps a pot of filter coffee ready instead of brewing each cup. The pot is the cache: most customers get coffee in seconds. Three things go wrong. The coffee goes stale if nobody checks the time it was brewed (TTL). When the pot empties during the morning rush, ten baristas start brewing ten pots at once (stampede), instead of one brewing and the others pouring the last of the old pot (stale-while-revalidate). And if the café switches to a new bean, someone has to pour out the old pot (invalidation), or customers keep getting the old taste until it runs out. This café comes back throughout the page.

Three common misunderstandings, up front ​

  1. "A cache is a performance optimisation I can add later." Once the database is sized for the miss rate, the cache is part of capacity. If it empties (restart, failover, a bad deploy that changes every key), the database receives the full traffic and falls over. Plan for a cold cache as a failure scenario, the way Facebook built Gutter and Cold Cluster Warmup.
  2. "Update the cache when the data changes, so it is always fresh." Setting the new value on every write is the most common source of permanent stale data, because writes and reads interleave. Facebook's paper says it plainly: they "choose to delete cached data instead of updating it because deletes are idempotent".
  3. "A higher hit ratio is always better." A 99% hit ratio on cheap queries can matter less than 80% on one very expensive aggregate. What matters is the miss penalty times the miss rate, the staleness you can tolerate, and the cost of memory.

Where it comes from ​

  • Hardware caches and paging (1960s onwards). CPU caches, virtual memory and the page replacement literature (LRU, Belady's optimal algorithm) gave the vocabulary: hit, miss, working set, eviction. Every software cache inherits it.
  • HTTP caching. HTTP/1.1 introduced Cache-Control, validators and shared caches; the current specification is RFC 9111 (2022), which defines an HTTP cache as "a local store of response messages and the subsystem that controls storage, retrieval, and deletion of messages in it", and separates a "shared cache" from a "private cache". RFC 5861 (2010) added stale-while-revalidate and stale-if-error.
  • memcached (2003) and Redis (2009). memcached made a network hash table with LRU eviction the default application cache. Its memory is split into 1 MB pages assigned to slab classes, "and its own LRU" per class, according to the memcached internals page. Redis added data structures, persistence, replication, and later Redis Cluster (sharding over hash slots) and client-side caching with server-assisted invalidation (Redis 6, RESP3).
  • Facebook, Scaling Memcache at Facebook (NSDI 2013). The reference for cache-aside at scale: memcache as "a demand-filled look-aside cache", delete-on-write, leases against stale sets and thundering herds (peak database query rate fell from 17K/s to 1.3K/s on the keys they measured), McSqueal invalidation from the MySQL commit log, regional pools, Gutter for failed servers, remote markers for read-your-writes across regions, Cold Cluster Warmup.
  • Vattani, Chierichetti, Lowenstein, Optimal Probabilistic Cache Stampede Prevention (VLDB 2015). Named the problem ("cache stampede (also called dog-piling, cache miss storm, or cache choking)") and gave XFetch, the exponential early-expiration rule implemented below.
  • Megiddo and Modha, ARC (FAST 2003) and Einziger, Friedman, Manes, TinyLFU: A Highly Efficient Cache Admission Policy (2015). ARC balances recency and frequency; TinyLFU adds an admission filter and W-TinyLFU a small window, the policy behind Caffeine and, in Go, ristretto and otter.

The concept catalogue ​

Cache levels and what each catches Must-know ​

Every hop can answer from memory; each level catches a different kind of repeatBrowser / HTTPprivate cacheone user, repeatsCache-Control, ETagCDN edgeshared HTTP cachemany users nearbyCloudflare, FastlyGateway / proxyNGINX, Varnishwhole responsesproxy_cache, graceApp in-processL1: Caffeine, otterhot keys, no hopms TTL, per podDistributed cacheRedis, Memcachedshared by all podscache-aside, TTLDB buffer poolPG/InnoDB buffershot pages of tablesautomaticOS page cachekernelfile blocksautomaticmiss goes right (slower, more authoritative); hit returns left (faster, possibly stale)Closer to the user- lowest latency, fewest hops- hardest to invalidate (you do not own it)- must never hold another user's dataCloser to the data- you control invalidation- one network hop (Redis) or none (L1, buffer pool)- shared by every request, so one bug serves everyoneRule of thumbCache as close to the user as correctness allows: public, identical bytes go to the CDN;per-user or permission-filtered data stays in the application tier, keyed by tenant and user.

In plain words: A request passes many places that can answer from memory: the browser, a CDN, the reverse proxy, the application process, a shared cache like Redis, the database's own memory and the operating system's file cache. Each one catches a different kind of repeat.

Common misunderstanding: "We have Redis, so we have caching." Redis is one level. The browser can avoid the request entirely, the CDN can absorb a launch spike, an in-process cache avoids the network hop for the hottest keys, and the database buffer pool is what makes the misses fast. Ignoring the other levels leaves the cheapest wins on the table, and ignoring their staleness causes bugs nobody can reproduce ("it is fixed for me").

Definition: A cache level is any component that stores a copy of a response or object and serves it without going further down the path. Levels differ in who shares the copy (one user, one process, all pods, all users in a region), who can invalidate it (you, the client, a CDN API), what unit they store (HTTP response, object, page, file block) and the cost of a miss.

 1  browser      GET /api/products/42      Cache-Control: max-age=30 -> fresh, no request sent
 2  CDN edge     MISS for this POP          -> forwards to origin shield / gateway
 3  NGINX        proxy_cache MISS           -> forwards to app (proxy_cache_lock: others wait)
 4  app L1       otter MISS (per pod)       -> asks L2
 5  Redis L2     GET t1:product:v3:42 MISS  -> app queries PostgreSQL
 6  PostgreSQL   page in shared_buffers     -> hit in buffer pool, 0.1 ms, no disk read
 7  app          fills Redis, fills L1, returns with Cache-Control: public, max-age=30, s-maxage=60
 8  NGINX, CDN, browser each store their copy; the next identical request stops at the first fresh copy

Real scenario: A product page for an e-commerce site: images and JS from the CDN with year-long TTLs and fingerprinted names; the product JSON cached at the edge for 60 s with s-maxage; the cart never cached at the edge because it is per user. An internal dashboard: no CDN, but an in-process cache for feature flags read 40 times per request. A reporting database: no application cache at all, but shared_buffers and the page cache sized so the hot partitions stay in memory.

LevelProduct examplesShared byInvalidation you controlTypical TTL
Browser / private HTTP cacheChrome, Safari, native HTTP clientsOne userOnly by versioned URLs or short max-ageSeconds to a year (fingerprinted assets)
CDN / shared HTTP cacheCloudflare, Fastly, AWS CloudFront, AkamaiAll users at a POPPurge API, Cache-Tag / Surrogate-KeySeconds to days
Gateway / reverse proxyNGINX proxy_cache, Varnish, Envoy cache filterAll users through that proxyPURGE/BAN, short TTLSeconds to minutes
In-process (L1)Caffeine (Java), ristretto/otter (Go), APCu or Octane tables (PHP), Laravel Cache::memo per requestOne process or podLocal only; needs broadcast for cross-pod invalidationMilliseconds to a minute
Distributed (L2)Redis, Valkey, memcached, AWS ElastiCache, Google MemorystoreAll app serversDelete, tags, versions, eventsSeconds to hours
Database buffer poolPostgreSQL shared_buffers, InnoDB buffer pool, SQL Server buffer poolAll queriesAutomatic, by page replacementUntil evicted
Precomputed resultsPostgreSQL materialized views (REFRESH MATERIALIZED VIEW), summary tablesAll queriesExplicit refresh or a jobUntil the next refresh
OS page cacheLinux page cache under PostgreSQL, Kafka, filesWhole machineAutomaticUntil evicted

Fix / how to use it: Decide per response what the outermost safe level is. Public, identical bytes go as far out as possible; per-user or permission-filtered data stops at the application tier and is keyed by tenant and user. PostgreSQL's documentation suggests a starting value for shared_buffers of "25% of the memory in your system" on a dedicated server, and says more than 40% is unlikely to help "because PostgreSQL also relies on the operating system cache"; size the database's own caches before adding an application cache in front of a database that is simply short of memory.

sql
-- PostgreSQL: is the buffer pool already absorbing the reads? (per table)
SELECT relname,
       heap_blks_hit,
       heap_blks_read,
       round(heap_blks_hit::numeric / nullif(heap_blks_hit + heap_blks_read, 0), 4) AS hit_ratio
FROM pg_statio_user_tables
ORDER BY heap_blks_read DESC
LIMIT 10;

Cache-aside (lazy loading) Must-know ​

In plain words: The application asks the cache first. If the answer is there, use it. If not, read the database, put the result in the cache with a TTL, and return it. When data changes, write the database and then delete the cache key, so the next reader loads the fresh value.

Common misunderstanding: "Cache-aside is simple, so it is safe." The read path has a race with the write path (the stale set), and the miss path has no protection against a stampede. The pattern is the right default, but only with delete-on-write, a bounded TTL and request coalescing. AWS's ElastiCache guide lists the other weakness of lazy loading: a miss costs three trips (cache, database, cache), so the first request after expiry is noticeably slower.

Definition: Cache-aside (Facebook: "demand-filled look-aside cache"; AWS: "lazy loading") keeps the cache outside the data path. The application owns three operations: get from the cache, load + set on a miss, and delete after a committed write. The cache never talks to the database.

 1  reader  GET product:42                 -> miss
 2  reader  SELECT * FROM products WHERE id = 42
 3  reader  SET product:42 <row> EX 600 (+/- jitter)
 4  reader  return row
 5  writer  BEGIN; UPDATE products SET price_cents = 2499 WHERE id = 42; COMMIT;
 6  writer  DEL product:42                 -> next reader repeats 1-4 with the new row

Real scenario: Product and user profile pages; permission sets loaded per request; configuration rows; the rendered fragment of a page; the result of a slow search query. It is the default because only data that is read gets cached, and a cache outage degrades to "slow" rather than "wrong".

Product / libraryHow cache-aside appearsNotes
LaravelCache::remember($key, $ttl, $loader)Atomic only per call; add a lock for stampedes
GoHand-written get/load/set, usually with singleflightSee aside below
Spring@Cacheable (cache-aside via proxy)sync = true coalesces per JVM
RailsRails.cache.fetch(key, expires_in:)race_condition_ttl serves stale briefly
memcachedPlain get/set/delete; meta mg with N/R flags adds a win flagLeases in Facebook's fork
RedisGET/SET key val EX n/DEL, or UNLINK for large valuesLua for atomic check-and-set

Fix / how to use it: In Go, the aside package below adds singleflight coalescing, jittered TTL and negative caching to cache-aside; in Laravel use Cache::remember or Cache::flexible, and delete in an observer that runs after commit. Never set the value in the write path.

Read-through Important ​

In plain words: The cache itself knows how to load a missing value. The application only ever asks the cache; on a miss the cache calls a loader and stores the result.

Common misunderstanding: "Read-through is a different consistency model from cache-aside." It is the same model with the loading code moved into the cache library. The races and stampedes are the same unless the library adds coalescing (Caffeine's LoadingCache and otter's loader do; a naive wrapper does not).

Definition: A read-through cache exposes get(key) and is configured with a load(key) function. It guarantees at most one load per key at a time within that cache instance if, and only if, it implements per-key loading locks.

 1  app      cache.Get("user:7")
 2  cache    miss -> loader("user:7") -> SELECT ... -> value
 3  cache    store value with TTL, return to app
 4  app2     cache.Get("user:7") during step 2 -> waits on the same load (if coalescing)

Real scenario: In-process L1 caches (Caffeine LoadingCache, otter with a loader), DataLoader-style batching in GraphQL resolvers, NGINX proxy_cache (the proxy loads from the upstream on a miss), Varnish, and CDNs in pull mode are all read-through caches.

ProductRead-through featureCoalescing
CaffeineLoadingCache, AsyncLoadingCacheYes, per key
otter (Go)Loader on GetYes, per key
NGINXproxy_cache loads from upstreamWith proxy_cache_lock on
VarnishEvery miss is a backend fetchRequest coalescing by default
CDN pull zoneEdge fetches from origin on missPer POP, often with an origin shield

Fix / how to use it: Use read-through for in-process tiers and HTTP caches where the library does coalescing for you; keep explicit cache-aside for the shared tier so the write path's delete is visible in code review.

Write-through Important ​

In plain words: Every write goes to the cache and to the database in the same operation, so the cache always has the latest value of everything that was written.

Common misunderstanding: "Write-through means the cache can never be stale." It is stale whenever something writes the database without going through the cache (a migration, an admin script, another service, a replica failover), and two concurrent write-throughs can still apply in different orders to cache and database unless the cache write is versioned.

Definition: In write-through, the write path updates the database and synchronously updates the cache; the write is acknowledged only when both succeeded. AWS's guide describes it as adding or updating data in the cache whenever data is written to the database. Usually combined with a TTL so that rarely read data still leaves.

 1  writer A  UPDATE ... SET price = 10 (v=7) ; COMMIT
 2  writer B  UPDATE ... SET price = 12 (v=8) ; COMMIT
 3  writer B  SET product:42 {v:8, price:12}
 4  writer A  SET product:42 {v:7, price:10}     -> older value cached last (without a version check)
 5  fix       SET only if v > cached v (Lua / CAS) -> step 4 is refused

Real scenario: Session stores and shopping carts where the cache is read on every request after every write; leaderboards where the write updates a Redis sorted set and the database; a profile edit where the user must see the change immediately on the next page (read-your-writes).

VariantProductWhat it costs
Application write-throughTwo calls in a service methodWrite latency = DB + cache; partial failure handling
Database-owned write-throughTriggers or CDC feeding the cacheExtra pipeline; see event-driven invalidation
Cache-owned write-throughJCache (JSR-107) CacheWriter, provider-specific writersLibrary ties cache to the store

Fix / how to use it: If you write through, write a versioned value (SetIfNewer in the Go cluster package) and keep a TTL. If the cache write fails after the database commit, delete the key (or let TTL expire it), never retry an unversioned set later.

Write-behind (write-back) Important ​

In plain words: Writes go to the cache only, and a background process copies them to the database later, often in batches. Writes become very fast; the database sees fewer, larger writes.

Common misunderstanding: "Redis has persistence, so write-behind is durable." Redis persistence (RDB snapshots, AOF with appendfsync everysec) can lose the last second or more, and Redis replication is asynchronous, so a failover can lose acknowledged writes. If the cache holds the only copy for a while, that window is data loss, not staleness.

Definition: Write-behind (write-back) acknowledges a write after it is stored in the cache and defers persistence to the system of record. It trades durability and consistency for write throughput and latency. It needs a durable queue or log between the cache and the database to be safe.

 1  t=0     client   INCR views:post:9      (Redis)      -> ack in 0.2 ms
 2  t=0..60 clients  10,000 more INCRs                    -> all in Redis
 3  t=60    flusher  GETSET/GETDEL views:post:9 -> 10,001; UPDATE posts SET views = views + 10001
 4  t=61    Redis primary dies before step 3 for another key -> those increments are gone

Real scenario: View counters, likes, rate counters and analytics where losing a few seconds is acceptable; game state ticks; IoT telemetry aggregation. Not for money, stock or bookings. For counters, Write Buffering & Sharded Counters owns the full design.

ApproachDurabilityProduct notes
Redis counter + periodic flushLoses up to the flush interval plus replication lagUse GETDEL or a rename-swap to avoid double counting
Redis Streams / Kafka as the bufferDurable log; consumer writes the databaseThe log, not the cache, is the source; see messaging
CPU and disk caches (hardware write-back)Battery-backed or flushed on fsyncThe origin of the term

Fix / how to use it: Make the buffer durable (a stream or queue), make the flush idempotent (upserts with a batch id), and keep the database as the system of record for anything that must not be lost.

Refresh-ahead Good to know ​

In plain words: Before a popular entry expires, refresh it in the background so readers never see a miss.

Common misunderstanding: "Refresh-ahead is just a long TTL." A long TTL serves stale data for longer; refresh-ahead keeps the TTL short but replaces the value before it ends, so staleness stays bounded and the miss latency disappears for keys that are actually read.

Definition: Refresh-ahead triggers an asynchronous reload when an entry is read within a refresh window before expiry (Caffeine refreshAfterWrite, memcached meta get R(token) "win for recache" when the remaining TTL is below the token, XFetch's probabilistic test, Laravel Cache::flexible).

 1  t=0    value cached, TTL 60 s, refresh window starts at 50 s
 2  t=52   reader gets the value immediately; one background refresh starts
 3  t=52.3 refresh stores new value with a new 60 s TTL
 4  t=60   nobody ever saw a miss

Real scenario: Exchange rates, feature flags, homepage modules, recommendation lists, a tenant's configuration.

ProductRefresh-ahead feature
CaffeinerefreshAfterWrite
memcachedmeta mg with R(token): returns W to one client when remaining TTL is below the token
Laravel 13Cache::flexible($key, [$fresh, $stale], ...) deferred refresh after the response
NGINXproxy_cache_background_update on with proxy_cache_use_stale updating
Varnishberesp.grace: serves stale while one fetch refreshes

Fix / how to use it: Refresh only on read (so unread keys can expire), refresh once per key (win flag, lock or singleflight), and keep a hard expiry so a broken loader cannot serve stale data forever.

Negative caching Important ​

In plain words: Remember "this does not exist" for a short time, so repeated lookups for missing things do not reach the database.

Common misunderstanding: "Only cache successful results." A bot requesting random ids, a client polling for a resource that is not created yet, or a typo in a popular link can each send all their traffic to the database because nothing is cached. That pattern is called cache penetration.

Definition: A negative cache entry is a marker for "not found" (or "no permission", "empty list") with a short TTL. The write path that creates the row must delete the marker. Errors (timeouts, 500s) are not "not found" and must not be cached as such.

 1  bot     GET /products/99999999        -> cache miss -> SELECT -> 0 rows
 2  app     SET product:99999999 "__none__" EX 30
 3  bot     same request x 5,000 / s       -> cache hit "__none__" -> 404, no query
 4  admin   INSERT product 99999999        -> DEL product:99999999 in the observer

Real scenario: 404 pages at the CDN (proxy_cache_valid 404 10s in NGINX); DNS caches negative answers by the SOA minimum (see IP, DNS & GeoDNS); username availability checks; permission checks that return "denied".

DefenceWhenCost
Negative entry with short TTLMissing ids are repeatedNew rows invisible for up to that TTL unless deleted
Bloom filter of existing idsHuge id space, random probingFalse positives fall through to the DB; rebuild on deletes (see Bloom filters)
Input validation / rate limitObviously invalid idsNone

Fix / how to use it: The Go aside.Cache stores a reserved marker with NegativeTTL and never caches loader errors (TestErrorsAreNotCached); the Laravel ProductCatalog::show stores __none__ through Cache::flexible.

Invalidation strategies: TTL, purge, tags, surrogate keys, generational keys Must-know ​

In plain words: Invalidation is how the cache learns that its copy is wrong. You can wait for it to expire (TTL), remove it by name (purge or delete), remove everything with a label (tags), or change the name so the old copy is never looked up again (generations or versions in the key).

Common misunderstanding: "TTL is a fallback; real systems invalidate explicitly." Explicit invalidation is a message that can be lost, delayed or reordered. TTL is the guarantee that bounds the damage when it is. Use both: explicit invalidation for freshness, TTL as the upper bound on staleness.

Definition: Cache invalidation is any mechanism that ends the life of a cached entry before or at the point it becomes wrong. The strategies differ in precision (one key vs a group), reliability (time always passes; messages can be lost) and cost (a purge API call per key vs one counter increment).

 1  TTL          SET k v EX 300                        -> wrong for at most 300 s
 2  purge        DEL k  / PURGE /path / Fastly purge   -> precise, one name at a time
 3  tag          Cache-Tag: product-42, category-7     -> purge "category-7" clears every page that showed it
 4  generation   key = "search:g{gen}:{hash}"; INCR gen -> old keys unreachable, evicted later
 5  write-through SET k v' on every write              -> fresh, but see the double write race

Real scenario: A CMS that tags each page with the ids of the articles on it and purges by tag on publish (Cloudflare Cache-Tag, Fastly Surrogate-Key, Varnish bans); an e-commerce search cache invalidated by bumping one generation counter per tenant; a pricing service that keeps a 30 s TTL as a safety net under event-driven deletes.

StrategyProduct featurePrecisionMain limit
TTLRedis EX/PX, memcached exptime, HTTP max-age/s-maxageTime onlyStaleness up to TTL
Purge by key or URLRedis DEL/UNLINK, Varnish PURGE (return (purge)), CDN purge APIsOne entryYou must know every key
Ban / filterVarnish ban() on object headers; checked on lookupPatternBan list grows; only objects already cached
Tags / surrogate keysCloudflare Cache-Tag header, Fastly Surrogate-Key (tokens up to 1 KB, header up to 16 KB), Laravel Cache::tagsGroupTag bookkeeping; Laravel tags not supported on file, dynamodb, database or storage drivers
Generational keyVersion counter in the key (g{n}), schema version (v3)Group or everythingOld entries occupy memory until evicted
Write-throughSet on writeOne entryRaces without versions

Fix / how to use it: In Laravel, Cache::tags([...])->flush() for a category, Cache::increment on a generation counter for search, Cache::forget for a single product (all in ProductCatalog and ProductCacheObserver below). At the edge, Cache-Tag or Surrogate-Key headers on the response and a purge call from the same after-commit hook.

Consistency problems: stale reads, read-your-writes and the double write race Must-know ​

The cache-aside race (stale set) and the two fixesReader RCacheDatabaseWriter W1 GET user:7 -> miss2 SELECT -> name=Ann (old)3 UPDATE name=Bob; COMMIT4 DEL user:75 SET user:7 = AnnCache holds Ann until TTL: stale readfor every reader, database says BobFix A: lease (Facebook memcache)1 the miss returns a lease token T4 DEL invalidates T5 SET with T is refused; next reader loads Bobalso: one token per key per 10 s stops herdsFix B: versioned value / compare-and-setrow carries version; cache stores (v, data)5 SET only if v is greater than cached vW also writes (v=8, Bob) or a tombstone v=8Lua script or memcached CAS makes it atomic

In plain words: Because the cache and the database are updated by separate operations, other requests can run between them. The bad cases are: a reader sees an old value (stale read), a user does not see their own change (read-your-writes broken), or the order of operations leaves an old value in the cache with nothing scheduled to remove it until the TTL (the double write race).

Common misunderstanding: "Deleting the key before the database write (delete then write) is safer than after (write then delete)." It is worse. Deleting first opens a window in which a reader misses, reads the old row from the database (the write has not committed) and caches it; the write then commits and nothing deletes the old value. Write then delete has a much smaller window, which leases or versions close completely.

Definition: Stale read: a read returns a value older than the latest committed write. Read-your-writes: after a client writes, its own later reads see that write. Double write race: two update paths (two writers, or a filling reader and a writer) apply their changes to cache and database in different orders, so the cache ends with an older value than the database.

     delete then write (wrong order)              write then delete (right order, rare race)
 1   W: DEL user:7                                R: GET user:7 -> miss
 2   R: GET user:7 -> miss                        R: SELECT -> Ann (old)
 3   R: SELECT -> Ann (old, W not committed)      W: UPDATE -> Bob; COMMIT
 4   W: UPDATE -> Bob; COMMIT                     W: DEL user:7
 5   R: SET user:7 = Ann                          R: SET user:7 = Ann   (needs R slower than W's whole write)
 6   cache = Ann until TTL                        cache = Ann until TTL -> closed by a lease or a version check

Real scenario: A price update that the product page ignores for ten minutes; a user who changes their display name and sees the old one on the next page because the read went to a replica that lags; two admins updating stock where the cache shows the first admin's number. The "double delete" workaround (delete, write, sleep, delete again) shrinks the window but does not close it and adds latency to every write.

ApproachCloses stale setRead-your-writesCost
TTL onlyNo, bounds itNoNone
Write then delete (after commit)Almost; rare race remainsYes on the primaryDelete per write
Delete then writeNo, opens a wide windowNoSame
Double delete with delayNarrows onlyPartiallyWrite latency, still racy
Lease (memcache)YesYesServer support (memcache fork, meta commands, Lua)
Versioned compare-and-setYesYes if writer sets new versionVersion column, Lua or CAS
Read from primary after own write (sticky for N seconds)n/aYesPrimary load; see replication
Facebook remote markerYes for cross-regionYesExtra key per write

Fix / how to use it: Delete after commit (Laravel observers implementing ShouldHandleEventsAfterCommit, Go: delete after tx.Commit() returns), keep a TTL, and for keys where a stale set is costly add a lease or a version check. For read-your-writes across replicas, route the writer's next reads to the primary for a few seconds or until the replica's position passes the commit's LSN.

sql
-- PostgreSQL: a version column makes "newer" unambiguous for the cache
ALTER TABLE products ADD COLUMN version bigint NOT NULL DEFAULT 0;

UPDATE products
SET price_cents = 2499, version = version + 1
WHERE id = 42
RETURNING id, version, price_cents;   -- the writer caches (version, row) or deletes

Leases (Facebook memcache leases) Important ​

In plain words: When you miss, the cache gives you a ticket. You may fill the key only with that ticket. If anybody deletes the key in the meantime, your ticket becomes invalid and your (old) value is refused.

Common misunderstanding: "A lease is a lock." A lease does not block anybody; it decides whose set is accepted and, in Facebook's variant, how often a ticket is handed out. Readers who do not get a ticket are told to wait briefly and retry, which is how leases also absorb a thundering herd.

Definition: From the paper: "a memcached instance gives a lease to a client to set data back into the cache when that client experiences a cache miss. The lease is a 64-bit token bound to the specific key the client originally requested." A delete invalidates the token, which prevents stale sets "in a manner similar to how load-link/store-conditional operates". To mitigate thundering herds, servers "return a token only once every 10 seconds per key"; other clients are told to wait. On the keys they measured, peak database query rate fell from 17K/s to 1.3K/s.

 1  R1  get user:7        -> miss, lease token 1001
 2  R2  get user:7        -> miss, "wait" (token issued less than 10 s ago)
 3  R1  SELECT -> Ann
 4  W   UPDATE -> Bob; COMMIT; delete user:7   -> token 1001 invalidated
 5  R1  set user:7 Ann token=1001  -> refused
 6  R2  retry get user:7  -> miss, new token 1002 -> SELECT -> Bob -> set accepted

Real scenario: Facebook's memcache tier; memcached's meta protocol exposes the same ideas as flags: N(token) "vivify on miss" creates a stub and returns W ("won the right to recache") to one client, Z to others; meta delete I marks an item stale and bumps CAS; X tells a reader the item is stale; CAS on the set gates the update.

ProductLease-like mechanism
Facebook memcache (paper)64-bit lease token per key, invalidated by delete, rate-limited per key
memcached meta commandsmg ... N30 win flag W/Z, md ... I invalidate (stale, bumps CAS), ms ... C<cas> compare
RedisNo built-in lease; emulate with a Lua script: miss creates lease:{k} with a random token (SET NX PX), set checks it, delete removes it
LaravelCache::lock($key, $seconds) plus owner token gives the "one filler" half, not the delete-invalidates half

Fix / how to use it: The Go lease package below models the server side and its tests replay the race; in Redis keep the lease key and the value key in one slot with a hash tag so a single Lua script can check both.

Versioned values and compare-and-set Important ​

In plain words: Store the row's version with the cached value. A write to the cache is accepted only if its version is newer than the one already there, so the order in which writers arrive no longer matters.

Common misunderstanding: "Use timestamps as versions." Clocks on different servers disagree, two writes can share a millisecond, and a replica's updated_at can go backwards after a failover. Use a counter that the database increments in the same statement as the write (a version column, an LSN, or a Kafka offset).

Definition: A versioned value is a cache entry (version, data). Compare-and-set (CAS) is an atomic "set if the current state matches an expectation": memcached cas with the token from gets (or meta ms C<cas>), Redis WATCH/MULTI/EXEC optimistic transactions, or a Lua script that compares versions. With versions, both cache-aside fills and write-through sets can be made safe.

 1  W1  UPDATE ... version 7 -> 8 ; COMMIT ; SetIfNewer(k, 8, Bob)   -> written
 2  R   (loaded version 7 earlier)          SetIfNewer(k, 7, Ann)   -> refused, 7 <= 8
 3  W2  UPDATE ... version 8 -> 9 ; COMMIT ; SetIfNewer(k, 9, Cy)    -> written
 4  W1' late retry of step 1                SetIfNewer(k, 8, Bob)   -> refused

Real scenario: Inventory counts cached by several services; denormalised read models fed by CDC where messages can arrive out of order; user profiles updated by several devices. The same idea appears in optimistic locking on the database side.

MechanismProductAtomicity
gets + casmemcachedPer item; EXISTS on conflict
WATCH + MULTI/EXECRedisTransaction aborts (nil reply) if the key changed
Lua EVAL/EVALSHA, functionsRedisScript runs atomically; keys must share a slot in Cluster
Conditional putDynamoDB ConditionExpression, etcd Txn compareServer-side condition

Fix / how to use it: cluster.SetIfNewer stores {v, d} in a Redis hash only when ARGV[1] > v. The Laravel Product model increments version in updating; a listener can then write (version, row) instead of deleting when write-through is wanted.

Event-driven invalidation (CDC) Important ​

In plain words: Instead of every piece of code remembering to delete cache keys, listen to the database's change log and delete (or update) keys from there. Whoever changed the row, the cache hears about it.

Common misunderstanding: "Publishing a 'product updated' event from the service is the same thing." An application event is only sent by code paths that remember to send it, and it can be sent for a transaction that later rolls back unless it goes through an outbox. The database log sees every committed change, including scripts and migrations.

Definition: Event-driven invalidation subscribes the cache tier to committed changes, either from the database log (Change Data Capture: PostgreSQL logical decoding, MySQL binlog, Debezium) or from an outbox stream, and translates each change into deletes, tag purges or versioned sets. Facebook's McSqueal daemon reads the MySQL commit log, extracts the deletes and broadcasts them to memcache; the web server that made the change also deletes in its own cluster to give that user read-after-write.

 1  app      UPDATE products SET price_cents = 2499 WHERE id = 42; COMMIT   (LSN 0/1A2B3C)
 2  CDC      Debezium reads the WAL change for products id=42 version=9
 3  topic    products.changes  key=42  {op:"u", id:42, version:9, category:7}
 4  invalid. consumer: DEL t1:product:v3:42 ; purge tag category-7 at the CDN
 5  invalid. commit offset after the deletes succeeded (at-least-once; deletes are idempotent)

Real scenario: A monolith's tables shared with a reporting service; several services caching the same product data; an admin tool that writes SQL directly; multi-region invalidation where each region's consumer deletes its local cache.

SourceProductDeliveryNotes
Database logDebezium on PostgreSQL logical decoding or MySQL binlogAt-least-once, ordered per keySees every committed write
Outbox tableOutbox relay to Kafka, RabbitMQ, Redis StreamsAt-least-onceBusiness events, not raw rows
Database notificationsPostgreSQL LISTEN/NOTIFYAt-most-once, only to connected listenersFine for a single region, lossy on disconnect
Redis keyspace notificationsnotify-keyspace-eventsPub/Sub, "fire and forget"Good for local caches mirroring Redis, not for durability

Fix / how to use it: Deletes are idempotent, so at-least-once delivery is fine; if consumers set values, include the version and use SetIfNewer. A lightweight single-region variant with PostgreSQL:

sql
-- PostgreSQL: notify listeners after commit (NOTIFY is delivered at commit time)
CREATE OR REPLACE FUNCTION products_cache_notify() RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify('cache_invalidation',
                    json_build_object('table', TG_TABLE_NAME, 'id', NEW.id,
                                      'version', NEW.version, 'category_id', NEW.category_id)::text);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER products_cache_notify
AFTER INSERT OR UPDATE ON products
FOR EACH ROW EXECUTE FUNCTION products_cache_notify();

Stampede, dogpile, thundering herd Must-know ​

A hot key expires: what reaches the databasetimetimeDBTTL expiresno protection: every miss recomputesTTL expiresprotected: one recompute, others servedCoalescingsingleflight, Varnish,proxy_cache_lockone load per process/nodeLock / leaseCache::lock, SET NX,memcache leaseone load per clusterEarly expirationXFetch: recompute withrising probabilitybefore TTL, no lockServe staleSWR, grace, flexiblerefresh in backgroundusers never waitJitter + warmTTL +/- 10%, prefillafter deploy/failoverno synchronized expiry

In plain words: A popular key expires (or is deleted) and every request that arrives before it is refilled runs the expensive query at the same time. The database sees a wall of identical queries, slows down, which makes the window longer, which lets more requests pile in.

Common misunderstanding: "Our cache hit ratio is 99%, so the database is safe." The hit ratio is an average; a stampede is a burst on one key that lasts for the duration of one recompute. At 2,000 requests per second and a 300 ms query, 600 requests run the same query in parallel, and a query that takes 300 ms alone takes several seconds under that load.

Definition: The VLDB paper: "The cache stampede problem (also called dog-piling, cache miss storm, or cache choking) is a situation that occurs when a popular cache item expires, leading to multiple requests seeing a cache miss and regenerating that same item at the same time." Facebook's "thundering herd" is the same burst caused by writes that repeatedly invalidate a hot key. Defences make exactly one caller recompute and give everybody else something reasonable.

 1  t=0.000  key "home:modules" expires (TTL 60 s, 2,000 req/s)
 2  t=0.000-0.300  600 requests miss and each runs the 300 ms query
 3  t=0.300  database CPU 100%, the query now takes 3 s; misses keep arriving
 4  t=3.000  6,000 queries in flight; connection pool exhausted; timeouts; retries add more
 5  with singleflight: 1 query per pod; with a lock or lease: 1 query in the cluster;
    with XFetch or stale-while-revalidate: 1 query, before or after expiry, and nobody waits

Real scenario: The homepage after a deploy that flushed the cache; a celebrity's profile after an edit; the "today's deals" module at midnight when all keys were set with the same TTL; a CDN purge of a large site followed by a flood to the origin.

DefenceProduct featureScopeWho waitsTrade-off
Request coalescingGo singleflight, Varnish (automatic), NGINX proxy_cache_lock, Caffeine loadingOne process or nodeDuplicates wait for the leaderN pods still make N queries
Lock / leaseRedis SET NX PX, Laravel Cache::lock, memcache leases, memcached N flagWhole clusterOthers wait or serve staleLock expiry vs recompute time; see distributed locking
Probabilistic early expirationXFetchWhole cluster, no coordinationNobodySome recomputes happen early
Stale-while-revalidateRFC 5861, Cache::flexible, Varnish grace, NGINX proxy_cache_use_stale updatingPer cacheNobody (stale served)Bounded staleness
Jittered TTLTTL +/- 10%Many keysn/aPrevents synchronized expiry only
Cache warmingPrefill before traffic, Facebook Cold Cluster WarmupDeploys and failoversn/aNeeds a list of hot keys
Never expire hot keysBackground refresher updates themKnown hot setn/aRefresher is a new component

Fix / how to use it: Combine: singleflight in every process, Cache::flexible or XFetch for hot keys, a lock for very expensive aggregates, jitter on every TTL, and a warm-up step after deploys. The Lab shows 1,000 concurrent misses becoming 1 query with singleflight.

XFetch in one line. The paper's rule is Time() - delta * beta * log(rand()) >= expiry, where delta is how long the last recompute took and beta defaults to 1: "The parameter β defaults to 1 and already provides effective prevention". Because log(rand()) is negative, each reader adds a random head start proportional to the recompute time; the probability of recomputing grows smoothly as expiry approaches, so one reader usually refreshes the key just before it would expire.

Hot keys and big keys Important ​

In plain words: A hot key gets so much traffic that the single node holding it saturates while the rest of the cluster idles. A big key is one value so large that reading, writing, replicating or evicting it blocks other work.

Common misunderstanding: "Sharding solves load." Sharding spreads keys, not requests: every read of one key goes to the same slot and the same primary. Adding shards does nothing for a hot key, and a big key moves as one unit during resharding.

Definition: Hot key: a key whose request rate exceeds what one cache node (one Redis primary, one memcached server) can serve, or what its network link can carry. Big key: a value large enough (megabytes, or collections with millions of members) to cause latency spikes on access, deletion, migration or replication.

 1  t=0   celebrity posts; key user:42:profile read 300,000 times per second
 2  t=1   Redis primary for slot 8811 at 100% CPU; p99 for every key on that shard rises
 3  fix   L1 in-process cache with 1 s TTL -> each of 200 pods reads Redis once per second
 4  fix   or key splitting: user:42:profile#0..#9 on different slots; reader picks one at random
 5  fix   or READONLY replicas for that shard; reads spread over primary + 2 replicas

Real scenario: Flash sale product; configuration blob read on every request; a leaderboard sorted set with 50 million members (big); a "recent orders" list never trimmed (big); one tenant's huge permissions document (big).

ProblemDetectionFixCost
Hot keyredis-cli --hotkeys (needs an LFU policy), MONITOR sampling (expensive), per-shard CPU skew, client metrics per key prefixL1 cache, key splitting (N copies, random suffix), replicas with READONLY, Facebook-style replication within a poolStaleness in L1; N times memory for split copies
Big keyredis-cli --bigkeys, --memkeys, MEMORY USAGE keySplit into a hash or many keys, paginate, compress, store a pointer to object storage, delete with UNLINK (lazy free)More keys, more code
Hot write keySingle counter updated by everyoneSharded counters, write bufferingReads must sum shards

Fix / how to use it: For read-hot keys, an L1 cache with a TTL of one second or less is the cheapest fix and needs no coordination. Facebook replicates "a category of keys within a pool" when the application fetches many keys simultaneously, the data fits in one or two servers and the request rate exceeds one server. For write-hot keys, see Write Buffering & Sharded Counters.

Eviction policies: LRU, LFU, ARC, TinyLFU, W-TinyLFU and Redis maxmemory-policy Must-know ​

In plain words: When the cache is full and a new entry arrives, something has to go. LRU throws out what was used longest ago, LFU what is used least often, TinyLFU asks whether the newcomer is likely to be worth more than the entry it would replace.

Common misunderstanding: "Redis evicts least recently used keys by default." Its default maxmemory-policy is noeviction: when memory is full, writes that need memory fail with an OOM error. A cache instance must set a policy explicitly. Also, Redis LRU and LFU are approximated: "It samples a small number of keys at random and then evicts the ones with the longest time since last access."

Definition: Eviction is removing an entry to make room, as opposed to expiry, which removes it because its TTL ended. The policy decides the victim. Admission (TinyLFU) decides whether a new entry should enter at all.

 1  LRU, capacity 3:   put A, B, C ; get A ; put D  -> evict B (least recently used)
 2  scan pollution:    100 hot keys cached ; one report scans 100 cold keys -> LRU evicts all hot keys
 3  LFU:               A hit 50 times, B hit 2 times -> B evicted; but last week's hot key stays without decay
 4  W-TinyLFU:         new key X arrives; frequency sketch says X seen 1 time, victim seen 40 times -> X not admitted
 5  window (1% LRU):   a burst of a brand-new key is kept in the window long enough to build frequency

Real scenario: A product catalogue with a long tail (LFU or W-TinyLFU beats LRU), a session cache where recency is everything (LRU), a mixed instance holding both cache keys with TTL and persistent keys without (Redis volatile-* policies, though the Redis docs advise two separate instances instead), batch jobs that scan everything once (TinyLFU protects the hot set).

PolicyRedis settingBehaviour (Redis docs)
No evictionnoeviction (default)Writes that need memory return an error; reads still work
LRU, all keysallkeys-lru"a good default option if you have no reason to prefer any others"
LFU, all keysallkeys-lfuApproximated LFU with a Morris counter and decay
Random, all keysallkeys-randomFor uniform access
LRM, all keysallkeys-lrm (Redis 8.6+)Least recently modified: only writes refresh the timestamp
LRU among keys with TTLvolatile-lruBehaves like noeviction if no key has a TTL
LFU among keys with TTLvolatile-lfuSame caveat
Random among keys with TTLvolatile-randomSame caveat
Shortest remaining TTLvolatile-ttlYour code chooses victims by giving them short TTLs
Policy familyProductsMemory overheadStrength
LRUmemcached (segmented LRU per slab class), Redis approximated, GuavaPointers per entrySimple, recency
LFU with decayRedis lfu-log-factor, lfu-decay-time8 bits counter + 16 bits time in RedisFrequency, adapts with decay
ARCZFS ARC, researchGhost lists of evicted keysSelf-tuning recency/frequency
W-TinyLFUCaffeine (4-bit CountMinSketch, "8 bytes per cache entry"), otter v2 ("adaptive W-TinyLFU")Sketch, no ghost entriesBest hit ratio across traces in the paper
TinyLFU admission + SampledLFUristretto ("12 bits per counter"), cost-basedSketchCost-aware: one big item can evict several small ones

Fix / how to use it: For a Redis cache, set maxmemory below the machine's RAM (replication and AOF buffers are not counted toward maxmemory; leave headroom), choose allkeys-lfu for skewed catalogues or allkeys-lru as a default, and raise maxmemory-samples from 5 to 10 if evicted_keys hurts the hit ratio. The Go lru package below demonstrates both the LRU baseline and its scan weakness in tests.

conf
# redis.conf for a node used ONLY as a cache (Redis Open Source 7.x/8.x).
# Persistent data (queues, locks, sessions you cannot lose) goes on another
# instance with noeviction.

maxmemory 12gb                  # leave headroom for replication/AOF buffers and fragmentation
maxmemory-policy allkeys-lfu    # hot keys stay even if not touched in the last second
maxmemory-samples 10            # approximated LRU/LFU: more samples, closer to exact, more CPU
lfu-log-factor 10               # default: counter saturates around 1M hits
lfu-decay-time 1                # default: halve-ish the counter every minute of no access

# A cache can be rebuilt: no RDB snapshots, no AOF.
save ""
appendonly no

# Free memory in background threads instead of blocking on big DEL/evictions.
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
lazyfree-lazy-user-del yes

# Keyspace notifications for expiry-driven invalidation (fire and forget).
notify-keyspace-events Ex

# Redis Cluster mode (one line per node config).
cluster-enabled yes
cluster-config-file nodes-6379.conf
cluster-node-timeout 5000
cluster-require-full-coverage no   # keep serving the healthy slots if one shard is down
cluster-allow-reads-when-down no

# Client-side caching: cap the server-side invalidation table.
tracking-table-max-keys 1000000

Serialization and compression of values Good to know ​

In plain words: Everything in a shared cache is bytes. How you turn objects into bytes decides how big the cache is, how much CPU each hit costs, and whether a deploy with a new class shape can still read old entries.

Common misunderstanding: "Serialize the ORM model and cache it." A serialized Eloquent model or Java object carries class names, lazy relations and internal state; a deploy that changes the class breaks deserialization of every cached entry, and PHP unserialize on data an attacker can write is a code-execution risk. Cache plain arrays or DTOs with an explicit schema version in the key.

Definition: The value format (JSON, MessagePack, Protobuf, PHP serialize, igbinary, gob) and optional compression (LZ4, zstd, LZF, gzip) determine size and CPU. Versioning the key (product:v3:42) lets a new format coexist with old entries until they expire. See Serialization Formats and Compression for the formats themselves.

 1  deploy N    caches product:42 as PHP-serialized App\Models\Product (2.1 KB)
 2  deploy N+1  renames a property; unserialize returns an incomplete object -> 500 errors on every hit
 3  fix         cache toArray() under key product:v3:42; deploy N+1 reads product:v4:42 and misses once
 4  size        same JSON with LZ4: 2.1 KB -> about 0.7 KB (typical for repetitive JSON; measure yours)

Real scenario: A cache tier at 80% memory where switching to igbinary plus LZ4 freed a third of it; a Go service and a PHP service sharing keys, which requires a neutral format (JSON or MessagePack); a big-key problem solved by compressing a 4 MB HTML fragment.

OptionProductNotes
PHP serializeLaravel default for most storesPHP-only; never on untrusted data
igbinary, MessagePack, JSONphpredis Redis::SERIALIZER_IGBINARY, SERIALIZER_MSGPACK, SERIALIZER_JSONConfigured in options.serializer
LZF, zstd, LZ4phpredis Redis::COMPRESSION_LZF, COMPRESSION_ZSTD, COMPRESSION_LZ4Configured in options.compression
encoding/json, MessagePack, ProtobufGoChoose per key family; keep a version byte
Built-in compression thresholdmemcached clients (e.g. compress above N bytes)Saves memory, costs CPU on every hit

Fix / how to use it: Cache arrays, not models; version the key; compress values above a threshold (a few KB); measure the CPU per hit.

Cache sizing and hit-ratio math Must-know ​

In plain words: You do not need to cache everything, only the part that is read again soon (the working set). Because popularity is skewed, a cache holding a small share of keys can serve most requests. What the remaining misses cost decides whether that is good enough.

Common misunderstanding: "Going from 95% to 99% hit ratio is a 4% improvement." For the database it is a fivefold reduction: misses go from 5% to 1% of traffic. Hit ratio improvements matter most at the top end.

Definition: Hit ratio h = hits / (hits + misses). Miss penalty = extra latency and backend cost of one miss. Effective latency = t_hit + (1 - h) x miss penalty. Backend load = (1 - h) x request rate. Working set = the set of keys accessed within a time window (for example one TTL); a cache smaller than the working set thrashes.

 1  traffic           20,000 reads/s; Redis hit 0.3 ms; miss penalty (query + set) 8 ms
 2  h = 0.95          DB load 1,000 q/s ; mean latency 0.3 + 0.05 x 8 = 0.70 ms
 3  h = 0.99          DB load   200 q/s ; mean latency 0.3 + 0.01 x 8 = 0.38 ms
 4  working set       2 M products touched per hour x 1.5 KB = 3 GB ; x 1.3 overhead and fragmentation = 3.9 GB
 5  skew (measured)   LRU holding 10% of 10,000 keys under Zipf(1.1): hit ratio 0.78 (go test -run Skew -v ./lru)

The numbers in lines 1 to 4 are a back-of-the-envelope example, not a benchmark; the method is in Capacity Estimation. Line 5 is the output of the test in this chapter's Go module.

Real scenario: Sizing ElastiCache nodes for a catalogue; deciding whether a 64 GB Redis is worth it versus a database read replica; explaining why a cache with 99% hit ratio still has a database at 80% CPU (the 1% are expensive aggregates).

QuantityHow to get itProduct source
Hit ratiokeyspace_hits / (keyspace_hits + keyspace_misses)Redis INFO stats
Evictionsevicted_keys per secondRedis INFO stats
Expiriesexpired_keysRedis INFO stats
Memoryused_memory, mem_fragmentation_ratio, mem_not_counted_for_evictRedis INFO memory
memcachedget_hits, get_misses, evictions, per-slab statsstats, stats slabs
Miss penaltyLoader latency histogram (p50, p99) and DB time per missApplication metrics

Fix / how to use it: Size from the working set, not from the table size; watch evicted_keys: if evictions are high and hit ratio low, the cache is too small or the policy wrong; if evictions are near zero, you are paying for memory you do not need.

Products: memcached vs Redis vs in-process vs Varnish and HTTP caches Must-know ​

In plain words: memcached is a fast, simple, multi-threaded key-value cache. Redis is a data-structure server that is often used as a cache. In-process caches live inside your application's memory. Varnish and other HTTP caches store whole HTTP responses.

Common misunderstanding: "Redis is always better than memcached." For a plain key-value cache of small objects, memcached's multi-threaded design and slab allocator are hard to beat on throughput per node and are operationally simple; Redis wins when you need data structures (sorted sets, hashes, streams), Lua, replication, Cluster or client-side caching.

Definition: The choice is by unit and sharing: objects shared across servers (memcached, Redis, Valkey), objects per process (Caffeine, ristretto, otter, APCu), whole HTTP responses (Varnish, NGINX, CDNs).

 1  browser -> Cloudflare (HTTP, per POP)  -> Varnish (HTTP, per site) -> app pod
 2  app pod -> otter L1 (objects, per pod, 1 s TTL)
 3  app pod -> Redis Cluster L2 (objects, all pods, 10 min TTL)
 4  app pod -> PostgreSQL (shared_buffers, page cache)

Real scenario: A news site behind Varnish with grace mode and bans per article; a Go API with ristretto in front of Redis; a Laravel monolith with Redis for cache, locks, sessions and queues on separate databases or instances.

AspectmemcachedRedis / ValkeyIn-process (Caffeine, ristretto, otter)Varnish / NGINX / CDN
UnitOpaque bytesStrings, hashes, lists, sets, sorted sets, streamsNative objectsHTTP responses
ThreadsMulti-threadedSingle command thread (I/O threads optional)Your processMulti-threaded
Memory managementSlab classes of 1 MB pages, LRU per classmaxmemory + policy, jemallocLibrary policy (W-TinyLFU etc.)Storage backend, LRU
Max item1 MB default (configurable)512 MB per string valueRAM of the processConfigurable
Replication / HANone built in (client-side, mcrouter)Replicas, Sentinel, ClusterNoneNone (CDN vendors replicate)
Invalidationdelete, CAS, meta flagsDEL/UNLINK, Lua, keyspace notifications, CLIENT TRACKINGLocal onlyPURGE, ban, tags, surrogate keys
Stampede toolsMeta N/R win flagsLua, SET NX locksLoading with per-key futuresRequest coalescing, grace
Typical latencySub-millisecond on a LANSub-millisecond on a LANNanoseconds to microsecondsMicroseconds local, milliseconds from CDN POP

Fix / how to use it: Start with Redis (or memcached) as L2, add an L1 only for measured hot keys, and put an HTTP cache in front only for responses that are identical for many users. The NGINX and Varnish configurations below show stampede protection and stale serving at the HTTP tier.

conf
# NGINX as a shared HTTP cache in front of the application.
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app:100m
                 max_size=20g inactive=1h use_temp_path=off;

server {
    listen 443 ssl;
    server_name shop.example.com;

    location /api/products/ {
        proxy_pass http://app_upstream;
        proxy_cache app;
        proxy_cache_key "$scheme$host$request_uri";
        proxy_cache_valid 200 60s;
        proxy_cache_valid 404 10s;                  # negative caching at the edge

        proxy_cache_lock on;                        # one request fills a missing entry
        proxy_cache_lock_timeout 5s;
        proxy_cache_use_stale updating error timeout http_500 http_502 http_503 http_504;
        proxy_cache_background_update on;           # refresh stale entries in a subrequest

        proxy_ignore_headers Set-Cookie;            # never cache a personalised response...
        proxy_cache_bypass $cookie_session;         # ...so logged-in traffic skips the cache
        proxy_no_cache $cookie_session;

        add_header X-Cache-Status $upstream_cache_status always;
    }
}
vcl
vcl 4.1;

backend app { .host = "app.internal"; .port = "8080"; }

acl purgers { "localhost"; "192.0.2.0"/24; }

sub vcl_recv {
    if (req.method == "PURGE") {                     # explicit purge of one URL
        if (!client.ip ~ purgers) { return (synth(405, "Not allowed.")); }
        return (purge);
    }
    if (req.method == "BAN") {                       # tag-style ban by surrogate key
        if (!client.ip ~ purgers) { return (synth(405, "Not allowed.")); }
        ban("obj.http.Surrogate-Key ~ " + req.http.X-Ban-Key);
        return (synth(200, "Banned."));
    }
    if (req.http.Cookie ~ "session=") { return (pass); }
}

sub vcl_backend_response {
    set beresp.ttl = 60s;
    set beresp.grace = 5m;    # serve stale for 5 minutes while one fetch refreshes
    set beresp.keep = 1h;     # keep for conditional GET (304) revalidation
}

Redis topologies: single node, replicas with Sentinel, Cluster Important ​

In plain words: One Redis is simplest. Add replicas and Sentinel when you need it to survive a node failure. Use Redis Cluster when one machine's memory or CPU is not enough.

Common misunderstanding: "Sentinel shards my data." Sentinel only monitors and fails over one primary and its replicas; all writes still go to one primary. Sharding is Redis Cluster (or client-side sharding).

Definition: Redis Sentinel provides "monitoring, notifications and acts as a configuration provider for clients"; on failure it promotes a replica, reconfigures the others and tells clients the new address. Redis Cluster splits the keyspace into 16384 hash slots over several primaries, each with replicas, and fails over without Sentinel. Persistence trade-offs (RDB, AOF, none) are covered in Redis; a pure cache usually disables both.

 1  Sentinel: client asks sentinels "SENTINEL get-master-addr-by-name cache" -> 192.0.2.10:6379
 2  primary dies; sentinels agree (quorum 2 of 3) -> promote replica 192.0.2.11
 3  client reconnects, asks again -> 192.0.2.11:6379 ; writes acked by the old primary but not replicated are lost
 4  Cluster: client loads CLUSTER SLOTS, hashes each key, talks to the owning primary directly

Real scenario: A small SaaS with one Redis and a cold-start plan; a mid-size app with Sentinel for sessions and locks; a large catalogue cache on a 9-primary Cluster; AWS ElastiCache "cluster mode enabled" (Redis Cluster) vs "disabled" (primary with replicas).

TopologyProductsLaravelGo (go-redis)
SingleRedis, Valkeyredis connectionredis.NewClient
SentinelRedis Sentinel, ElastiCache Multi-AZ (managed failover)phpredis/Predis sentinel optionsredis.NewFailoverClient
ClusterRedis Cluster, ElastiCache cluster mode, Memorystore Clusterclusters key, options.cluster = redisredis.NewClusterClient
Client-side shardingPredis sharding, twemproxy, mcrouterRemove options.cluster (Predis)Ring client (redis.NewRing)

Fix / how to use it: For a cache, prefer Cluster once you need more than one primary, because it fails over by itself and clients route directly. Laravel's documentation notes that client-side sharding "does not handle failover; therefore, it is primarily suited for transient cached data that is available from another primary data store".

Redis Cluster: hash slots, hash tags, MOVED/ASK, resharding, READONLY Must-know ​

Redis Cluster: key -> CRC16 mod 16384 -> slot -> primaryClient (go-redis, phpredis)slot map from CLUSTER SLOTSHASH_SLOT = CRC16(key) mod 16384{user:7}:cart and {user:7}:feedshare one slot (hash tag)Primary Aslots 0-5460Replica of AREADONLY reads, stale okasync replPrimary Bslots 5461-10922Replica of BREADONLY reads, stale okasync replPrimary Cslots 10923-16383Replica of CREADONLY reads, stale okasync replGETRedirections-MOVED 3999 host:port: slot owner changed for good; update the slot map and retry there.-ASK 3999 host:port: slot is migrating; send ASKING then the command to that node, once; keep the map.-TRYAGAIN: multi-key op on a slot being split mid-move.-CROSSSLOT: keys of one command are in different slots.Limits a cache must design aroundmulti-key commands, MULTI and Lua only within one slotno SELECT: database 0 onlyasync replication: acked writes can be lost on failoverresharding moves slots with MIGRATE (or atomic slot migration); keys move, clients follow MOVED

In plain words: Redis Cluster cuts the keyspace into 16384 numbered slots. Each primary owns a range of slots. The client computes the slot of a key itself and talks to the right node; if it guessed wrong, the node tells it where to go.

Common misunderstanding: "Redis Cluster is a drop-in replacement for one Redis." Commands that touch several keys (MGET, MSET, DEL with several keys, transactions, Lua scripts) work only if all keys are in the same slot; otherwise the server replies CROSSSLOT Keys in request don't hash to the same slot. There is only database 0 (no SELECT). And replication is asynchronous: the spec says "There is always a window of time when it is possible to lose writes during partitions".

Definition: HASH_SLOT = CRC16(key) mod 16384, CRC16 being the XMODEM variant (check value 31C3 for "123456789"). Hash tags: if the key contains {...} with at least one character inside, only that substring is hashed, so {user1000}.following and {user1000}.followers land in one slot. A node that does not own the slot replies -MOVED <slot> <host:port> (update the map) or, during migration, -ASK <slot> <host:port> (send ASKING then the command to that node, once, without updating the map). Multi-key operations during a split migration return -TRYAGAIN. READONLY on a connection to a replica allows reads of "possibly stale data".

 1  client   CLUSTER SLOTS -> 0-5460 A, 5461-10922 B, 10923-16383 C
 2  client   GET somekey -> slot 11058 -> C
 3  admin    redis-cli --cluster reshard ... moves slot 11058 from C to D
 4  client   GET somekey -> C replies -ASK 11058 192.0.2.40:6379 (key already moved)
 5  client   ASKING ; GET somekey on D -> value (map still says C)
 6  admin    migration done; C replies -MOVED 11058 192.0.2.40:6379 -> client updates the map

Real scenario: Cart and its items under {cart:9f2} so one Lua script can update both; per-tenant keys under {t42} (careful: one huge tenant becomes one hot slot); adding a node and moving 1,000 slots during the day while clients follow MOVED; read-heavy cache reading from replicas with ReadOnly: true in go-redis.

ItemRulePractical consequence
Slots16384, owned by primariesMax 16384 primaries; spec suggests about 1,000 nodes
HashingCRC16(key) & 16383Clients compute it; CLUSTER KEYSLOT to check
Hash tagFirst { to first } after it, non-emptyfoo{}{bar} hashes the whole key; foo{bar}{zap} hashes bar
Multi-keySame slot onlyDesign key families with a shared tag
-MOVEDPermanent owner changeRefresh slot map
-ASKSlot migratingASKING + retry once, keep map
-TRYAGAINMulti-key op on a slot whose keys are split mid-migrationRetry later
-CROSSSLOTKeys in different slotsUse hash tags or split the command
READONLY / READWRITEReplica reads on/off per connectionStale reads allowed, lag-dependent
cluster-require-full-coverageyes: stop serving if any slot is uncoveredno keeps healthy slots serving (cache friendly)
cluster-allow-reads-when-downDefault noyes favours read availability
Reshardingredis-cli --cluster reshard, add-nodeKeys move with MIGRATE; Redis 8.4+ also has atomic slot migration

Fix / how to use it: The Go cluster package computes KeySlot exactly as the spec (tests check somekey = 11058 and foo{hash_tag} = 2515 from the Redis docs), groups a product's keys under one tag, and builds a ClusterClient with ReadOnly and RouteByLatency. Laravel's config/database.php gets a clusters entry and options.cluster = redis.

Client-side caching: CLIENT TRACKING and RESP3 Important ​

In plain words: The application keeps a local copy of hot Redis values in its own memory, and Redis promises to tell it when any of those keys change. You get in-process speed without guessing a TTL.

Common misunderstanding: "An in-process cache is always stale for up to its TTL." With server-assisted invalidation the local copy is dropped when the key is modified; staleness is the invalidation delay (usually milliseconds), not the TTL. The catch is that invalidations are asynchronous messages: during a disconnect the client must flush its local cache.

Definition: CLIENT TRACKING ON makes the server remember which keys a connection read (default mode, stored in the Invalidation Table) or which prefixes it subscribed to (BCAST PREFIX user:, no server memory per key), and send invalidation messages when they change. With RESP3 (Redis 6+) invalidations arrive as push messages on the same connection; with RESP2 they go to another connection via REDIRECT <client-id> and the __redis__:invalidate channel. OPTIN caches only keys marked with CLIENT CACHING yes; NOLOOP suppresses invalidations for the connection's own writes. When the invalidation table is full (tracking-table-max-keys), Redis evicts entries "by pretending that such key was modified" and sends invalidations.

 1  pod A  HELLO 3 ; CLIENT TRACKING ON
 2  pod A  GET flags:t1 -> {"new_checkout":true}   (stored locally; server records A read flags:t1)
 3  pod A  GET flags:t1 x 40 per request           -> local hits, no network
 4  admin  SET flags:t1 {"new_checkout":false}
 5  Redis  push to A: invalidate ["flags:t1"]       -> A drops the local copy
 6  pod A  next GET goes to Redis, caches the new value

Real scenario: Feature flags and configuration read many times per request; permission sets; exchange rates. go-redis v9 exposes it as ClientSideCacheConfig with Protocol: 3 (and v9.24 adds it to ClusterOptions, one cache per node).

ModeServer memoryInvalidations sentUse
Default (tracking)Per key read by each clientOnly for keys that client readModerate key sets
BCAST PREFIXNone per keyEvery key under the prefixSmall, well-prefixed hot sets
OPTIN / OPTOUTOnly for opted keysSame as defaultSelective caching
NOLOOPSameNot for own writesWriter keeps its fresh local copy

Fix / how to use it: Use client-side caching for small, very hot, rarely written keys; cap entries; flush the local cache on reconnect; do not use it for keys written many times per second (invalidation traffic exceeds the benefit).

Observability: hit ratio, evictions, latency Important ​

In plain words: Measure how often the cache answers, how often it throws data away, how long hits and misses take, and how much load reaches the database. A cache you do not measure eventually turns into an outage you do not understand.

Common misunderstanding: "Redis INFO hit ratio is my application hit ratio." Redis counts every key lookup, including locks, rate-limit counters and session reads, in keyspace_hits and keyspace_misses. Measure per key family in the application (product:* hit ratio, search:* hit ratio) to see what matters.

Definition: Core signals: hit ratio per key family, miss penalty (loader latency), cache latency p50/p99, evictions per second, expired keys per second, memory used and fragmentation, connected clients, commands per second per shard, replication lag, and database queries per second attributable to misses.

 1  09:00  hit ratio product:* 0.97, evicted_keys 0/s, DB 300 q/s
 2  09:05  deploy changes key prefix v3 -> v4 (every key misses)
 3  09:05  hit ratio 0.10, DB 9,000 q/s, p99 2.4 s ; alert fires on DB, not on cache
 4  fix    alert on hit-ratio drop per family; warm v4 keys before switching; roll out by percentage

Real scenario: A slow memory leak from keys without TTL (memory grows, evictions start, hit ratio falls); a big key causing 50 ms spikes (Redis SLOWLOG, LATENCY DOCTOR); a hot shard (per-node CPU in Cluster).

SignalRedismemcachedApplication
Hit / misskeyspace_hits, keyspace_missesget_hits, get_missesCounter per key family
Evictionsevicted_keysevictionsn/a
LatencyLATENCY, SLOWLOG, INFO commandstatsstats timings via proxiesHistogram per call
Memoryused_memory, mem_fragmentation_ratiobytes, limit_maxbytesL1 size
Big/hot keys--bigkeys, --memkeys, --hotkeyslru_crawler metadumpTop keys by client sampling

Fix / how to use it: Emit metrics from the cache wrapper (the Go aside.Cache.Loads() counter is the seed of one), alert on hit ratio per family and on database load, and track evicted_keys against memory.

Cache security: secrets, tenants, poisoning Important ​

In plain words: A shared cache is a shared database without row-level security. Anything you put in it can be read by every process that can reach it, and any key that two users can compute will be served to both.

Common misunderstanding: "It is only a cache, so it does not need protecting." Caches hold session tokens, personal data, permission sets and rendered pages with names and addresses. An unauthenticated Redis on a reachable network is a classic breach, and a CDN that caches a page with Set-Cookie or personal data serves it to strangers.

Definition: Cache security covers access control (Redis ACLs and requirepass, TLS, private networks), data minimisation (no secrets or raw tokens in a shared cache; hash or encrypt where needed), key namespaces per tenant and per environment (prefix, or separate databases or instances), HTTP cache rules (Cache-Control: private or no-store for personal responses, Vary correctness) and cache poisoning defences (never include unvalidated headers in a cache key or response).

 1  bug      key = "dashboard:" . $userId   (tenant missing)
 2  tenant A user 7 caches their dashboard
 3  tenant B user 7 (same numeric id, other tenant) reads "dashboard:7" -> sees tenant A's data
 4  fix      key = "t{tenant}:u{user}:dashboard:v2" ; per-tenant prefix ; tests that assert the key shape

Real scenario: A staging and a production Laravel app sharing one Redis with the same REDIS_PREFIX; Laravel's Redis documentation warns that instances on the same server "will use the same prefix and read each other's data". A CDN caching /account because the origin forgot Cache-Control: private. A web cache poisoning attack via an unkeyed X-Forwarded-Host header.

RiskControlProduct
Open cache serverACL users, TLS, private subnet, no public portRedis ACL, ElastiCache in-transit encryption
Cross-tenant leakageTenant in every key; separate instances for strict isolationREDIS_PREFIX, CACHE_PREFIX per app and environment
Secrets in cacheStore references, not secrets; short TTL; encrypt valuesLaravel Crypt before caching sensitive values
Personal data at CDNCache-Control: private/no-store, bypass on session cookieNGINX proxy_cache_bypass $cookie_session
Cache poisoningOnly cache on normalised, keyed inputsCDN cache-key configuration
Deserialization attacksJSON or igbinary of arrays, never untrusted unserializeLaravel cache stores

Fix / how to use it: The Laravel ProductCatalog::key() puts the tenant and a schema version in every key; config/cache.php sets a CACHE_PREFIX per environment; the NGINX configuration bypasses the shared cache for requests with a session cookie.

Mechanics ​

The exact knobs ​

ProductKnobDefaultWhat it does
Redismaxmemory0 on 64-bit (no limit)Memory limit that triggers eviction
Redismaxmemory-policynoevictionVictim selection (see Eviction)
Redismaxmemory-samples5Keys sampled per eviction; 10 is "very close" to true LRU per the docs
Redislfu-log-factor, lfu-decay-time10, 1Counter saturates around 1M hits; decays every minute
Redislazyfree-lazy-eviction, lazyfree-lazy-expirenoFree memory in a background thread
Redisnotify-keyspace-events"" (off)Keyspace notifications (Ex = expired events)
Redistracking-table-max-keys1000000Size of the client-side caching invalidation table
Redis Clustercluster-node-timeout15000 msFailure detection time
Redis Clustercluster-require-full-coverageyesStop accepting queries if a slot is uncovered
memcached-m64 MBMemory for items, in 1 MB pages
memcached-I1 MBMax item size
NGINXproxy_cache_lockoffOne request populates a new element
NGINXproxy_cache_lock_timeout5sWaiters give up and go to the upstream
NGINXproxy_cache_use_staleoffupdating, error, timeout, http_5xx
NGINXproxy_cache_background_updateoffRefresh stale entries in a subrequest
Varnishberesp.grace, default_gracedefault_graceServe stale while fetching
Varnishberesp.keep0Keep for 304 revalidation
HTTPCache-Control: max-age, s-maxage, stale-while-revalidate, stale-if-error, private, no-storen/aRFC 9111, RFC 5861
LaravelCACHE_STORE, CACHE_PREFIX, REDIS_CACHE_CONNECTION, REDIS_CACHE_LOCK_CONNECTIONdatabase store by defaultStore choice and namespaces
go-redisReadOnly, RouteByLatency, RouteRandomly, MaxRedirects, Protocol, ClientSideCacheConfigfalse, false, false, 3, 3 (RESP3), nilCluster routing and client-side caching

Errors and replies you will see ​

Reply / errorProductMeaningAction
OOM command not allowed when used memory > 'maxmemory'.Redis with noeviction or volatile-* and no TTL keysWrite refusedSet a policy for caches; add TTLs
-MOVED 3999 127.0.0.1:6381Redis ClusterSlot owned elsewhereUpdate slot map, retry
-ASK 3999 127.0.0.1:6381Redis ClusterSlot migratingASKING, retry once
-TRYAGAINRedis ClusterMulti-key op during split migrationRetry later
CROSSSLOT Keys in request don't hash to the same slotRedis ClusterMulti-key command across slotsHash tags
CLUSTERDOWNRedis ClusterCluster in fail stateFallback to DB with coalescing
READONLY You can't write against a read only replica.Redis replicaWrite sent to a replica (stale topology)Refresh topology
EXISTS / NOT_FOUND on casmemcachedCAS token stale / item goneReload and retry, or delete
W, Z, X flags on mgmemcached metaWon recache / someone else won / staleRecompute only on W
LockTimeoutExceptionLaravel Cache::lock()->block()Lock not acquired in timeServe stale or degrade
X-Cache-Status: HIT/MISS/STALE/UPDATING/EXPIRED/BYPASSNGINX $upstream_cache_statusCache result per requestLog and graph

Where the time goes ​

OperationOrder of magnitudeSource / note
In-process map lookupTens of nanosecondsMemory access; no serialization
Redis or memcached GET on the same LANSub-millisecond, dominated by the network round tripMeasure with redis-cli --latency
Cross-zone Redis callNoticeably more than in-zone; often the largest part of a hitMeasure; see Latency Budgets
Typical indexed database queryMillisecondsDominated by planning, locks, I/O on miss
Miss in cache-asideCache round trip + query + setThree trips, as AWS notes for lazy loading

These are orders of magnitude to reason with, not measurements of your system; the latency chapter owns the canonical numbers.

Go ​

Before: the naive cache-aside ​

go
// Package before is the naive cache-aside that most codebases start with.
// It works on a quiet day. Under load it has three defects that the rest of
// the chapter fixes: every concurrent miss hits the database (stampede), every
// key expires at the same moment (synchronized expiry), and the write path
// sets the cache after the database write, so two writers can leave the older
// value in the cache indefinitely (double-write race).
package before

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"
	"time"
)

// ErrMiss is returned by a Store when the key is absent.
var ErrMiss = errors.New("cache miss")

// Store is the shared cache (Redis, Memcached) seen as bytes.
type Store interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, val []byte, ttl time.Duration) error
}

// Product is the cached entity.
type Product struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Price int64  `json:"price_cents"`
}

// DB is the source of truth.
type DB interface {
	LoadProduct(ctx context.Context, id int64) (Product, error)
	SaveProduct(ctx context.Context, p Product) error
}

// Catalog reads through the cache by hand.
type Catalog struct {
	Cache Store
	DB    DB
}

// Get: look in the cache, on a miss load and set with one fixed TTL.
func (c *Catalog) Get(ctx context.Context, id int64) (Product, error) {
	key := "product:" + strconv.FormatInt(id, 10)
	if b, err := c.Cache.Get(ctx, key); err == nil {
		var p Product
		if json.Unmarshal(b, &p) == nil {
			return p, nil
		}
	}
	// Defect 1: 1,000 concurrent requests that miss all run this query.
	p, err := c.DB.LoadProduct(ctx, id)
	if err != nil {
		return Product{}, err
	}
	b, _ := json.Marshal(p)
	// Defect 2: every key written in the same minute expires in the same minute.
	_ = c.Cache.Set(ctx, key, b, 10*time.Minute)
	return p, nil
}

// Update: write the database, then overwrite the cache with the new value.
// Defect 3: writer A and writer B can interleave as
// A.db, B.db, B.cache, A.cache, leaving A's older value cached for 10 minutes.
func (c *Catalog) Update(ctx context.Context, p Product) error {
	if err := c.DB.SaveProduct(ctx, p); err != nil {
		return err
	}
	b, _ := json.Marshal(p)
	return c.Cache.Set(ctx, "product:"+strconv.FormatInt(p.ID, 10), b, 10*time.Minute)
}

After: cache-aside with singleflight, jitter and negative caching ​

go
// Package aside is a production-shaped cache-aside (lazy loading) helper:
//
//   - request coalescing with golang.org/x/sync/singleflight, so N concurrent
//     misses for one key in one process cause one load;
//   - jittered TTLs, so keys written together do not expire together;
//   - negative caching, so a flood of lookups for a missing id is absorbed;
//   - invalidation by delete after the database commit (never set-on-write),
//     which is the write path Facebook describes for memcache.
//
// The shared cache is behind the Store interface; MemStore is the in-memory
// implementation used by the tests. A Redis Store is a thin adapter over
// go-redis Get/Set/Del.
package aside

import (
	"context"
	"errors"
	"math/rand/v2"
	"sync"
	"time"

	"golang.org/x/sync/singleflight"
)

// ErrMiss means the key is not in the cache.
var ErrMiss = errors.New("cache miss")

// ErrNotFound means the source of truth has no such row. It is cached
// (negative caching) so repeated lookups do not reach the database.
var ErrNotFound = errors.New("not found")

// negativeMarker is the value stored for "known absent". Real code may use a
// typed envelope; a reserved byte string is enough here.
var negativeMarker = []byte{0}

// Store is the shared cache seen as bytes with a TTL.
type Store interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, val []byte, ttl time.Duration) error
	Delete(ctx context.Context, keys ...string) error
}

// Loader reads the source of truth. It returns ErrNotFound for absent rows.
type Loader func(ctx context.Context, key string) ([]byte, error)

// Cache wraps a Store with the cache-aside read path.
type Cache struct {
	Store       Store
	TTL         time.Duration // base TTL for positive entries
	Jitter      float64       // 0.1 = TTL is spread over +/-10%
	NegativeTTL time.Duration // TTL for "not found" markers; 0 disables
	LoadTimeout time.Duration // bound on one coalesced load

	group singleflight.Group
	// Loads counts real loader invocations; tests and metrics read it.
	mu    sync.Mutex
	loads int
}

// Get returns the cached value or loads it once per key per process.
func (c *Cache) Get(ctx context.Context, key string, load Loader) ([]byte, error) {
	if b, err := c.Store.Get(ctx, key); err == nil {
		if isNegative(b) {
			return nil, ErrNotFound
		}
		return b, nil
	}
	// ErrMiss, or the cache is down: either way go to the loader, coalesced,
	// so a Redis outage does not multiply database load by the request rate.
	v, err, _ := c.group.Do(key, func() (any, error) {
		// Re-check: another goroutine may have filled the key while we queued.
		if b, err := c.Store.Get(ctx, key); err == nil {
			return b, nil
		}
		lctx := context.WithoutCancel(ctx) // one caller's cancel must not fail the others
		if c.LoadTimeout > 0 {
			var cancel context.CancelFunc
			lctx, cancel = context.WithTimeout(lctx, c.LoadTimeout)
			defer cancel()
		}
		c.mu.Lock()
		c.loads++
		c.mu.Unlock()
		b, err := load(lctx, key)
		switch {
		case errors.Is(err, ErrNotFound):
			if c.NegativeTTL > 0 {
				_ = c.Store.Set(lctx, key, negativeMarker, c.NegativeTTL)
			}
			return negativeMarker, nil
		case err != nil:
			return nil, err // do not cache errors
		}
		_ = c.Store.Set(lctx, key, b, c.jittered(c.TTL))
		return b, nil
	})
	if err != nil {
		return nil, err
	}
	b := v.([]byte)
	if isNegative(b) {
		return nil, ErrNotFound
	}
	return b, nil
}

// Invalidate is called after the database transaction commits. Deleting
// (not setting) is idempotent and cannot install an older value.
func (c *Cache) Invalidate(ctx context.Context, keys ...string) error {
	for _, k := range keys {
		c.group.Forget(k) // a load already in flight must not be joined
	}
	return c.Store.Delete(ctx, keys...)
}

// Loads reports how many times the loader really ran.
func (c *Cache) Loads() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.loads
}

func (c *Cache) jittered(ttl time.Duration) time.Duration {
	if c.Jitter <= 0 {
		return ttl
	}
	f := 1 + c.Jitter*(2*rand.Float64()-1) // uniform in [1-j, 1+j)
	return time.Duration(float64(ttl) * f)
}

func isNegative(b []byte) bool { return len(b) == 1 && b[0] == 0 }

// MemStore is a goroutine-safe in-memory Store with expiry, for tests and
// for an L1 tier in front of Redis.
type MemStore struct {
	mu   sync.Mutex
	m    map[string]memItem
	Now  func() time.Time
	sets int
}

type memItem struct {
	val []byte
	exp time.Time
}

// NewMemStore returns an empty store using the wall clock.
func NewMemStore() *MemStore { return &MemStore{m: map[string]memItem{}, Now: time.Now} }

// Get implements Store.
func (s *MemStore) Get(_ context.Context, key string) ([]byte, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	it, ok := s.m[key]
	if !ok || (!it.exp.IsZero() && !s.Now().Before(it.exp)) {
		delete(s.m, key)
		return nil, ErrMiss
	}
	return it.val, nil
}

// Set implements Store.
func (s *MemStore) Set(_ context.Context, key string, val []byte, ttl time.Duration) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	var exp time.Time
	if ttl > 0 {
		exp = s.Now().Add(ttl)
	}
	s.m[key] = memItem{val: val, exp: exp}
	s.sets++
	return nil
}

// Delete implements Store.
func (s *MemStore) Delete(_ context.Context, keys ...string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, k := range keys {
		delete(s.m, k)
	}
	return nil
}

// TTL returns the remaining lifetime of a key, for tests.
func (s *MemStore) TTL(key string) time.Duration {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.m[key].exp.Sub(s.Now())
}
go
package aside

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"
)

func TestConcurrentMissesLoadOnce(t *testing.T) {
	c := &Cache{Store: NewMemStore(), TTL: time.Minute, Jitter: 0.1}
	release := make(chan struct{})
	load := func(ctx context.Context, key string) ([]byte, error) {
		<-release // hold the load open until every caller has queued
		return []byte("v1"), nil
	}
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			b, err := c.Get(context.Background(), "product:42", load)
			if err != nil || string(b) != "v1" {
				t.Errorf("got %q, %v", b, err)
			}
		}()
	}
	time.Sleep(50 * time.Millisecond)
	close(release)
	wg.Wait()
	if n := c.Loads(); n != 1 {
		t.Fatalf("loader ran %d times, want 1", n)
	}
}

func TestNegativeCaching(t *testing.T) {
	c := &Cache{Store: NewMemStore(), TTL: time.Minute, NegativeTTL: 30 * time.Second}
	load := func(context.Context, string) ([]byte, error) { return nil, ErrNotFound }
	for i := 0; i < 5; i++ {
		if _, err := c.Get(context.Background(), "product:404", load); !errors.Is(err, ErrNotFound) {
			t.Fatalf("want ErrNotFound, got %v", err)
		}
	}
	if n := c.Loads(); n != 1 {
		t.Fatalf("absent row loaded %d times, want 1 (negative cache)", n)
	}
}

func TestErrorsAreNotCached(t *testing.T) {
	c := &Cache{Store: NewMemStore(), TTL: time.Minute}
	boom := errors.New("db timeout")
	load := func(context.Context, string) ([]byte, error) { return nil, boom }
	for i := 0; i < 3; i++ {
		if _, err := c.Get(context.Background(), "k", load); !errors.Is(err, boom) {
			t.Fatalf("want boom, got %v", err)
		}
	}
	if n := c.Loads(); n != 3 {
		t.Fatalf("errors must not be cached: loads=%d want 3", n)
	}
}

func TestJitterSpreadsExpiry(t *testing.T) {
	s := NewMemStore()
	c := &Cache{Store: s, TTL: 100 * time.Second, Jitter: 0.2}
	seen := map[time.Duration]bool{}
	for i := 0; i < 50; i++ {
		key := "k" + string(rune('a'+i))
		_, _ = c.Get(context.Background(), key, func(context.Context, string) ([]byte, error) { return []byte("x"), nil })
		ttl := s.TTL(key).Round(time.Second)
		if ttl < 79*time.Second || ttl > 121*time.Second {
			t.Fatalf("ttl %v outside +/-20%%", ttl)
		}
		seen[ttl] = true
	}
	if len(seen) < 5 {
		t.Fatalf("jitter produced only %d distinct TTLs", len(seen))
	}
}

func TestInvalidateThenReload(t *testing.T) {
	c := &Cache{Store: NewMemStore(), TTL: time.Minute}
	v := "v1"
	load := func(context.Context, string) ([]byte, error) { return []byte(v), nil }
	_, _ = c.Get(context.Background(), "p", load)
	v = "v2" // the database row changed and committed
	if err := c.Invalidate(context.Background(), "p"); err != nil {
		t.Fatal(err)
	}
	b, _ := c.Get(context.Background(), "p", load)
	if string(b) != "v2" {
		t.Fatalf("after invalidate got %q want v2", b)
	}
}

XFetch probabilistic early expiration ​

go
// Package xfetch implements probabilistic early expiration from Vattani,
// Chierichetti and Lowenstein, "Optimal Probabilistic Cache Stampede
// Prevention" (VLDB 2015). Each reader recomputes early with a probability
// that rises as expiry approaches; the gap is drawn from an exponential
// distribution scaled by delta, the time the last recomputation took:
//
//	recompute if now - delta*beta*ln(rand()) >= expiry
//
// ln(rand()) is negative, so the left side is "now plus a random head start".
// beta = 1 is the paper's default; beta > 1 favours earlier recomputation.
package xfetch

import (
	"context"
	"math"
	"math/rand/v2"
	"sync"
	"time"
)

// Entry is what is stored in the cache next to the value: how long the last
// recompute took (Delta) and when the entry expires (Expiry).
type Entry[V any] struct {
	Value  V
	Delta  time.Duration
	Expiry time.Time
}

// ShouldRecompute is the XFetch test. u must be in (0, 1]; pass rand.Float64
// output mapped away from zero. It is a pure function so it can be tested.
func ShouldRecompute(now time.Time, e Entry[any], beta, u float64) bool {
	return shouldRecompute(now, e.Delta, e.Expiry, beta, u)
}

func shouldRecompute(now time.Time, delta time.Duration, expiry time.Time, beta, u float64) bool {
	if u <= 0 {
		u = math.SmallestNonzeroFloat64
	}
	headStart := time.Duration(-float64(delta) * beta * math.Log(u))
	return !now.Add(headStart).Before(expiry)
}

// Cache is a small in-process XFetch cache. A distributed version stores
// Entry in Redis (for example as a hash with value, delta and expiry fields)
// and uses the same test on every read.
type Cache[V any] struct {
	TTL  time.Duration
	Beta float64
	Now  func() time.Time
	Rand func() float64

	mu sync.Mutex
	m  map[string]Entry[V]
}

// New returns a cache with beta = 1, the wall clock and math/rand/v2.
func New[V any](ttl time.Duration) *Cache[V] {
	return &Cache[V]{TTL: ttl, Beta: 1, Now: time.Now, Rand: func() float64 { return 1 - rand.Float64() }, m: map[string]Entry[V]{}}
}

// Fetch returns the cached value, recomputing it when absent or when the
// XFetch test fires. recompute is timed to learn Delta.
func (c *Cache[V]) Fetch(ctx context.Context, key string, recompute func(context.Context) (V, error)) (V, bool, error) {
	c.mu.Lock()
	e, ok := c.m[key]
	c.mu.Unlock()
	now := c.Now()
	if ok && !shouldRecompute(now, e.Delta, e.Expiry, c.Beta, c.Rand()) {
		return e.Value, false, nil
	}
	start := c.Now()
	v, err := recompute(ctx)
	if err != nil {
		if ok && now.Before(e.Expiry) {
			return e.Value, false, nil // early refresh failed: keep serving the fresh value
		}
		var zero V
		return zero, false, err
	}
	end := c.Now()
	c.mu.Lock()
	c.m[key] = Entry[V]{Value: v, Delta: end.Sub(start), Expiry: end.Add(c.TTL)}
	c.mu.Unlock()
	return v, true, nil
}
go
package xfetch

import (
	"context"
	"math"
	"testing"
	"time"
)

func TestNeverEarlyWhenUIsOne(t *testing.T) {
	exp := time.Unix(1000, 0)
	e := Entry[any]{Delta: time.Second, Expiry: exp}
	// ln(1) = 0: no head start, so only at or after expiry.
	if ShouldRecompute(exp.Add(-time.Millisecond), e, 1, 1) {
		t.Fatal("recomputed before expiry with u=1")
	}
	if !ShouldRecompute(exp, e, 1, 1) {
		t.Fatal("did not recompute at expiry")
	}
}

func TestHeadStartScalesWithDeltaAndBeta(t *testing.T) {
	exp := time.Unix(1000, 0)
	u := math.Exp(-3) // -ln(u) = 3, so head start = 3 * delta * beta
	e := Entry[any]{Delta: 2 * time.Second, Expiry: exp}
	if !ShouldRecompute(exp.Add(-5*time.Second), e, 1, u) {
		t.Fatal("6s head start should fire 5s before expiry")
	}
	if ShouldRecompute(exp.Add(-7*time.Second), e, 1, u) {
		t.Fatal("6s head start must not fire 7s before expiry")
	}
	if !ShouldRecompute(exp.Add(-11*time.Second), e, 2, u) {
		t.Fatal("beta=2 doubles the head start to 12s")
	}
}

func TestEarlyRateIsLowFarFromExpiry(t *testing.T) {
	// With delta=1s and 10s left, P(early) = exp(-10) ~ 4.5e-5.
	exp := time.Unix(1000, 0)
	e := Entry[any]{Delta: time.Second, Expiry: exp}
	now := exp.Add(-10 * time.Second)
	fired := 0
	const n = 200000
	for i := 1; i <= n; i++ {
		u := float64(i) / n // deterministic sweep of (0,1]
		if ShouldRecompute(now, e, 1, u) {
			fired++
		}
	}
	if p := float64(fired) / n; p > 1e-4 {
		t.Fatalf("early probability %.6f, want about 4.5e-5", p)
	}
}

func TestFetchRecomputesOnceThenServes(t *testing.T) {
	clock := time.Unix(0, 0)
	c := New[string](time.Minute)
	c.Now = func() time.Time { return clock }
	c.Rand = func() float64 { return 1 } // no early refresh in this test
	calls := 0
	rc := func(context.Context) (string, error) { calls++; return "report", nil }
	for i := 0; i < 10; i++ {
		if _, _, err := c.Fetch(context.Background(), "k", rc); err != nil {
			t.Fatal(err)
		}
	}
	clock = clock.Add(61 * time.Second)
	_, refreshed, _ := c.Fetch(context.Background(), "k", rc)
	if calls != 2 || !refreshed {
		t.Fatalf("calls=%d refreshed=%v, want 2 and true", calls, refreshed)
	}
}

Leases against stale sets and herds ​

go
// Package lease is an in-memory model of the memcache lease mechanism from
// Nishtala et al., "Scaling Memcache at Facebook" (NSDI 2013):
//
//   - on a miss the server hands the client a lease token bound to the key;
//   - the client must present that token to set the value;
//   - a delete for the key invalidates the outstanding token, so a reader that
//     loaded an old row before the delete cannot install it afterwards
//     (the "stale set");
//   - the server issues at most one token per key per interval (10 seconds in
//     the paper); other readers are told to wait and retry (the "thundering
//     herd" on a hot key).
//
// Real systems: memcached meta commands (mg with N/R flags, W/Z/X response
// flags) or a Redis Lua script with the same rules.
package lease

import (
	"errors"
	"sync"
	"time"
)

// ErrWait tells the client another client holds the lease; retry shortly.
var ErrWait = errors.New("lease held by another client: retry")

// ErrStaleLease is returned when a set uses a token that was invalidated.
var ErrStaleLease = errors.New("lease invalidated by a delete")

// Server is one memcached-like node.
type Server struct {
	Interval time.Duration // minimum gap between tokens for one key
	Now      func() time.Time

	mu     sync.Mutex
	vals   map[string][]byte
	leases map[string]lease
	next   uint64
}

type lease struct {
	token  uint64
	issued time.Time
}

// New returns a server issuing at most one token per key per interval.
func New(interval time.Duration) *Server {
	return &Server{Interval: interval, Now: time.Now, vals: map[string][]byte{}, leases: map[string]lease{}}
}

// Get returns (value, 0, nil) on a hit, (nil, token, nil) when the caller
// wins the lease, and (nil, 0, ErrWait) when another caller holds it.
func (s *Server) Get(key string) ([]byte, uint64, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if v, ok := s.vals[key]; ok {
		return v, 0, nil
	}
	now := s.Now()
	if l, ok := s.leases[key]; ok && now.Sub(l.issued) < s.Interval {
		return nil, 0, ErrWait
	}
	s.next++
	s.leases[key] = lease{token: s.next, issued: now}
	return nil, s.next, nil
}

// Set stores the value only if token is the key's current lease.
func (s *Server) Set(key string, val []byte, token uint64) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	l, ok := s.leases[key]
	if !ok || l.token != token {
		return ErrStaleLease
	}
	delete(s.leases, key)
	s.vals[key] = val
	return nil
}

// Delete removes the value and invalidates any outstanding lease.
func (s *Server) Delete(key string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.vals, key)
	delete(s.leases, key)
}
go
package lease

import (
	"errors"
	"testing"
	"time"
)

// The cache-aside race: reader R misses and loads the OLD row, writer W
// commits the NEW row and deletes the key, then R sets the OLD value.
// Without leases the old value stays cached until its TTL. With leases the
// delete invalidated R's token, so R's set is refused.
func TestDeleteInvalidatesLeaseAndBlocksStaleSet(t *testing.T) {
	s := New(10 * time.Second)
	_, tok, err := s.Get("user:7") // 1 R: miss, wins lease
	if err != nil || tok == 0 {
		t.Fatalf("want lease, got %d %v", tok, err)
	}
	old := []byte("name=Ann") // 2 R: SELECT returns the old row
	s.Delete("user:7")        // 3 W: UPDATE ... COMMIT; delete user:7
	if err := s.Set("user:7", old, tok); !errors.Is(err, ErrStaleLease) {
		t.Fatalf("stale set accepted: %v", err) // 4 R: set must fail
	}
	if v, _, _ := s.Get("user:7"); v != nil {
		t.Fatalf("stale value cached: %q", v)
	}
}

func TestOneTokenPerIntervalAbsorbsHerd(t *testing.T) {
	clock := time.Unix(0, 0)
	s := New(10 * time.Second)
	s.Now = func() time.Time { return clock }
	winners, waiters := 0, 0
	var tok uint64
	for i := 0; i < 1000; i++ {
		_, tk, err := s.Get("hot")
		switch {
		case err == nil && tk != 0:
			winners++
			tok = tk
		case errors.Is(err, ErrWait):
			waiters++
		}
	}
	if winners != 1 || waiters != 999 {
		t.Fatalf("winners=%d waiters=%d", winners, waiters)
	}
	if err := s.Set("hot", []byte("v"), tok); err != nil {
		t.Fatal(err)
	}
	if v, _, _ := s.Get("hot"); string(v) != "v" {
		t.Fatalf("waiters should now hit, got %q", v)
	}
}

func TestLeaseExpiresAfterInterval(t *testing.T) {
	clock := time.Unix(0, 0)
	s := New(10 * time.Second)
	s.Now = func() time.Time { return clock }
	_, _, _ = s.Get("k") // winner crashes and never sets
	if _, _, err := s.Get("k"); !errors.Is(err, ErrWait) {
		t.Fatal("second reader should wait")
	}
	clock = clock.Add(11 * time.Second)
	if _, tok, err := s.Get("k"); err != nil || tok == 0 {
		t.Fatal("after the interval a new lease must be issued")
	}
}

An LRU and what it cannot do ​

go
// Package lru is a small generic LRU cache: a map for O(1) lookup and a
// doubly linked list ordered by recency. It is the baseline every other
// policy (LFU, ARC, W-TinyLFU) is compared against. Not safe for concurrent
// use; wrap it in a mutex or shard it.
package lru

import "container/list"

// Cache holds at most Cap entries and evicts the least recently used.
type Cache[K comparable, V any] struct {
	cap     int
	ll      *list.List
	items   map[K]*list.Element
	OnEvict func(K, V)

	Hits, Misses, Evictions int
}

type entry[K comparable, V any] struct {
	key K
	val V
}

// New returns an LRU with the given capacity (> 0).
func New[K comparable, V any](capacity int) *Cache[K, V] {
	if capacity <= 0 {
		panic("lru: capacity must be positive")
	}
	return &Cache[K, V]{cap: capacity, ll: list.New(), items: make(map[K]*list.Element, capacity)}
}

// Get returns the value and marks it most recently used.
func (c *Cache[K, V]) Get(k K) (V, bool) {
	if el, ok := c.items[k]; ok {
		c.ll.MoveToFront(el)
		c.Hits++
		return el.Value.(*entry[K, V]).val, true
	}
	c.Misses++
	var zero V
	return zero, false
}

// Put inserts or updates a value, evicting the LRU entry when full.
func (c *Cache[K, V]) Put(k K, v V) {
	if el, ok := c.items[k]; ok {
		el.Value.(*entry[K, V]).val = v
		c.ll.MoveToFront(el)
		return
	}
	c.items[k] = c.ll.PushFront(&entry[K, V]{k, v})
	if c.ll.Len() > c.cap {
		old := c.ll.Back()
		e := old.Value.(*entry[K, V])
		c.ll.Remove(old)
		delete(c.items, e.key)
		c.Evictions++
		if c.OnEvict != nil {
			c.OnEvict(e.key, e.val)
		}
	}
}

// Delete removes a key.
func (c *Cache[K, V]) Delete(k K) {
	if el, ok := c.items[k]; ok {
		c.ll.Remove(el)
		delete(c.items, k)
	}
}

// Len is the number of entries.
func (c *Cache[K, V]) Len() int { return c.ll.Len() }

// HitRatio is hits / (hits + misses).
func (c *Cache[K, V]) HitRatio() float64 {
	t := c.Hits + c.Misses
	if t == 0 {
		return 0
	}
	return float64(c.Hits) / float64(t)
}
go
package lru

import (
	"math/rand/v2"
	"testing"
)

func TestEvictsLeastRecentlyUsed(t *testing.T) {
	c := New[string, int](2)
	var evicted []string
	c.OnEvict = func(k string, _ int) { evicted = append(evicted, k) }
	c.Put("a", 1)
	c.Put("b", 2)
	c.Get("a")    // a is now most recent
	c.Put("c", 3) // evicts b
	if _, ok := c.Get("b"); ok {
		t.Fatal("b should be evicted")
	}
	if len(evicted) != 1 || evicted[0] != "b" {
		t.Fatalf("evicted %v", evicted)
	}
}

// A one-off scan of cold keys flushes an LRU: this is the weakness that
// LFU, ARC and W-TinyLFU address.
func TestScanPollutesLRU(t *testing.T) {
	c := New[int, int](100)
	for k := 0; k < 100; k++ { // hot set fills the cache
		c.Put(k, k)
	}
	for k := 1000; k < 1100; k++ { // one scan of 100 cold keys
		c.Put(k, k)
	}
	hot := 0
	for k := 0; k < 100; k++ {
		if _, ok := c.Get(k); ok {
			hot++
		}
	}
	if hot != 0 {
		t.Fatalf("expected the scan to evict the whole hot set, %d survived", hot)
	}
}

// Skewed (Zipf-like) traffic: a cache holding 10% of keys gets far more
// than 10% of hits. This is the 80/20 effect the sizing math relies on.
func TestSkewGivesHighHitRatio(t *testing.T) {
	r := rand.New(rand.NewPCG(1, 2))
	z := rand.NewZipf(r, 1.1, 1, 9999)
	c := New[uint64, struct{}](1000)
	for i := 0; i < 200000; i++ {
		k := z.Uint64()
		if _, ok := c.Get(k); !ok {
			c.Put(k, struct{}{})
		}
	}
	if hr := c.HitRatio(); hr < 0.6 {
		t.Fatalf("hit ratio %.2f with 10%% of keys cached, want > 0.6", hr)
	}
	t.Logf("hit ratio with 10%% of keys cached under Zipf(1.1): %.3f", c.HitRatio())
}

Redis Cluster: slots, hash tags, ClusterClient, versioned set ​

go
// Package cluster shows Redis Cluster from a cache client's point of view:
// the key-to-slot function (CRC16 XMODEM mod 16384 with hash tags), a
// go-redis ClusterClient configured for a read-heavy cache, a RESP3 client
// with client-side caching, and a versioned compare-and-set written as a Lua
// script so that an older writer can never overwrite a newer value.
package cluster

import (
	"context"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

// Slots is the fixed number of hash slots in Redis Cluster.
const Slots = 16384

// CRC16 is CRC-16/XMODEM: poly 0x1021, init 0, no reflection, no xorout.
// The cluster specification gives the check value CRC16("123456789") = 0x31C3.
func CRC16(b []byte) uint16 {
	var crc uint16
	for _, c := range b {
		crc ^= uint16(c) << 8
		for i := 0; i < 8; i++ {
			if crc&0x8000 != 0 {
				crc = crc<<1 ^ 0x1021
			} else {
				crc <<= 1
			}
		}
	}
	return crc
}

// HashTag returns the part of the key that is hashed: the substring between
// the first '{' and the first '}' after it, if that substring is non-empty;
// otherwise the whole key.
func HashTag(key string) string {
	s := strings.IndexByte(key, '{')
	if s < 0 {
		return key
	}
	e := strings.IndexByte(key[s+1:], '}')
	if e <= 0 { // no closing brace, or "{}" with nothing inside
		return key
	}
	return key[s+1 : s+1+e]
}

// KeySlot is what CLUSTER KEYSLOT returns.
func KeySlot(key string) int {
	return int(CRC16([]byte(HashTag(key))) & (Slots - 1))
}

// NewCacheCluster returns a ClusterClient tuned for a cache tier:
// reads may go to replicas (READONLY is sent for you when ReadOnly is set),
// routed to the lowest-latency node; timeouts are short because a slow cache
// is worse than a miss.
func NewCacheCluster(addrs []string, password string) *redis.ClusterClient {
	return redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:          addrs, // seed nodes; the slot map is discovered with CLUSTER SLOTS/SHARDS
		Password:       password,
		ReadOnly:       true, // allow reads from replicas (possibly stale)
		RouteByLatency: true, // pick master or replica with the lowest latency
		MaxRedirects:   3,    // follow MOVED/ASK at most 3 times per command
		DialTimeout:    200 * time.Millisecond,
		ReadTimeout:    50 * time.Millisecond,
		WriteTimeout:   50 * time.Millisecond,
		PoolSize:       64,
	})
}

// NewTrackedClient enables RESP3 client-side caching on a standalone or
// Sentinel-managed node: the client keeps hot replies in process memory and
// the server pushes invalidations (CLIENT TRACKING) when a tracked key
// changes. go-redis v9.24 adds the same option to ClusterOptions (one cache per
// node); v9.22, pinned here to keep the module on go 1.24, has it on Options.
func NewTrackedClient(addr string) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:                  addr,
		Protocol:              3,
		ClientSideCacheConfig: &redis.ClientSideCacheConfig{MaxEntries: 10_000},
	})
}

// setIfNewer stores value only when version is greater than the stored one.
// KEYS[1] is a hash {v = version, d = data}. Returns 1 if written, 0 if the
// cache already holds the same or a newer version.
var setIfNewer = redis.NewScript(`
local cur = tonumber(redis.call('HGET', KEYS[1], 'v') or '-1')
if tonumber(ARGV[1]) <= cur then return 0 end
redis.call('HSET', KEYS[1], 'v', ARGV[1], 'd', ARGV[2])
redis.call('PEXPIRE', KEYS[1], ARGV[3])
return 1
`)

// SetIfNewer is the versioned-value defence against the double-write race:
// whichever order two writers arrive in, the higher database version wins.
func SetIfNewer(ctx context.Context, c redis.Scripter, key string, version int64, data []byte, ttl time.Duration) (bool, error) {
	n, err := setIfNewer.Run(ctx, c, []string{key}, version, data, ttl.Milliseconds()).Int()
	return n == 1, err
}

// ProductKeys keeps every key of one product in one slot with a hash tag,
// so MGET/DEL/Lua over them is legal in Redis Cluster (no CROSSSLOT error).
func ProductKeys(tenant string, id string) (row, price, stock string) {
	tag := "{" + tenant + ":product:" + id + "}"
	return tag + ":row", tag + ":price", tag + ":stock"
}
go
package cluster

import "testing"

func TestCRC16CheckValue(t *testing.T) {
	if got := CRC16([]byte("123456789")); got != 0x31C3 {
		t.Fatalf("CRC16 = %#x, want 0x31C3 (cluster spec)", got)
	}
}

func TestKeySlotMatchesRedisDocs(t *testing.T) {
	cases := map[string]int{
		"somekey":       11058, // CLUSTER KEYSLOT somekey
		"foo{hash_tag}": 2515,  // CLUSTER KEYSLOT foo{hash_tag}
		"bar{hash_tag}": 2515,
	}
	for k, want := range cases {
		if got := KeySlot(k); got != want {
			t.Errorf("KeySlot(%q) = %d, want %d", k, got, want)
		}
	}
}

func TestHashTagRulesFromSpec(t *testing.T) {
	cases := map[string]string{
		"{user1000}.following": "user1000",
		"{user1000}.followers": "user1000",
		"foo{}{bar}":           "foo{}{bar}", // empty tag: whole key
		"foo{{bar}}zap":        "{bar",       // first { to first } after it
		"foo{bar}{zap}":        "bar",
		"no-tag":               "no-tag",
	}
	for k, want := range cases {
		if got := HashTag(k); got != want {
			t.Errorf("HashTag(%q) = %q, want %q", k, got, want)
		}
	}
}

func TestProductKeysShareASlot(t *testing.T) {
	a, b, c := ProductKeys("t42", "1001")
	if KeySlot(a) != KeySlot(b) || KeySlot(b) != KeySlot(c) {
		t.Fatalf("slots differ: %d %d %d", KeySlot(a), KeySlot(b), KeySlot(c))
	}
}

func TestClientsConstructWithoutServer(t *testing.T) {
	c := NewCacheCluster([]string{"127.0.0.1:7000"}, "")
	defer c.Close()
	tc := NewTrackedClient("127.0.0.1:6379")
	defer tc.Close()
}

The Go angle ​

  • golang.org/x/sync/singleflight "provides a duplicate function call suppression mechanism". Group.Do(key, fn) returns (v, err, shared); DoChan returns a channel so a caller can stop waiting on its own context; Forget(key) makes the next call start a new execution, which aside.Invalidate uses so a load that began before a write is not joined by readers after it.
  • One caller's cancellation must not fail the shared load: aside runs the loader under context.WithoutCancel(ctx) plus its own LoadTimeout. Without that, the first caller's timeout cancels the database query for everybody waiting on it.
  • Singleflight is per process. Two hundred pods still make two hundred loads after an expiry; add a lock, a lease, XFetch or stale serving for cluster-wide protection.
  • go-redis v9: redis.NewClient, NewFailoverClient (Sentinel), NewClusterClient (Cluster), NewRing (client-side sharding), NewUniversalClient (picks one). ClusterOptions.ReadOnly sends READONLY to replicas, RouteByLatency/RouteRandomly choose among master and replicas, MaxRedirects bounds MOVED/ASK following. redis.NewScript runs EVALSHA and falls back to EVAL.
  • Client-side caching in go-redis: Protocol: 3 with ClientSideCacheConfig{MaxEntries: ...}. This module pins go-redis v9.22.0 (go 1.24), where the option is on Options; v9.24 also accepts it on ClusterOptions but requires go 1.26.
  • In-process caches: ristretto v2 (github.com/dgraph-io/ristretto/v2, generics, TinyLFU admission, cost-based eviction), otter v2 (github.com/maypok86/otter/v2, adaptive W-TinyLFU, loaders, refresh), or the standard library plus container/list for a small LRU like lru here. Benchmarks in their READMEs are vendor claims; measure your key distribution.
  • math/rand/v2 gives Float64 and NewZipf for skewed test traffic; the lru test shows a 10% cache reaching a 0.78 hit ratio under Zipf(1.1).
  • Serialization: encoding/json is the neutral default when PHP and Go share keys; encoding/gob is Go-only. Put a schema version in the key.

Laravel ​

Before ​

php
<?php

namespace App\Services\Before;

use App\Models\Product;
use Illuminate\Support\Facades\Cache;

/**
 * The naive version: works in development, fails under load.
 * - get/put by hand: every concurrent miss runs the query (stampede);
 * - one fixed TTL for every key (synchronized expiry);
 * - update writes the database, then PUTS the new value into the cache:
 *   two concurrent updates can leave the older one cached (double-write race);
 * - the key has no tenant or version, so a schema change serves old shapes.
 */
class ProductCatalogBefore
{
    public function find(int $id): ?array
    {
        $cached = Cache::get("product:{$id}");
        if ($cached !== null) {
            return $cached;
        }

        $product = Product::query()->find($id);
        if ($product === null) {
            return null; // not cached: every lookup of a bad id hits the database
        }

        Cache::put("product:{$id}", $product->toArray(), 600);

        return $product->toArray();
    }

    public function updatePrice(int $id, int $priceCents): void
    {
        $product = Product::query()->findOrFail($id);
        $product->update(['price_cents' => $priceCents]);

        // Set-on-write: races with other writers and with concurrent readers.
        Cache::put("product:{$id}", $product->toArray(), 600);
    }
}

After ​

php
<?php

namespace App\Models;

use App\Observers\ProductCacheObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Model;

#[ObservedBy([ProductCacheObserver::class])]
class Product extends Model
{
    protected $fillable = ['tenant_id', 'category_id', 'name', 'price_cents', 'stock'];

    protected function casts(): array
    {
        return ['price_cents' => 'integer', 'stock' => 'integer', 'version' => 'integer'];
    }

    // Every update bumps a monotonically increasing version, used by the
    // cache to refuse writes of older data (versioned values).
    protected static function booted(): void
    {
        static::updating(function (Product $product): void {
            $product->version = ($product->getOriginal('version') ?? 0) + 1;
        });
    }
}
php
<?php

namespace App\Services;

use App\Models\Product;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;

/**
 * Cache-aside done properly with Laravel 13's cache API.
 */
class ProductCatalog
{
    private const NEGATIVE = '__none__';

    /** Keys carry tenant and a schema version so tenants and deploys never collide. */
    public function key(int $tenantId, int $id): string
    {
        return "t{$tenantId}:product:v3:{$id}";
    }

    /**
     * Hot detail page: stale-while-revalidate. Fresh for 60 s; for the next
     * 240 s the stale value is served and a deferred refresh runs after the
     * response is sent. Only after 300 s does a request wait for the database.
     */
    public function show(int $tenantId, int $id): ?array
    {
        $value = Cache::flexible($this->key($tenantId, $id), [60, 300], function () use ($id) {
            return Product::query()->find($id)?->toArray() ?? self::NEGATIVE;
        });

        return $value === self::NEGATIVE ? null : $value;
    }

    /**
     * Expensive aggregate: remember with a jittered TTL and a lock so that
     * only one worker recomputes after expiry (stampede / dogpile control).
     */
    public function categoryStats(int $tenantId, int $categoryId): array
    {
        $key = "t{$tenantId}:category-stats:{$categoryId}";
        $ttl = now()->plus(seconds: 600 + random_int(-60, 60)); // +/-10% jitter

        $cached = Cache::get($key);
        if ($cached !== null) {
            return $cached;
        }

        try {
            // Wait up to 3 s for the worker that holds the lock, then re-read.
            return Cache::lock("lock:{$key}", 30)->block(3, function () use ($key, $ttl, $categoryId) {
                return Cache::remember($key, $ttl, fn () => $this->computeStats($categoryId));
            });
        } catch (LockTimeoutException) {
            // The recompute is taking too long: degrade instead of piling on.
            return Cache::get($key) ?? ['products' => null, 'degraded' => true];
        }
    }

    /**
     * Tag-based invalidation (redis and memcached stores only): a category
     * page is tagged with the category, so one flush clears every variant.
     */
    public function categoryPage(int $tenantId, int $categoryId, int $page): array
    {
        return Cache::tags(["t{$tenantId}", "category:{$categoryId}"])
            ->remember("page:{$page}", 300, fn () => Product::query()
                ->where('category_id', $categoryId)
                ->orderBy('id')
                ->forPage($page, 50)
                ->get()
                ->toArray());
    }

    /**
     * Generational keys: bump one counter and every key built from the old
     * generation becomes unreachable; the old entries age out by TTL or LRU.
     * Works on every store, including those without tags.
     */
    public function searchResults(int $tenantId, string $query): array
    {
        $gen = Cache::get("t{$tenantId}:search-gen", 1);
        $key = "t{$tenantId}:search:g{$gen}:".hash('xxh128', $query);

        return Cache::remember($key, 120, fn () => Product::query()
            ->where('name', 'like', '%'.$query.'%')
            ->limit(20)
            ->get()
            ->toArray());
    }

    public function invalidateSearch(int $tenantId): void
    {
        Cache::add("t{$tenantId}:search-gen", 1); // atomic: only creates if missing
        Cache::increment("t{$tenantId}:search-gen");
    }

    /**
     * Request-scoped memo in front of the shared store: the same key read
     * ten times while rendering one page costs one Redis round trip.
     */
    public function featureFlags(int $tenantId): array
    {
        $key = "t{$tenantId}:flags";
        $flags = Cache::memo()->get($key); // first call: Redis; later calls in this request: memory
        if ($flags === null) {
            $flags = ['new_checkout' => true]; // load from the flags table in real code
            Cache::memo()->put($key, $flags, 60); // writes through and forgets the memoized miss
        }

        return $flags;
    }

    /** One-time work per key, cluster-wide: Cache::add is an atomic SET NX. */
    public function sendLowStockAlertOnce(int $productId): bool
    {
        return Cache::add("alert:low-stock:{$productId}", true, now()->plus(hours: 6));
    }

    private function computeStats(int $categoryId): array
    {
        return [
            'products' => Product::query()->where('category_id', $categoryId)->count(),
            'avg_price' => (int) Product::query()->where('category_id', $categoryId)->avg('price_cents'),
            'degraded' => false,
        ];
    }
}
php
<?php

namespace App\Observers;

use App\Models\Product;
use App\Services\ProductCatalog;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
use Illuminate\Support\Facades\Cache;

/**
 * Invalidate after COMMIT, by delete, never by set. Running inside the
 * transaction would let a concurrent reader re-cache the old row before the
 * commit is visible.
 */
class ProductCacheObserver implements ShouldHandleEventsAfterCommit
{
    public function __construct(private ProductCatalog $catalog) {}

    public function saved(Product $product): void
    {
        $this->invalidate($product);
    }

    public function deleted(Product $product): void
    {
        $this->invalidate($product);
    }

    private function invalidate(Product $product): void
    {
        Cache::forget($this->catalog->key($product->tenant_id, $product->id));
        Cache::tags(["category:{$product->category_id}"])->flush();
        $this->catalog->invalidateSearch($product->tenant_id);
    }
}
php
<?php

// config/cache.php (excerpt): one store per job.
return [
    'default' => env('CACHE_STORE', 'failover'),

    'stores' => [
        // Shared cache on the Redis Cluster defined in config/database.php.
        'redis' => [
            'driver' => 'redis',
            'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
            'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
        ],

        'memcached' => [
            'driver' => 'memcached',
            'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
            'servers' => [
                ['host' => env('MEMCACHED_HOST', '127.0.0.1'), 'port' => env('MEMCACHED_PORT', 11211), 'weight' => 100],
            ],
        ],

        // Per-process, per-request: tests, and short-lived memo of hot values.
        'array' => ['driver' => 'array', 'serialize' => false],

        // If Redis is unreachable, fall back to the database store, then to
        // the in-process array store; Laravel fires CacheFailedOver.
        'failover' => [
            'driver' => 'failover',
            'stores' => ['redis', 'database', 'array'],
        ],

        'database' => [
            'driver' => 'database',
            'connection' => env('DB_CACHE_CONNECTION'),
            'table' => env('DB_CACHE_TABLE', 'cache'),
            'lock_table' => env('DB_CACHE_LOCK_TABLE', 'cache_locks'),
        ],
    ],

    // Every key is namespaced per application and environment.
    'prefix' => env('CACHE_PREFIX', 'shop-prod-cache-'),
];
php
<?php

use Illuminate\Support\Str;

// config/database.php (excerpt): the 'redis' key, with a Redis Cluster for
// the cache store and a separate single primary for queues and locks.
return [
    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'), // native Redis Cluster, handles failover
            'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
            'serializer' => Redis::SERIALIZER_IGBINARY, // phpredis built with igbinary: smaller than serialize()
            'compression' => Redis::COMPRESSION_LZ4,      // phpredis: cheap CPU, big win on JSON-like values
        ],

        'clusters' => [
            'cache' => [
                ['host' => env('REDIS_CACHE_HOST_1', '192.0.2.11'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
                ['host' => env('REDIS_CACHE_HOST_2', '192.0.2.12'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
                ['host' => env('REDIS_CACHE_HOST_3', '192.0.2.13'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
            ],
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],
    ],
];
php
<?php

namespace Tests\Feature;

use App\Models\Product;
use App\Services\ProductCatalog;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ProductCatalogTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        config(['cache.default' => 'array']); // array store supports tags and locks
    }

    public function test_second_read_is_served_from_cache(): void
    {
        $p = Product::query()->create(['tenant_id' => 1, 'category_id' => 7, 'name' => 'Lamp', 'price_cents' => 1999, 'stock' => 3]);
        $catalog = app(ProductCatalog::class);

        DB::enableQueryLog();
        $catalog->show(1, $p->id);
        $catalog->show(1, $p->id);

        $this->assertCount(1, DB::getQueryLog(), 'one SELECT for two reads');
    }

    public function test_missing_rows_are_negatively_cached(): void
    {
        $catalog = app(ProductCatalog::class);
        DB::enableQueryLog();

        $this->assertNull($catalog->show(1, 999));
        $this->assertNull($catalog->show(1, 999));

        $this->assertCount(1, DB::getQueryLog());
    }

    public function test_update_invalidates_after_commit(): void
    {
        $p = Product::query()->create(['tenant_id' => 1, 'category_id' => 7, 'name' => 'Lamp', 'price_cents' => 1999, 'stock' => 3]);
        $catalog = app(ProductCatalog::class);
        $catalog->show(1, $p->id);

        DB::transaction(fn () => $p->update(['price_cents' => 2499]));

        $this->assertSame(2499, $catalog->show(1, $p->id)['price_cents']);
    }

    public function test_add_is_atomic_once(): void
    {
        $catalog = app(ProductCatalog::class);

        $this->assertTrue($catalog->sendLowStockAlertOnce(5));
        $this->assertFalse($catalog->sendLowStockAlertOnce(5));
    }

    public function test_generation_bump_hides_old_search_results(): void
    {
        $catalog = app(ProductCatalog::class);
        $catalog->searchResults(1, 'lamp');
        $before = Cache::get('t1:search-gen', 1);

        $catalog->invalidateSearch(1);

        $this->assertSame($before + 1, Cache::get('t1:search-gen'));
    }
}

The Laravel angle ​

  • Stores: Laravel 13 "supports popular caching backends like Memcached, Redis, DynamoDB, relational databases, and filesystem disks out of the box", plus array and null for tests, a failover driver and a memo decorator. The default store is database; set CACHE_STORE=redis (or failover) in production.
  • Cache::remember($key, $ttl, $closure) is cache-aside; rememberForever has no TTL (on memcached such items "may be removed when the cache reaches its size limit"). TTLs accept seconds or a date (now()->plus(minutes: 10), as in the 13.x docs).
  • Cache::flexible($key, [$fresh, $stale], $closure) implements stale-while-revalidate: within the first value the cached value is returned; between the two values "the stale value is served to the user, and a deferred function is registered to refresh the cached value after the response is sent"; after the second value the request recomputes.
  • Cache::add($key, $value, $ttl) "will only add the item to the cache if it does not already exist"; the documentation states it "is an atomic operation". Use it for once-only work and as the base of hand-written leases.
  • Atomic locks: Cache::lock($name, $seconds) with get(), block($seconds, $closure) (throws Illuminate\Contracts\Cache\LockTimeoutException), owner() and Cache::restoreLock($name, $owner) across processes, refresh(), forceRelease(); supported on memcached, redis, dynamodb, database, file and array, with all servers talking to the same central cache. Cache::withoutOverlapping and Cache::funnel limit concurrency.
  • Tags: Cache::tags([...])->put/remember/get and ->flush(); "not supported when using the file, dynamodb, database, or storage cache drivers". Items must be read with the same ordered tag list they were written with.
  • Cache::memo() memoizes resolved values for one request or job; mutating calls through it forget the memoized value and delegate to the underlying store. It removes repeated Redis round trips within a request, not cross-request staleness.
  • Cache::touch($key, $ttl) extends a TTL; Cache::increment/decrement are atomic on Redis and memcached and power generational keys.
  • Redis cluster: define clusters in config/database.php; options.cluster = redis uses native Redis Cluster, which Laravel calls "a great default option, as it gracefully handles failover". Removing it with Predis gives client-side sharding. phpredis supports serializer (SERIALIZER_PHP, JSON, IGBINARY, MSGPACK) and compression (LZF, ZSTD, LZ4) options.
  • Key prefixes: every Redis key gets the prefix (from REDIS_PREFIX, default from the app name). Staging and production on one server with the same prefix "read each other's data"; give each environment its own prefix or database.
  • Invalidate after commit: observers implementing Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit run their handlers only after the transaction commits (immediately if none is open). Queued listeners can implement ShouldQueueAfterCommit. This is the Laravel form of "write then delete".
  • Octane: the application stays in memory between requests, so static properties and singletons act as an in-process cache that survives requests; reset or scope them, and prefer Cache::memo for per-request memoization.

Solving the classic problems ​

The page shows the old price after an update ​

CauseFixAdvantageCost or limit
Write path sets the cache, racing readersDelete after commit instead of setIdempotent, simpleOne miss after each write
Delete runs inside the transactionObserver with ShouldHandleEventsAfterCommit / delete after Commit()No re-caching of the old rowNone
Rare reader-writer race remainsLease or versioned SetIfNewerCloses the raceLua or meta-protocol support
Another writer (script, service) bypasses the codeCDC-driven invalidationSees every committed changePipeline to operate
CDN or browser still holds itTag purge (Cache-Tag, Surrogate-Key) and short s-maxageEdge stays freshPurge API quotas

The database falls over when a hot key expires ​

CauseFixAdvantageCost or limit
Every miss recomputessingleflight per processNo coordinationPer process only
Many pods recomputeLock (Cache::lock, SET NX PX) or leaseOne recompute cluster-wideWaiters need a timeout and a fallback
Users wait for recomputeCache::flexible, Varnish grace, NGINX use_stale updatingNo user waitsBounded staleness
Keys expire togetherJittered TTL, staggered warm-upFlattens expiryNone
Deploy changes every keyWarm new keys first, shift traffic graduallyNo cold-cache outageRelease process work

One shard is at 100% CPU ​

CauseFixAdvantageCost or limit
Read-hot keyL1 cache with sub-second TTL, or client-side cachingRemoves most readsStaleness up to L1 TTL or invalidation delay
Same, extremeKey splitting into N copiesSpreads over N slotsN writes per update
Replicas idleREADONLY reads (ReadOnly, RouteByLatency)Uses existing capacityReplica lag
Tenant tag puts one big tenant in one slotTag by tenant + entity, not tenant aloneSpreads loadFewer multi-key operations

Redis is full and writes fail ​

CauseFixAdvantageCost or limit
Default noevictionmaxmemory-policy allkeys-lfu or allkeys-lru for cache instancesCache evicts instead of failingMust not hold data you cannot lose
Keys without TTL under volatile-*TTL on every cache key, or allkeys-*EvictableNone
Queues and locks share the cache instanceSeparate instance with noeviction for queues/locksNo eviction of jobsOne more instance
Big keys--bigkeys, split, compress, UNLINKMemory backCode changes

Permanent misses for ids that do not exist ​

CauseFixAdvantageCost or limit
Nothing cached for "not found"Negative caching with a short TTLAbsorbs repeatsNew rows hidden until marker deleted
Random id scanningBloom filter of valid ids, rate limitingStops before cacheFalse positives, rebuilds

Users do not see their own change (replica lag plus cache) ​

CauseFixAdvantageCost or limit
Refill read from a lagging replicaRefill from the primary after a write, or wait for replica LSNCorrect refillPrimary load
Cross-region cacheFacebook remote marker: mark key, route misses to the primary regionCross-region read-your-writesExtra latency on miss
Session-level guaranteeSticky "read primary for N seconds after my write"SimpleCoarse

Choosing ​

SituationChooseExtra techniqueReason
General read-heavy entity readsCache-aside on Redis or memcachedDelete after commit, jittered TTL, singleflightSimple, degrades to slow not wrong
Read immediately after write (profile, cart)Write-through with versioned setTTL as a safety netRead-your-writes without a miss
Counters, likes, analyticsWrite-behind through a durable bufferSharded counters, idempotent flushWrite throughput; loss tolerable
Hot, expensive aggregateStale-while-revalidate (Cache::flexible, XFetch)Lock for the recomputeNobody waits; one recompute
Very hot small keys (flags, config)L1 in-process or client-side cachingShort TTL or CLIENT TRACKINGRemoves the network hop
Many writers, many servicesCDC-driven invalidationVersioned valuesEvery committed change seen
Public pages and APIs, identical for allCDN / Varnish / NGINX with tagsstale-if-error, request coalescingOffloads origin entirely
Per-user or permissioned dataApplication cache keyed by tenant and userCache-Control: private at the edgeNo cross-user leakage
Skewed catalogue with scansW-TinyLFU in process, allkeys-lfu in RedisSeparate scan workloadsHot set survives scans
More data than one RedisRedis ClusterHash tags per entitySharding with failover
HA for one-node data (locks, sessions)Primary + replicas + Sentinelnoeviction, persistenceFailover without sharding

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith on two servers with one PostgreSQL. The simplest correct design: Redis as the cache store, Cache::remember for product and category reads with jittered TTLs, Cache::flexible for the homepage modules, and a ProductCacheObserver that deletes after commit. Sessions and queues live on separate Redis databases or a separate instance with noeviction, so cache eviction never deletes jobs. The first thing to measure is whether PostgreSQL's shared_buffers already holds the hot data; if the database is idle, the cache is for latency, not capacity, and a cold cache is not an outage.

Modular monolith: boundaries without the network ​

Catalog, Pricing and Inventory are modules in one codebase. Each module owns its key namespace (catalog:, pricing:) and is the only code that writes or deletes those keys; other modules call the owning module's API, which may be cached internally. Cross-module invalidation goes through in-process domain events dispatched after commit. Generational keys per module (pricing:g{n}:...) make "invalidate everything pricing" one Cache::increment. Tags help when a page combines several modules, but each module still flushes only its own tags.

Microservices: every arrow is a decision ​

 1  browser   -> CDN               GET /p/42  (s-maxage=60, Cache-Tag: product-42 category-7)
 2  CDN       -> gateway -> product-svc   MISS
 3  product-svc  -> otter L1 MISS -> Redis Cluster GET {t1:product:42}:row MISS
 4  product-svc  -> PostgreSQL (product DB)   -> row v9
 5  product-svc  -> Redis SET via SetIfNewer(v9), L1 put (1 s), respond
 6  pricing-svc  UPDATE price; COMMIT ; outbox row "PriceChanged{42, v12}"
 7  outbox relay -> Kafka price.changes (key 42)
 8  product-svc consumer: DEL {t1:product:42}:price ; CDN purge tag product-42 ; L1 broadcast delete
 9  next request: CDN MISS -> product-svc composes from Redis and pricing-svc (cached 5 s) -> v12 shown

What survives across service boundaries is only what travels in messages: each service owns its cache and invalidates it from events of the owning service (outbox or CDC), with versions so out-of-order events cannot install old data. Never let one service read another service's cache keys directly: it couples them to each other's key format and TTLs. Caching another service's API responses is fine with a short TTL and a clear staleness contract.

Distributed data: replicas, caches, regions ​

With read replicas, a cache refill can read a lagging replica and install old data for a whole TTL; refill from the primary after a write, or include the version and refuse older ones. With multiple regions, each region has its own cache; Facebook keeps a master region for writes, invalidates other regions from the replication stream and uses remote markers so a user who just wrote is routed to the master region until the replica catches up. Redis replication itself is asynchronous: a cache that fails over may forget recent deletes, so TTLs remain the last line of defence. See Consistency Models for the formal names and Replication Topologies for the replica side.

Scaling path: 1x, 10x, 100x ​

  • 1x (hundreds of requests per second): one Redis, cache-aside, TTLs, delete after commit. Measure hit ratio from day one.
  • 10x (thousands per second): Sentinel or a managed primary with a replica for HA; singleflight and Cache::flexible on hot keys; CDN for public assets and pages; negative caching; alerts on hit ratio and evictions; warm-up in the deploy process.
  • 100x (tens to hundreds of thousands per second): Redis Cluster with hash-tag key design; L1 in-process or client-side caching for hot keys; leases or versioned sets on contended keys; CDC-driven invalidation across services; separate cache pools for keys with different churn (Facebook sizes "high-churn pools appropriate to their cache miss cost"); a Gutter-like fallback so a failed node does not send its whole slice to the database; regional caches with explicit read-your-writes rules.

Lab: stampedes, races and slots, with tests ​

The Go experiments run on one machine with no services (run, outputs below are real). The Redis experiments need a Redis 7+ server and are expected, not run.

  1. Stampede vs coalescing (run). From docs/snippets/system-design/caching/go:
$ go run ./cmd/stampede
concurrent misses:           1000
database queries, naive:     1000
database queries, coalesced: 1
go
// Command stampede simulates a hot key expiring under load, in one process,
// and counts how many requests reach the "database" with and without
// request coalescing. Run: go run ./cmd/stampede
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"golang.org/x/sync/singleflight"
)

func main() {
	const clients = 1000
	const loadTime = 20 * time.Millisecond

	var naive atomic.Int64
	run(clients, func() {
		naive.Add(1) // every miss queries the database
		time.Sleep(loadTime)
	})

	var coalesced atomic.Int64
	var g singleflight.Group
	run(clients, func() {
		_, _, _ = g.Do("product:42", func() (any, error) {
			coalesced.Add(1)
			time.Sleep(loadTime)
			return "row", nil
		})
	})

	fmt.Printf("concurrent misses:           %d\n", clients)
	fmt.Printf("database queries, naive:     %d\n", naive.Load())
	fmt.Printf("database queries, coalesced: %d\n", coalesced.Load())
}

// run starts n goroutines that all call f at the same instant.
func run(n int, f func()) {
	var start, done sync.WaitGroup
	start.Add(1)
	for i := 0; i < n; i++ {
		done.Add(1)
		go func() {
			defer done.Done()
			start.Wait()
			f()
		}()
	}
	start.Done()
	done.Wait()
}
  1. The stale-set race and leases (run). go test -run StaleSet -v ./lease replays the five-step race from Consistency problems; the set with the invalidated token returns ErrStaleLease. TestOneTokenPerIntervalAbsorbsHerd shows 1,000 readers producing one winner and 999 waiters.

  2. Hash slots (run, then compare with a server). go test -v ./cluster checks CRC16 0x31C3 and the documented slots. With a Redis server (expected, not run):

$ redis-cli CLUSTER KEYSLOT somekey
(integer) 11058
$ redis-cli CLUSTER KEYSLOT "foo{hash_tag}"
(integer) 2515
$ redis-cli -c MSET "{user:7}:name" Ann "{user:7}:city" Oslo
OK
$ redis-cli -c MSET user:7:name Ann user:8:name Bob
(error) CROSSSLOT Keys in request don't hash to the same slot
  1. Eviction policy (expected, not run). On a test Redis:
$ redis-cli CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "noeviction"
$ redis-cli CONFIG SET maxmemory 50mb
$ redis-benchmark -t set -n 2000000 -r 10000000 -d 100 -q   # fills memory with random keys
$ redis-cli SET k v
(error) OOM command not allowed when used memory > 'maxmemory'.
$ redis-cli CONFIG SET maxmemory-policy allkeys-lfu
$ redis-cli SET k v
OK
$ redis-cli INFO stats | grep -E 'evicted_keys|keyspace_(hits|misses)'
evicted_keys:153201
keyspace_hits:0
keyspace_misses:0
  1. Client-side caching invalidation (expected, not run). Two terminals:
 1  T1  redis-cli -3                      # RESP3
 2  T1  CLIENT TRACKING on
 3  T1  GET flags:t1                       -> "on"
 4  T2  redis-cli SET flags:t1 off
 5  T1  -> push: invalidate ["flags:t1"]   # T1 must drop its local copy
  1. Laravel (expected, not run). php artisan test --filter=ProductCatalogTest passes five tests: one SELECT for two reads, negative caching, invalidation after commit, atomic Cache::add, and the generation bump.

Common misconceptions ​

BeliefReality
Update the cache on every write to keep it freshSet-on-write races; delete after commit and let readers refill
Delete the key before writing the databaseDelete then write opens a wide stale-set window; write then delete
A high hit ratio means the database is safeA stampede on one hot key can still take it down
Redis evicts LRU by defaultDefault is noeviction; caches must set a policy
Redis LRU is exactIt samples keys (maxmemory-samples); approximated LRU and LFU
Sentinel shards dataSentinel fails over one primary; Cluster shards
Redis Cluster supports every multi-key commandOnly when all keys share a slot (hash tags)
Write-behind with Redis persistence is durableAOF/RDB and async replication can lose recent writes
A lock solves stampedes completelyWaiters still need a timeout and something to serve; stale serving is gentler
TTL is only a fallbackTTL is the only guarantee that bounds staleness when invalidations are lost
Cache serialized ORM modelsDeploys break deserialization; cache arrays with a versioned key
Caches do not need securityThey hold personal data and sessions; tenant prefixes, ACLs, TLS, private
In-process caches cannot be consistentWith CLIENT TRACKING the local copy is invalidated on change
Adding shards fixes a hot keyOne key lives in one slot; use L1, splitting or replicas

Cheat sheet ​

TopicRemember
Default patternCache-aside: get, on miss load and set with jittered TTL, delete after commit
Write pathWrite then delete, never set; delete after commit
Stale-set raceClose with leases or versioned compare-and-set
Stampedesingleflight per process, lock or lease per cluster, XFetch or SWR for hot keys
XFetchRecompute if now - delta * beta * ln(rand) >= expiry, beta = 1
Negative cachingShort TTL, delete on create, never cache errors
InvalidationTTL always; plus delete, tags, generations or CDC
EvictionLRU default, LFU or W-TinyLFU for skew; Redis default noeviction
Redis cache configmaxmemory with headroom, allkeys-lfu, no persistence, lazyfree on
Redis Cluster16384 slots, CRC16, hash tags for multi-key, MOVED vs ASK, READONLY for replicas
Hot keyL1 or client-side caching, key splitting, replicas
Big keySplit, compress, UNLINK, --bigkeys
SizingWorking set x value size x overhead; DB load = (1 - h) x traffic
Laravelremember, flexible, lock, add, tags, memo, after-commit observers
SecurityTenant and version in every key, no secrets, Cache-Control: private for personal data

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does Facebook delete cache entries on write instead of updating them? Must-know ​

Answer

Answer: Deletes are idempotent and cannot install an older value: if two deletes or a delete and a refill reorder, the worst case is an extra miss. Two sets that reorder leave whichever arrived last, which may be the older value, until the TTL. The paper says they "choose to delete cached data instead of updating it because deletes are idempotent".

2 — Draw the race in which cache-aside with write-then-delete still caches stale data. What closes it? Important ​

Answer

Answer: Reader misses, reads the old row, then stalls; the writer commits the new row and deletes the key; the reader sets the old value. A lease (the delete invalidates the reader's token, so the set is refused) or a versioned compare-and-set (the reader's version is older than the one written or recorded by the writer) closes it.

3 — Why is delete-then-write worse than write-then-delete? Important ​

Answer

Answer: Deleting first lets any reader that arrives before the commit miss, read the old row from the database and cache it, and nothing deletes it afterwards. The window is the whole transaction. With write-then-delete the reader must load before the commit and set after the delete, which is much rarer.

4 — A hot key at 2,000 requests per second takes 300 ms to recompute. Roughly how many requests miss during one recompute without protection, and what are three defences? Must-know ​

Answer

Answer: About 600 (2,000 x 0.3 s), each running the query, and the load makes the query slower so the number grows. Defences: request coalescing (singleflight) per process, a lock or lease across the cluster, stale-while-revalidate or XFetch so one caller refreshes while others are served; plus jittered TTLs.

5 — What does XFetch's beta do, and why does the rule use delta? Good to know ​

Answer

Answer: beta scales the random head start: values above 1 make early recomputation more likely. delta is the measured recompute time, so slow items start refreshing earlier than fast ones; the head start is -delta * beta * ln(rand).

6 — Your Redis cache returns OOM errors on SET. What happened and what do you change? Must-know ​

Answer

Answer: maxmemory was reached under noeviction (the default) or a volatile-* policy with keys lacking TTLs. Set maxmemory-policy allkeys-lfu or allkeys-lru on cache instances, put TTLs on cache keys, and move queues and locks to an instance with noeviction.

7 — Why does MGET user:1 user:2 fail on Redis Cluster while MGET {user:1}:a {user:1}:b works? Important ​

Answer

Answer: Multi-key commands require all keys in one hash slot. user:1 and user:2 hash to different slots (CROSSSLOT). With the hash tag {user:1} only user:1 is hashed, so both keys share a slot.

8 — What is the difference between -MOVED and -ASK? Good to know ​

Answer

Answer: MOVED means the slot now belongs permanently to another node: update the slot map and send there. ASK means the slot is being migrated and this key is already on the target: send ASKING and the command to the target once, but keep the map until migration finishes and a MOVED arrives.

9 — When is W-TinyLFU better than LRU? Good to know ​

Answer

Answer: When access is skewed and there are scans or one-off accesses: TinyLFU admits a new key only if its estimated frequency beats the victim's, so a scan cannot flush the hot set. The small LRU window keeps brand-new bursts long enough to build frequency.

10 — Hit ratio rises from 95% to 99%. By what factor does database load fall? Must-know ​

Answer

Answer: Misses go from 5% to 1% of traffic: a factor of five. Mean latency also falls by four hundredths of the miss penalty.

11 — Name two ways the cache can leak data between tenants and the fix for each. Must-know ​

Answer

Answer: A key without the tenant id (fix: tenant and version in every key, tests that assert the key format), and a shared Redis between environments or apps with the same prefix (fix: distinct REDIS_PREFIX/CACHE_PREFIX or separate instances). At the edge: a personal response cached by a CDN (fix: Cache-Control: private or no-store, bypass on session cookies).

12 — How does Redis client-side caching keep a local copy fresh, and what must the client do on disconnect? Good to know ​

Answer

Answer: With CLIENT TRACKING, the server records keys the client read (or prefixes in BCAST mode) and pushes invalidation messages (RESP3 push or the __redis__:invalidate channel) when they change. On disconnect the client may have missed invalidations, so it must flush its local cache before serving from it again.

Glossary ​

TermMeaning
CacheA store of copies that answers repeated requests without the expensive path
Cache hit / missThe value was / was not found in the cache
Hit ratiohits / (hits + misses)
Miss penaltyExtra latency and backend cost of one miss
Working setKeys accessed within a time window; the cache should hold it
Cache-aside (lazy loading)App reads cache, loads and fills on miss, deletes after writes
Read-throughCache library loads missing values with a configured loader
Write-throughWrites go to cache and database synchronously
Write-behind (write-back)Writes go to cache; persisted to the database later
Refresh-aheadBackground refresh before expiry
Negative cachingCaching "not found" briefly
Cache penetrationRequests for missing keys bypassing the cache to the database
TTLTime to live: when an entry expires
Jittered TTLTTL randomised (for example +/- 10%) to avoid synchronized expiry
Cache invalidationEnding an entry's life because it is or may be wrong
Purge / banRemoving one entry / filtering out matching entries (Varnish)
Cache tagsLabels on entries for group invalidation (Laravel Cache::tags, Cloudflare Cache-Tag)
Surrogate keyFastly's tag header for group purges
Generational keyKey containing a generation counter; bumping it hides old entries
Stale readReading a value older than the latest committed write
Read-your-writesA client always sees its own previous writes
Double write raceInterleaved cache and database updates leave an older value cached
Delete then write / write then deleteInvalidate before / after the database write; after is correct
Stale setA refill that installs an outdated value (Facebook's term)
LeaseToken that authorizes one client to fill a key; a delete invalidates it (memcache leases)
Versioned valueCache entry carrying the source row's version
Compare-and-set (CAS)Atomic set that succeeds only if the current state matches
Event-driven invalidationInvalidating from change events (CDC, outbox)
CDCChange Data Capture: reading committed changes from the database log
Stampede / dogpile / thundering herdMany concurrent misses recomputing the same key
Request coalescingMerging concurrent identical requests into one (singleflight, Varnish)
singleflightGo package that suppresses duplicate concurrent calls per key
Probabilistic early expiration / XFetchRecompute early with rising probability near expiry
Stale-while-revalidateServe stale while one refresh runs (RFC 5861, Cache::flexible)
Stale-if-errorServe stale when the origin fails (RFC 5861)
GraceVarnish's serve-stale period after TTL
Cache warmingPrefilling a cache before traffic arrives
Hot keyA key with more traffic than one node can serve
Big keyA value or collection large enough to block operations
Key splittingStoring N copies of a hot key under different names
EvictionRemoving entries to free memory
LRU / LFULeast recently / least frequently used eviction
Approximated LRURedis's sampled LRU (maxmemory-samples)
ARCAdaptive Replacement Cache, self-tuning recency/frequency
TinyLFU / W-TinyLFUFrequency-sketch admission policy / with a small LRU window
maxmemory / maxmemory-policyRedis memory limit / eviction policy (allkeys-lru, volatile-lfu, noeviction...)
In-process cache (L1)Cache inside the application's memory (Caffeine, ristretto, otter)
Distributed cache (L2)Network cache shared by all app servers (Redis, memcached)
memcachedMulti-threaded key-value cache with slab allocation
RedisData-structure server used as cache, with replication and Cluster
VarnishHTTP reverse-proxy cache with VCL, grace and bans
SentinelRedis HA: monitoring, failover, configuration provider
Redis ClusterRedis sharding over 16384 hash slots with built-in failover
Hash slotOne of 16384 partitions; CRC16(key) mod 16384
Hash tag{...} part of a key; only it is hashed
MOVED / ASKCluster redirections: permanent owner change / migrating slot
ASKINGCommand that lets the next command run on an importing node
TRYAGAIN / CROSSSLOTCluster errors for split migrations / keys in different slots
ReshardingMoving hash slots between nodes
READONLYAllows reads from a Cluster replica on that connection
Client-side cachingApp keeps local copies; Redis sends invalidations
CLIENT TRACKINGRedis command enabling server-assisted invalidation
RESP3Redis protocol version 3, supports push messages
Keyspace notificationsRedis Pub/Sub events on key changes and expiries
GutterFacebook's small pool that takes over for failed memcached servers
Remote markerFacebook's key marking data as possibly stale in a replica region
Cache::remember / Cache::flexibleLaravel cache-aside / stale-while-revalidate
Cache::lock / atomic lockLaravel distributed lock on the cache store
Cache::addLaravel atomic "set if absent"
Cache::memoLaravel per-request memoization over a store

References ​

Built by Morteza Negahi