Field Notes

Play's Cache API Cache aside, Proven by Tests: Eight Lessons with Caffeine, Guice and MongoDB

Play's Cache API Cache aside, Proven by Tests: Eight Lessons with Caffeine, Guice and MongoDB

I wanted to learn Play Framework’s cache API properly, not just copy a getOrElseUpdate call from the docs. So I ran it as a structured experiment: an empty Play 3 / Scala 2.13 template, eight lessons, and one rule. Before running anything, I wrote down what I expected. Then I typed the code myself, ran it, and kept a journal of every wrong guess.

Halfway through, I added a second rule: when the docs stop, read the source. Several of the most useful findings below came from opening the play-cache and play-caffeine-cache 3.0.12 source jars, not from the documentation. One of them contradicted what I had “learned” three lessons earlier.

Everything is in a public repository: github.com/zakariahere/cacheplay. The app is small but realistic (a deliberately slow upstream, MongoDB, HTTP endpoints), and 37 tests pin down how the cache actually behaves.

The setup: a trait in Play, an implementation you choose

Play splits caching into an API and an implementation. play.api.cache.AsyncCacheApi and SyncCacheApi ship with Play. An implementation only arrives when you add one to build.sbt. I used Caffeine, the in-memory default:

libraryDependencies ++= Seq(guice, caffeine, /* ... */)

The consequence is the first gotcha. Without caffeine, code that injects AsyncCacheApi still compiles, because the trait exists. It fails when the app starts, as a Guice error. I had switched the template from compile-time DI to runtime Guice for this project, and this is exactly the trade I accepted: a missing wire moves from compile time to startup.

The second gotcha was an import. I ended up with play.cache.AsyncCacheApi, which is the Java API. The compiler error gave it away by mentioning CompletionStage[java.util.Optional[Int]]. Play ships most APIs twice; in Scala code the package should contain .api..

Type safety: where the check actually lives

The cache stores Any, so reading a value back needs a runtime check. The signature promises one: get[T: ClassTag](key). In my first lesson I tested it with the sync API, and it worked as advertised:

sync.set("l1-type", "42")
sync.get[Int]("l1-type") mustBe None          // the ClassTag filter rejects a String

Then I tried a generic type, and the check stopped meaning anything. At runtime List[String] and List[Int] are both just List, so the filter passes:

sync.set("l1-erasure", List("a", "b"))
val result = sync.get[List[Int]]("l1-erasure")
result.isDefined mustBe true                                 // the check passes
a[ClassCastException] must be thrownBy (result.get.head + 1)  // and the value explodes on use

The exception does not happen at the cache call. It happens wherever the value is first used as an Int, because that is where the compiler inserted the unboxing cast. In a real system that could be another service, minutes later, with a stack trace that never mentions the cache. Calling get("k") without a type parameter is similar: Scala infers T = Nothing, Play skips the check, and you get Some(anything).

The bigger surprise came in the last lesson, when I read CaffeineCacheApi.scala. The sync implementation filters with Primitives.wrap(ct.runtimeClass).isInstance(...). The async implementation does not filter at all. It casts:

// AsyncCacheApi, Caffeine implementation (play-caffeine-cache 3.0.12)
resultJFuture.asScala.map(v => Some(v.asInstanceOf[ExpirableCacheValue[T]].value))

So cache.get[Int] on the async API returns Some("42") typed as Option[Int]. My lesson-one conclusion (“the ClassTag protects get”) was only true for the sync API, and the cache-aside service I had written in lesson three used the async one.

Comparison of SyncCacheApi.get and AsyncCacheApi.get: the sync API rejects a String read as Int, the async API returns it; both are defeated by erasure
Only the sync API checks the type, and erasure defeats both. Cache concrete, immutable types.

The practical rule I took from this: never cache a bare generic or an Option. Wrap the value in a concrete case class such as UserNames(values: List[String]), so a runtime check means something where one exists, and do not rely on one where it does not.

getOrElseUpdate, and what it protects you from

To make hits and misses visible, I built a fake upstream that takes one second (with Pekko’s after, so no thread is blocked), returns a random price, and counts its calls:

