What you'll learn: By the end of this lesson you will be able to classify any caching code by two questions (who loads the value on a miss, and who writes the database on an update), explain cache-aside, read-through, write-through and write-back (also called write-behind) and what each costs in database reads, database writes and staleness, tell which of them Spring's cache annotations give you and which you must build, avoid the self-invocation trap that silently turns caching off, and choose a strategy per kind of data using counts from a Spring and Caffeine lab.
A bakery keeps its best sellers on a shelf by the till. The assistant looks on the shelf first and walks to the back oven only when a loaf is missing. In another arrangement the shelf has its own runner: you ask the shelf, and it fetches from the oven if needed. In a third, every new loaf goes on the shelf and into the oven's ledger before the assistant says "done". In a fourth, the assistant says "done" as soon as the loaf is on the shelf and a clerk updates the ledger at closing time, which is fast until the night the shop floods.
Those are the four cache strategies. Caching basics introduced cache-aside and advanced caching listed the write policies in one table. This lesson is the dedicated treatment: the two questions that separate them, what each costs in counted operations, and how Spring's cache abstraction maps onto them. Eviction, invalidation and stampedes have their own lessons.
Verified with Java 25, Spring Boot 4.1.2 (Spring Framework 7.0.10), Caffeine 3.2.4, the Spring Framework and Caffeine documentation, Oracle Coherence 15.1.1 documentation, the Azure Architecture Center and the Amazon ElastiCache documentation, on 2026-12-01.
The core idea
A cache strategy answers two questions. On a read miss, who loads the value: the application or the cache? On a write, who updates the database and when: the application, the cache before it answers, or the cache after it answers? Everything else (latency, staleness, data loss, code you must write) follows from those two answers.
| Strategy | Read miss | Write | Database updated |
|---|---|---|---|
| Cache-aside | The application loads and stores | The application writes the database, then evicts or updates the entry | By the application, before the cache is touched |
| Read-through | The cache loads, through a loader it was given | (any write strategy) | (any) |
| Write-through | (usually combined with read-through) | The cache writes the database, then keeps the value | By the cache, before the write returns |
| Write-back (write-behind) | (usually combined with read-through) | The cache keeps the value and queues the database write | By the cache, after the write returned |
Read-through is a read-side answer and the other two are write-side answers, so real systems combine one of each: cache-aside with evict-on-write, read-through with write-through, read-through with write-behind. The lab counts all of them on the same workload.
Three illustrations run through the lesson: a minimal example (one product read and updated through each strategy, every database call counted), a realistic example (ShopStream's catalogue, price edits and view counters) and a failure example (a Spring method that calls a cached method on its own object, and a writer that never tells the cache).
Cache-aside and read-through: who loads
In cache-aside the application owns the logic. The Azure Architecture Center describes the steps: the application tries to read from the cache, on a miss retrieves the item from the data store, and adds it to the cache; on an update it writes the data store and then invalidates the cached item.
In read-through the cache owns the loading. Oracle's Coherence documentation: when an application asks for an entry that is not in the cache, the cache delegates to a store it was configured with to load it from the data source, places it in the cache and returns it. The caller never sees a miss, only a slower answer.
Figure 1. The read path in cache-aside and in read-through. How to read this: the arrows show who calls the database. In the top row the application makes both calls and stores the result itself. In the bottom row the application makes one call, and the cache calls the database through the loader it was given.
Cache-aside repeats the loading code at every call site unless you wrap it; read-through keeps it in one loader. Read-through needs a cache that accepts a loader, while cache-aside works with any key-value store, which is why Azure recommends it when a cache lacks native read-through and write-through. The ElastiCache documentation calls it "lazy loading" and lists the miss penalty as three trips: the request to the cache, the query to the database and the write to the cache. A read-through cache does the same work inside the cache.
How Spring maps onto them
Spring's cache abstraction is not a cache. Its reference says it "frees you from having to write the caching logic but does not provide the actual data store"; the interfaces are Cache and CacheManager, and you choose the store (a ConcurrentMap, Caffeine, Redis).
The annotations give you cache-aside, written declaratively. @Cacheable means that on later calls with the same arguments the cached value is returned "without having to actually invoke the method". The method body is your loader and the proxy around the bean is the application-side logic: from the caller's code it looks like read-through, but the cache store never talks to the database, which is the defining property of cache-aside. Spring describes the effect as "a direct equivalent of the typical get-if-not-found-then-proceed-and-put-eventually code blocks", with no locks applied, so several threads may load the same item concurrently.
Real read-through comes from a store that has a loader. CaffeineCacheManager.setCacheLoader turns each cache into a LoadingCache, which Caffeine defines as a cache "built with an attached CacheLoader" that computes an entry when it is absent.
Write-through and write-back: who writes, and when
On the write side the question is when the database learns about the change.
Write-through. The cache stores the write in the database before the write returns. Coherence says the put does not return until the data is stored in the data source, which "does not improve write performance at all". The gain is on the read side: ElastiCache lists "data in the cache is never stale" as the advantage, at the cost of two trips per write and a cache full of entries nobody reads ("cache churn").
Write-back, also called write-behind. The cache acknowledges at once and the database is updated later. Coherence describes modified entries being "asynchronously written to the data source after a configured delay", with several changes to one object in that delay "coalesced" and written once.
Figure 2. When the database learns about a write. How to read this: in write-through the answer comes back after the database call, so the write is as slow as the database. In write-behind the answer comes back first, two updates share one database write, and anything that goes wrong after the early answer is the cache's problem to repair.
What write-back risks
The cache, not the database, holds the newest value for a while. Coherence's documentation is plain about it: "write-behind effectively makes the cache the system-of-record" until the queue has been written, and database updates "occur outside of the cache transaction", which "implies that the database transactions must never fail; if this cannot be guaranteed, then rollbacks must be accommodated". A write-behind cache can be configured to re-queue a failed write.
Figure 3. The two endings of an acknowledged write-behind update. How to read this: the self-loop is the coalescing that saves database writes. The arrow to "Lost" is the price: a client was told the write succeeded, and the only copy was in memory.
Write-back therefore suits data where losing the last few seconds is acceptable and writes to one key are frequent, such as counters, last-seen timestamps and metrics. It is the wrong tool for money, orders and anything a customer was told is saved.
Spring's annotations and the write side
Spring's two write-side annotations are not write-through. @CacheEvict removes the entry, by default after the method completes (if it throws, no eviction happens; beforeInvocation flips the order). @CachePut always runs the method and places the result in the cache. Both leave the database call in your method, so both are cache-aside: write the database first, then evict or refresh. Azure is explicit about the order: update the data store before removing the cached item, because removing it first lets a reader refetch the old row and put it back.
A true write-through or write-back cache needs a hook that runs your database write inside the cache's own write. Spring's abstraction has none, and Caffeine removed the one it had: its CacheWriter is marked "removed in 3.0", and the replacement is the atomic compute operation. Caffeine's Compute page describes write-through as an update where "the cache will only be updated if the writer completes successfully", avoiding races "where the resource and cache are updated as independent atomic operations", and write-behind as an external write after the cache update, improving throughput "at the risk of data inconsistency". The lab builds both in about thirty lines each.
Build it: counting every strategy in a Spring and Caffeine lab
This is the minimal example: a product catalogue, an in-memory stand-in for the database, and counters for every database read and write and every cache hit and miss.
Setup. From examples/spring-labs (no Docker, no database server):
cd examples/spring-labs && ./gradlew :labs:cache-strategies:test
The command runs 15 tests, one of which, GoldenRunTest, compares the report below with examples/spring-labs/golden/cache-strategies.txt. The code is in examples/spring-labs/labs/cache-strategies/src/main/java/buildingai/labs/cachestrategies/.
How the model works. CatalogService is cache-aside with annotations. Reads are one method; writes come in three flavours, one per way to treat the cache:
@Cacheable(cacheNames = "products", key = "#id")
public Product find(String id) {
return db.read(id);
}
@CacheEvict(cacheNames = "products", key = "#updated.id()")
public void updateAndEvict(Product updated) {
db.write(updated);
}
@CachePut(cacheNames = "products", key = "#updated.id()")
public Product updateAndPut(Product updated) {
db.write(updated);
return updated;
}
The cache behind the annotations is a plain Caffeine cache with statistics on, run on the caller's thread so counts do not depend on timing. Read-through is the same cache with a loader set on CaffeineCacheManager. Write-through is a Spring Cache that does its database write inside one atomic per-key compute:
caffeine().asMap().compute(key, (k, current) -> {
database.write(product);
return product;
});
If database.write throws, compute leaves the entry as it was. Write-behind puts the value in the cache, queues the row by product (so repeated updates coalesce) and writes the queue on flush(), which the lab calls by hand to stay deterministic; a real cache flushes after a delay or a batch size.
Cache-aside: reads, and three ways to write
Section 1 of the report reads a product five times and a missing product twice. Section 2 then updates a cached product in three ways. Each row shows the change in database reads, database writes, cache hits and cache misses caused by that one step.
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, Caffeine 3.2.4, 2026-12-01):
== 1. Cache-aside with @Cacheable (CatalogService.find) ==
step db rd db wr hits misses result
find(p1), first read 1 0 0 1 p1 Oat milk 1L @120
find(p1), second read 0 0 1 0 p1 Oat milk 1L @120
find(p1), three more reads 0 0 3 0 p1 Oat milk 1L @120
find(p99), a row that does not exist 1 0 0 1 null
find(p99) again 0 0 1 0 null
A miss runs the method (one database read) and the proxy stores the result; every later read is a hit.
The missing row was cached too (the cache manager allows null values), so the second find(p99) never reached the database.
== 2. Three ways to write while p1 (price 120) is cached ==
step db rd db wr hits misses result
A: write 130 straight to the database (cache not told) 0 1 0 0 database now 130
A: find(p1) 0 0 1 0 p1 Oat milk 1L @120
B: updateAndEvict(140): write, then drop the entry 0 1 0 0 database now 140
B: find(p1), first read after the write 1 0 0 1 p1 Oat milk 1L @140
B: find(p1), second read 0 0 1 0 p1 Oat milk 1L @140
C: updateAndPut(150): write, then store the new value 0 1 0 0 database now 150
C: find(p1), first read after the write 0 0 1 0 p1 Oat milk 1L @150
A leaves the cache serving 120 while the database holds 130. B costs one extra miss and read after the write. C costs none.
The first find(p1) is one miss and one database read; every later read is a hit. A missing row is cached too (the Caffeine cache manager accepts null values by default), so the second find(p99) never reaches the database. In the second block, writer A updates the database without telling the cache, and the next read returns the old price 120 while the database holds 130. Writer B evicts, which costs one miss and one database read after the write. Writer C puts, which costs none.
The self-invocation trap
Spring's default advice mode is proxy, and "only external method calls coming in through the proxy are intercepted"; self-invocation "does not lead to actual caching at runtime even if the invoked method is marked with @Cacheable". The lab's label() calls find() on its own object.
Figure 4. Why a cached method is not cached when called from the same class. How to read this: the cache check lives in the proxy, and a call from inside the bean never passes through it. The top half is the working path; the bottom half is the bug.
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, Caffeine 3.2.4, 2026-12-01):
== 3. Failure example: label() calls find() on its own object ==
step db rd db wr hits misses result
label(p1), first call 1 0 0 0 Oat milk 1L @120
label(p1), second call 1 0 0 0 Oat milk 1L @120
label(p1), third call 1 0 0 0 Oat milk 1L @120
find(p1) from outside, through the proxy 1 0 0 1 p1 Oat milk 1L @120
find(p1) again 0 0 1 0 p1 Oat milk 1L @120
label() reaches find() directly, so the annotation never runs: no hit, no miss, a database read every time.
Three calls to label() cost three database reads and register no hit and no miss, because the cache was never asked. Nothing fails and nothing logs; the symptom is a database busier than the hit ratio suggests. Spring's documentation points to aspectj mode, and the simpler fix is to move the cached method to another bean.
Read-through, write-through and write-behind
Sections 4 to 6 use Caffeine caches with a loader, and the two write policies built for the lab.
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, Caffeine 3.2.4, 2026-12-01):
== 4. Read-through: a Caffeine LoadingCache; the caller only asks the cache ==
step db rd db wr hits misses result
cache.get(p1), first read 1 0 0 1 p1 Oat milk 1L @120
cache.get(p1), second read 0 0 1 0 p1 Oat milk 1L @120
cache.get(p1), three more reads 0 0 3 0 p1 Oat milk 1L @120
cache.get(p99), a row that does not exist 1 0 0 1 null
cache.get(p99) again 1 0 0 1 null
Same counts for p1 as cache-aside, but the loading code lives in the cache (the loader), not in the caller.
The loader returned null for p99; Caffeine stores no entry for that, so each lookup went back to the database.
== 5. Write-through: the put changes the database first, then the cache ==
step db rd db wr hits misses result
put(p1 @160) 0 1 0 0 database now 160
get(p1) right after the write 0 0 1 0 p1 Oat milk 1L @160
put(p1 @999) while the database refuses writes 0 0 0 0 FAILED: database refused the write for p1
get(p1) after the refused write 0 0 1 0 p1 Oat milk 1L @160
five more puts to p1 (@161 to @165) 0 5 0 0 database now 165
Every accepted put is one database write, and a read after it is a hit. A refused write leaves the cache on the old value.
== 6. Write-behind: the put changes the cache and queues the row ==
step db rd db wr hits misses result
five puts to p1 (@161 to @165) 0 0 0 0 database still 120, queued rows 1, queued updates 5
get(p1) before the flush 0 0 1 0 p1 Oat milk 1L @165
flush() 0 1 0 0 1 row written, database now 165
three puts to p1 (@170, @175, @180) 0 0 0 0 database still 165, queued updates 3
the process crashes before the next flush 0 0 0 0 3 acknowledged updates lost, database holds 165
get(p1) after the restart 1 0 0 1 p1 Oat milk 1L @165
Five updates cost one database write once flushed. The three updates that were acknowledged but not flushed are gone.
Read-through gives the same counts for p1 as cache-aside: the strategy changes who runs the loader, not how often. The loader returned null for p99, Caffeine stores no entry for that, and every lookup reached the database (cache-aside above cached the null), so a read-through cache needs its own negative-caching rule if absent rows are common. In write-through, the refused database write left both cache and database on 160: the cache never ran ahead of the system of record. In write-behind, five updates cost one database write once flushed, readers saw 165 while the database still held 120, and the three updates acknowledged after the flush were gone after the crash.
The same workload under six strategies
Section 7 replays 60 operations (48 reads and 12 writes, from a fixed seed, skewed toward one hot product) on five products.
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, Caffeine 3.2.4, 2026-12-01):
== 7. The same 60 operations (48 reads, 12 writes, fixed seed) under six strategies ==
stale = reads that returned a value older than the last acknowledged write.
behind = products whose database row is older than the last acknowledged write when the run ends.
strategy db rd db wr hits misses stale behind
no cache 48 12 0 0 0 0
cache-aside, write evicts 14 12 34 14 0 0
cache-aside, write puts 5 12 43 5 0 0
cache-aside, writes bypass the cache 5 12 43 5 24 0
read-through + write-through 5 12 43 5 0 0
read-through + write-behind, flush every 8 5 10 43 5 0 1
Reads: 48, writes: 12.
These are the numbers of one workload, not a benchmark. Any cache cuts reads from 48 to between 5 and 14. Evicting on write costs nine more reads than putting on write, because each evicted entry must be reloaded. The bypassing writer keeps the lowest read count and serves 24 stale reads out of 48, half of them. Write-through costs the same as put-on-write here, but guarantees the database was written before the cache moved. Write-behind saved two database writes (10 instead of 12) and finished with one row still behind.
Break it. In CatalogService, delete the @Cacheable line on find: the read tests fail, because every read reaches the database. In WriteThroughCache.put, move the database.write call outside the compute call and put into the map first: the refused-write test fails, because the cache moves ahead of the database. Restore both and run the tests again.
Stretch. Add @Cacheable(sync = true) and 50 threads on a cold key (the stampede lab does this without Spring), give WriteBehindCache a queue limit, or add write-around as a seventh strategy.
What the model leaves out. Concurrency (single-threaded on purpose), eviction and size limits (see the LRU lab), expiry, a distributed cache, a real database and its transactions, and the race between a reader's fill and a writer's evict, which cache invalidation covers.
Choosing a strategy
Figure 5. A decision tree for one kind of data. How to read this: start at the top and answer for each kind of data separately; one service often uses three of these answers at once.
| Strategy | Gain | Cost | Wrong when |
|---|---|---|---|
| Cache-aside, evict on write | Works with any cache; the cache stays out of the write path | One extra miss after each write; code at every call site; stale until a writer evicts or the TTL expires | Several writers do not all evict |
| Cache-aside, put on write | No miss after a write | Caches rows nobody reads; two writers can leave the older value in the cache | Writes are frequent and reads rare |
| Read-through | One loader, simpler callers | Needs loader support; tied to one source; negative results need a rule | The cache cannot reach the source or the source differs by call |
| Write-through | Cache never ahead of the database; no stale read after a write | Write latency equals the database's; cache fills with unread data | Writes dominate and reads are rare |
| Write-back | Fast writes; coalescing cuts database writes | Acknowledged writes can be lost; the database lags; the cache becomes the record | The data matters after a crash |
| Writer bypasses the cache | Nothing to maintain | Stale reads until the TTL ends | A reader acts on the value (a price, a stock count) |
The other side of this topic
In a browser the same ideas appear as HTTP caching and revalidation. The front-end lessons HTTP caching, caching across the stack and server state caching and revalidation cover that side; this lesson is about the server's data cache.
In practice: ShopStream's catalogue, prices and view counters
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Numbers are illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's catalogue holds 100,000 products per region and serves about 2,300 browsing requests per second at peak (the course's illustrative figures). Three kinds of data sit behind the product page. Descriptions and photos change a few times a year. Prices are edited by store owners and also by a nightly bulk import from a store's own system. A "viewed N times today" counter is updated on every page view.
Starting architecture
Figure 6. The starting design. How to read this: the catalogue service reads and evicts through the cache and writes the database. The nightly import, in amber, writes the database and never touches the cache.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Cache-aside with a TTL on everything | Simple, one pattern | Prices stale until the TTL; counters hit the database on every view |
| B. Cache-aside with evict-on-write for prices, TTL as a backstop | Owner edits show at once; descriptions stay cached | The import still writes behind the cache's back |
| C. B plus write-behind for view counters | Counter writes drop to one per product per flush | A crash loses the last interval of counts |
The decision
Option C, with a change to the import. Descriptions and photos use cache-aside with a long TTL. Prices use cache-aside: write the database first, evict afterwards, and keep a short TTL as the bound on anything the evict misses. The import calls the same service method as the owners' edits, so it evicts too. View counters use write-behind with coalescing and a flush every few seconds; the team records that the counter may lose the last interval after a crash and is never used for anything billed.
Rollout and verification
A rollout starts with the lab's shape: the same workload through each variant, comparing database reads and stale reads. In production the checks are the hit ratio per method (a method stuck at zero suggests the self-invocation trap), database reads per second at peak, the age of the oldest queued counter write, and a sampled audit that compares cached and database prices for a few hundred products. Verification is "the mismatch count after the import is zero, and the oldest queued counter is younger than the flush interval".
The 2 a.m. failure
Support reports shoppers seeing the old price at checkout after last night's import. The import wrote the database directly (the "writer that bypasses the cache" row of the lab), so cached prices stayed old until their TTL ended. The checks: compare a cached price with the database for an imported product, and look for a missing evict in the import's code path. The mitigation is to evict the imported keys. The lasting fix is that every writer goes through the service that owns the cache, with the sampled audit as an alert, since a TTL only bounds the damage.
Architect's notes
- Name both answers. "Who loads on a miss" and "who writes the database, and when" are separate decisions; write both next to each cache in the design.
- Make one component own the writes. Every writer that bypasses the cache is a stale-read source.
- Write the database before touching the cache. Evict or refresh after the database call succeeded, never before.
- Treat write-back as a durability decision. It makes the cache the record for a while; say what may be lost.
Common mistakes
- Calling Spring's
@Cacheableread-through. The cache store never calls the database; the proxy and your method do. - Evicting before the database write. A reader can refill the old value between the two steps.
- Using write-back for data a customer was told is saved. An acknowledged write can exist only in memory.
- Calling a cached method from its own class. It runs uncached and nothing reports it.
Key takeaways
- Two questions classify every strategy: who loads on a miss, and who writes the database and when.
- Cache-aside keeps the cache passive and the application in charge; read-through gives the cache a loader.
- Write-through updates the database before the write returns; write-back acknowledges first and writes later.
- Spring's annotations are cache-aside; true read-through, write-through and write-back need a store or code that supports them.
- The lab's counts: any cache cut 48 reads to 5 to 14; evict-on-write cost nine more reads than put-on-write; a bypassing writer produced 24 stale reads of 48.
- Choose per kind of data, and give one component the job of writing.
Practice exercises
Exercise 1 (20 min). For a book catalogue, a shopping cart and a page-view counter, choose a strategy for each and say what a crash loses.
Exercise 2 (45 min). Run the lab. In section 2, say what a shopper sees in rows A, B and C and which you would ship for a price.
Exercise 3 (1 hour). Run "Break it". Then call find from a second bean and show the hit it records.
Exercise 4 (2 hours). Add write-around (write the database only, evict nothing) as a seventh strategy and compare its stale reads with the bypassing writer's.
Related reading
- Caching basics and advanced caching: the first cache-aside example and the write policies in one table.
- Cache layers: where a strategy runs.
- Cache invalidation: how an entry learns it is stale.
- Distributed caches: Redis and Memcached: the next lesson, moving the cache out of the process.
Official documentation
- Spring Framework reference, cache abstraction: the annotations, proxy mode and the
CacheandCacheManagerinterfaces. - Caffeine wiki: Population, Compute and Writer.
- Oracle Coherence documentation, Caching Data Sources: read-through, write-through, write-behind and refresh-ahead.
- Azure Architecture Center, Cache-Aside pattern.
- Amazon ElastiCache, Caching strategies.