The 30-line cache that made our dashboard feel instant

People don't read analytics dashboards, they fidget with them. Last 30 days, last 7, back to 30 just to check. Every click used to bring up a spinner, even for numbers they'd seen five seconds earlier. Now going back is instant, and the whole cache fits on one screen.

30 days7 days30 daysGermanyNo filter first looknew viewrevisitnew viewrevisit Before 30 days: waits on the network 7 days: waits on the network 30 days again: waits on the network Germany: waits on the network No filter again: waits on the network waitwaitwaitwaitwait After 30 days: waits on the network 7 days: waits, with the previous numbers shown faded Germany: waits, with the previous numbers shown faded waitwaitwait 30 days again: instant, from the cache No filter again: instant, from the cache instantinstant Waiting on the network Shown instantly from the cache
Before: five waits. After: three, and both revisits are instant.

What we wanted

  1. A view you saw in the last minute shows instantly, with no request.
  2. An older view shows instantly, faded, while fresh data loads. That's stale-while-revalidate: show the old answer now, fetch a new one quietly, swap it in when it lands.
  3. No duplicate requests for data that's already on its way. If two panels ask for the same numbers at once, they share one request.
  4. Bounded memory: the cache has a size limit, because somebody always leaves the tab open for a week.

Our stats endpoints are plain GETs: they only read data, never change it. And the URL describes the whole answer (/stats/overview?period=7d always means the same numbers), so the URL is the cache key, the label each saved answer is filed under.

The cache

recent = new Map()       // path -> (fetched_at, data), oldest first
inFlight = new Map()     // path -> the request on its way
RECENT_MAX = 200

// GETs a stats path, sharing a request already in flight and remembering the answer.
function getStats(path):
    if path not in inFlight:
        inFlight[path] = fetch(path)
            then data:
                recent.delete(path)              // re-adding moves it to the back
                recent.set(path, (now, data))
                if recent.size > RECENT_MAX:
                    recent.delete(first key)     // the oldest
            finally:
                inFlight.delete(path)            // success or failure
    return inFlight[path]

// The remembered answer for a stats path, and how old it is.
function recentStats(path):
    entry = recent.get(path)
    return entry and (entry.data, age: now - entry.fetched_at)
  • inFlight removes duplicates. A request is "in flight" once it's sent but before the answer is back. fetch hands back a promise, an IOU for an answer that hasn't arrived yet. We store the promise straight away, so a second caller gets the same IOU instead of sending a second request. finally clears it either way, so a failure isn't remembered.
  • A Map is nearly an LRU already. An LRU cache ("least recently used") is one that, when it's full, throws out whatever has gone untouched the longest. A JavaScript Map is a key-to-value lookup table that remembers the order keys were added, and deleting then setting a key moves it to the back. So the first key is always the oldest, and past 200 entries it goes. That's the whole clean-up rule, for free. Strictly, it drops the least recently fetched entry, not the least recently read. It's close enough, and we checked.
  • Each entry knows its age, so callers decide what "fresh" means. The dashboard says under a minute.

The hook

The dashboard is React, and a hook is React's way of packaging up "fetch this and keep track of it" so any component can reuse it. Each panel calls useStats with its URL and gets back numbers plus a loading flag.

STATS_FRESH_MS = 60_000

function useStats(path):
    on path change:
        hit = recentStats(path)
        if hit and hit.age < STATS_FRESH_MS:
            last = hit.data, loading = false     // fresh: no request at all
            stop
        loading = true
        live = true
        getStats(path)
            then data: if live, last = data
            finally: if live, loading = false
        when path changes again: live = false    // ignore answers for a path we left

    // Until this path's answer arrives, the previous one stays on screen, faded.
    hit = recentStats(path)
    fresh = hit and hit.age < STATS_FRESH_MS
    return data: hit.data or last, loading: loading and not fresh

The last three lines do the stale-while-revalidate part. If there's a remembered answer for this exact path, it shows the moment the panel draws, and if it's fresh there's no loading state at all. Otherwise the previous path's data stays on screen, faded, until the new answer lands. Numbers changing in place read much better than a panel collapsing into a spinner and back. The live flag ignores answers for a path the user has already left, so a slow response can't overwrite a newer one. Click 7 days, then quickly 30 days: if the 7-day answer straggles in last, it's thrown away.

Why not the browser's HTTP cache?

Browsers have a cache built in, steered by the server's Cache-Control header. Cache-Control: max-age=60, stale-while-revalidate=300 means "reuse this for a minute, then for five more minutes hand out the old copy while fetching a new one". That gets close, but:

  • The UI can't tell stale from fresh. The browser hands back the old copy without saying it's old, so we can't fade the old numbers.
  • Private data can end up on disk. The browser may save cached responses to the hard drive. Ours lives in memory, so it's gone when the tab closes.
  • Prefetching needs the same store. Prefetching means starting a request before anything asks for it. A dashboard starts every panel's request before the panels appear on the page, and when each panel arrives, getStats hands it the request that's already on its way. That took a whole round trip (one request to the server and back) off opening a dashboard: We made our dashboard 35% faster without making any query faster.

Reach for a library when you need edits that update the cache, refetching when the user switches back to the tab, retries or pagination. That's where 30 lines become 3,000.

The result

Going back to a period, or removing a filter, is now instant: no request, no spinner. Try it on the demo. Open your browser's developer tools, flip between two periods and watch the Network tab, which lists every request, do absolutely nothing.