Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,60 @@ class StampedeShield<T> {
| `coalescedCount` | `number` | Total callers attached to the upstream flight (`0` on cache hits). |
| `cacheError` | `boolean` | `true` when a cache read or write failed and fell back via `onCacheError`. |

<details>
<summary>Prometheus metrics for cache reads and coalesced callers</summary>

Install `prom-client` in your application and define the instruments once. Serve
its registry from your usual metrics endpoint. These helpers return the original
value, so the caller can record a result where it already awaits the read.

```js
import { Counter, Histogram } from 'prom-client';

const reads = new Counter({
name: 'app_cache_reads_total', help: 'Completed cache reads by outcome.', labelNames: ['status'],
});
const refreshes = new Counter({
name: 'app_cache_refreshes_total', help: 'Started background refreshes.', labelNames: ['status'],
});
const fallbacks = new Counter({
name: 'app_cache_fallbacks_total', help: 'Reads served after a cache error.',
});
const callers = new Histogram({
name: 'app_flight_callers', help: 'Flight size seen by each foreground caller.',
labelNames: ['operation', 'shared'], buckets: [1, 2, 4, 8, 16, 32],
});

export function recordFlight(result) {
callers.observe({ operation: 'singleflight', shared: String(result.shared) }, result.coalescedCount);
return result.value;
}

export function recordCache(result) {
reads.inc({ status: result.status });
if (result.revalidated) refreshes.inc({ status: result.status });
if (result.cacheError) fallbacks.inc();
if (result.status === 'miss') {
callers.observe({ operation: 'cache', shared: String(result.shared) }, result.coalescedCount);
}
return result.value;
}

// At the call site:
// recordFlight(await singleFlight.doWithMeta(key, load));
// recordCache(await shield.getOrSetWithMeta(key, load, {
// ttlMs: 60_000,
// onCacheError: (error, operation) => console.warn('Cache operation failed', operation, error),
// }));
```

Providing `onCacheError` lets the read return a value after a cache failure so
`recordCache` can count the fallback. A refresh on a `fresh` read is an early XFetch refresh.
A refresh on a `stale` read is stale-while-revalidate. Two callers sharing one flight each observe a
flight size of two. Keep cache keys and user IDs out of the metric labels.

</details>

### Read state machine (`getOrSet`)

| Cache state | Condition (`now = Date.now()`) | Caller response | Upstream loader work |
Expand Down