def quote(symbol: String): Future[BigDecimal] =
  cache.getOrElseUpdate[BigDecimal](s"quote:$symbol", ttl) {
    upstream.quote(symbol)
  }

Two details matter. orElse is a by-name parameter (=> Future[A]), so the slow call only runs on a miss. And the TTL is expire-after-write: Play’s DefaultCaffeineExpiry keeps the current duration on read, so frequent reads do not keep an entry alive.

The more interesting property showed up under concurrency. I released 100 concurrent misses on one key with a single Promise:

val gate = Promise[Int]()
val all = Future.sequence((1 to 100).map { _ =>
  Future(cache.getOrElseUpdate[Int]("hot") { calls.incrementAndGet(); gate.future }).flatten
})
Thread.sleep(200)
gate.success(42)
calls.get mustBe 1

One upstream call. Play delegates to Caffeine’s AsyncCache.get(key, mappingFunction), which is atomic per key: the first miss stores the in-flight future and every other caller receives the same future. The same experiment with a hand-written get-then-set produced 100 upstream calls.

Two cards comparing getOrElseUpdate (1 upstream call) with manual get-then-set (100 upstream calls) for 100 concurrent misses
Stampede protection comes from Caffeine, not Play, and only if you use getOrElseUpdate.

That protection has a flip side. Waiters share a failure as well as a success. A failed future is not cached for the TTL, but Caffeine removes it asynchronously: an immediate retry in my test still got the same RuntimeException("boom") without calling the upstream, while a retry inside eventually succeeded on the second real call. And if orElse throws instead of returning Future.failed, getOrElseUpdate throws synchronously, so code that only uses .recover will not see it.

Cache-aside with MongoDB: the stale data you can watch

With a real repository, two questions appear that a fake never asks. Should “not found” be cached? And what happens when the data changes? I deliberately avoided getOrElseUpdate[Option[Product]]: it would hit the erasure problem on Option, and it would silently cache None, so a product created later would stay invisible for the whole TTL. Negative caching can be useful, but it should be a decision.

I first wrote the update without invalidation, on purpose. After PUT /products/p1/price/9999, GET /products/p1 kept returning the old price until the one-minute TTL ran out. The fix is two lines, but the order matters:

def updatePrice(id: String, priceCents: Long): Future[Boolean] =
  for {
    updated <- repo.updatePrice(id, priceCents)   // 1. write the source of truth
    _       <- cache.remove(key(id))              // 2. then forget the cached copy
  } yield updated

Deleting before the write leaves a window where a concurrent read refills the cache with the old value. Writing the new value with set instead of remove lets two concurrent writers leave the cache holding a value the database no longer has. remove after the write is idempotent, and the next read always comes from the database.

The pitfall tests later showed that this service still had two weaknesses: manual get-then-set gives no stampede protection, and it ran on the async API with no type check. A better version keeps getOrElseUpdate and caches a concrete result type, for example a sealed Found(product) / Missing, with a short TTL for Missing.

Named caches: separate keyspaces and limits

By default everything shares one Caffeine instance called play, with a maximum-size of 10,000 (from Play’s reference.conf). Named caches give each kind of data its own instance:

play.cache {
  bindCaches = ["products"]
  caffeine.caches.products { maximum-size = 10 }
}

Injection uses @NamedCache("products"), which is a Guice qualifier: a plain AsyncCacheApi and one qualified with "products" are different keys in the injector. The tests confirmed separate keyspaces, a removeAll() that leaves the default cache alone, and 100 writes into the size-10 cache leaving at most 10 entries. Caffeine evicts with W-TinyLFU rather than plain LRU, so the survivors are not simply the last ten written. One small correction to my own notes: removeAll() exists only on AsyncCacheApi, which I found through a compile error.

The Cached helper: the year-long 404

play.api.cache.Cached caches a whole HTTP response, and on a hit your action never runs. Reading Cached.scala before using it changed how I wrote the endpoint. cached(key) uses a duration of 0, the builder turns 0 into 365 days (the source even carries a FIXME about it), and the default rule matches every status code.

