← Statpro dev log

A cache with a bedtime: 15 seconds fresh, 90 stale

#web#mobile#product

A ring with a short bright amber arc followed by a long dotted arc, around one page that fans out to five small phones

The Stats home on Statpro, my sports stats and betting-research site and app, was being built from scratch for every member who opened it. The Stats home is the landing page for a league's stats, and it shows games in progress. It fires about nine upstream reads per league, meaning separate backend lookups, before it can render anything, and it carries no personal data at all. On a live NFL Sunday, hundreds of phones were each paying for the same page.

Three rules that had to hold together

The fix is to build the page once per league and time zone, then share it. A cache sounds like a chore for a slow afternoon. The shape of this one is the interesting part:

  • Fresh for 15 seconds, because the home carries games in progress.
  • Stale-while-revalidate for 90 seconds. Past the fresh window a reader still gets the old copy instantly while one rebuild runs in the background.
  • Never cache a failure. If the build throws, nothing is stored and the next request retries for real.

The third rule keeps the other two honest. A cache that stores errors turns one transient hiccup into the same crash served to everybody until the entry expires.

ONE COPY PER LEAGUE AND TIME ZONE 0 s 15 s after the stale window 15 s fresh 90 s stale: old copy now, one rebuild behind it miss: build it one cache read still one cache read, never a wait a failed build is never stored
The common case is a single cache read. Only a true miss pays for the build.

The whole policy fits in one call, and every read reports whether it was a hit, a miss or stale:

/** Reads the assembled home through the cache; a build failure is never cached. */
export function cachedStatsHome(league, scope, build, cache, forceRefresh = false) {
  return cache(statsHomeCacheKey(league, scope), build, {
    ttl: 15, staleTtl: 90, forceRefresh,
    onCacheState: (state) => recordTimingStep(`home_cache_${state}`, 0),
  });
}

Cache work fails quietly. With the state in server timing, I can watch the warm path work instead of believing it does.

The key includes your time zone

A shared cache has a nasty edge here: the page shows today in your time zone, so the key carries both league and zone. A warmer is a background job that fills the cache before anyone asks. One that only primes New York helps one zone in five. Mine walks five US zones (the contiguous four plus Arizona, which skips daylight saving) times three leagues, one at a time to keep database load flat.

The app got the same idea one layer up. It remembers your assembled home between launches and throws it away when the account or the data changes.

This is the build log for Statpro (statpro.io) · All entries · Weekly essays