LRU Cache TTL Stale-While-Revalidate

Combine LRU eviction with TTL expiry and stale-while-revalidate semantics so hot keys stay warm, expired entries serve stale, and refreshes dedupe.

JavascriptData Fetching

Code

javascriptsnippet
35 lines
import { LRUCache } from 'lru-cache';

const cache = new LRUCache({
  max: 500,
  ttl: 60_000,
  staleTtl: 300_000,
  allowStale: true,
  fetchMethod: async (key) => {
    const res = await fetch('https://api.example.com/rates/' + key);
    if (!res.ok) throw new Error('upstream ' + res.status);
    return res.json();
  },
});

const inflight = new Map();

async function getRate(currency) {
  const value = await cache.fetch(currency);
  return value;
}

async function revalidate(key, loader) {
  if (inflight.has(key)) return inflight.get(key);

  const task = loader()
    .then((fresh) => { cache.set(key, fresh); return fresh; })
    .finally(() => { inflight.delete(key); });

  inflight.set(key, task);
  return task;
}

const usd = await getRate('usd');
const again = await getRate('usd');
console.log('rate:', usd.rate, 'second read:', again.rate);

How it works

Count the functions getRate and revalidate as the entire surface area of LRU Cache TTL Stale-While-Revalidate.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Reach for lru-cache and what you get is LRUCache — that is the whole API contact area. When the guard condition holds, Error is thrown rather than a bogus value returned.

What to watch for

  • lru-cache must be installed first — the snippet imports it directly.
  • Uses fetch, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard !res.ok short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads async function getRate(currency)

Each run prints the 1 labeled block rate: in source order.

Key statements

.then((fresh) => { cache.set(key, fresh); return fresh; })
.finally(() => { inflight.delete(key); });
const res = await fetch('https://api.example.com/rates/' + key);
if (!res.ok) throw new Error('upstream ' + res.status);

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
What does this need from the package registry?
These are real dependencies: `lru-cache`. Without it the snippet will not load.