A test reproduced it: a request for a product that did not exist returned 404, the product was then inserted into MongoDB, and the endpoint kept returning 404, with an Expires header a year in the future. The explicit form behaves:

def findCached(id: String): EssentialAction =
  cached.status(req => s"page:${req.uri}", OK, 30) {
    find(id)
  }

This caches only 200 responses for 30 seconds, and adds an ETag and an Expires header. A request that sends the ETag back in If-None-Match gets 304 Not Modified. The ETag is a SHA-1 of the expiry date, not of the body, so it identifies the cached copy rather than the content.

The cache API has its own interpretation of zero. DefaultCaffeineExpiry maps any duration <= 0 to one second, and my test measured the entry disappearing after about 1055 ms. The same number means one second in one part of Play and a year in another.

Data cache versus Cached helper: set with zero seconds lasts about one second, cached(key) caches every status for 365 days, and service invalidation does not clear the page cache
Two cache layers with different defaults, and they invalidate independently.

The page cache also ignores the data-layer invalidation from the previous section. After updatePrice removed the product entry, /products/:id was fresh and /cached/products/:id still served the old price for up to 30 seconds. Invalidating it from the service would mean rebuilding an HTTP cache key inside business logic. And because Cached has no Vary handling, the key is the only isolation: leave out the query string or the user id, and different requests share one response.

Testing caches without sleeping

My first quote spec waited on a real one-second upstream, slept 5.5 seconds to watch a TTL expire, and could only assert “same price as before” because prices were random. The fix was a seam and a fake:

  • a QuoteUpstream trait, bound in Module.scala to the real implementation;
  • a @Singleton fake that answers instantly with a price the test controls and counts calls;
  • the TTL read from configuration, so a test can set quotes.ttl to 200 milliseconds and use eventually instead of Thread.sleep.
override def fakeApplication(): Application =
  new GuiceApplicationBuilder()
    .configure("quotes.ttl" -> "200 millis")
    .overrides(bind[QuoteUpstream].to[FakeQuoteUpstream])
    .build()

private def fake = app.injector.instanceOf[FakeQuoteUpstream]

The obvious first version holds the fake in a private val and binds it with toInstance. Run on its own, it fails the second test with “2 was not equal to 1”. GuiceOneAppPerTest gives each test a new application, but a ScalaTest suite is one instance for all its tests, so the counter carried over. Letting Guice create a @Singleton fake gives one fake per application. The same reasoning explains why I used GuiceOneAppPerTest for most cache specs: with GuiceOneAppPerSuite, every test in the class shares one cache, which I demonstrated with a test that read a key written by an earlier one.

The last finding happened while preparing the repository for publication. sbt test was green with 34 tests, but reported 8 suites for 9 spec files. The fast quote spec had ended up nested inside a plain wrapper class with the same name, and ScalaTest only discovers top-level suites. The test had never run. Underneath, it was still the version with the shared val, and the service still depended on the concrete upstream instead of the trait, so it would not have tested anything even if discovered. After the fix: 9 suites, 37 tests.

Code showing a ScalaTest spec nested inside a plain class, and sbt output reporting 8 suites completed for 9 spec files
A green build does not prove that a test ran. Compare the suite count with your spec files.

The rules I am keeping

  • Prefer getOrElseUpdate to get-then-set; stampede protection comes with it.
  • Cache concrete, immutable types. Not bare generics, not Option, and not mutable objects: Caffeine stores references, and my test mutated a cached ListBuffer through a value returned by get.
  • Do not rely on the async API to check types.
  • Make negative caching a decision, with its own TTL.
  • Invalidate with remove after the write.
  • Pass an explicit, positive TTL, and give Cached an explicit status and duration.
  • Treat the page-cache key as the only isolation; do not page-cache personalised responses with a URL key.
  • Use a named cache with its own maximum-size for anything keyed by user input.
  • Count your suites.

The method mattered as much as the findings. Writing a prediction before each run made wrong assumptions visible, and reading the source turned several of my “facts” into corrections. The cache API’s guarantees turned out to be whatever its tests prove. The code, the 37 tests and the full lesson journal are on GitHub.

Keep reading