flight-shield helps protect Node.js services from redundant upstream I/O by coalescing concurrent identical requests, guarding caches against stampedes, and micro-batching sequential reads. It has zero runtime dependencies, targets Node.js 20+, and ships ESM and CJS builds with TypeScript types.
npm install flight-shieldimport {
singleFlight,
StampedeShield,
MemoryCacheAdapter,
BatchFlight,
} from "flight-shield";
// 1. Coalesce concurrent identical calls into one upstream execution
const user = await singleFlight.do(
`user:${id}`,
(signal) => db.getUser(id, signal),
);
// 2. Cache with stale-while-revalidate and XFetch stampede protection
const shield = new StampedeShield(new MemoryCacheAdapter());
const product = await shield.getOrSet(
`product:${id}`,
(signal) => db.getProduct(id, signal),
{ ttlMs: 30_000, staleTtlMs: 120_000 },
);
// 3. Collect individual loads in a window into one batch request
const userBatch = new BatchFlight<number, User>(
(ids, signal) => db.getUsersByIds(ids, signal),
{ maxBatchSize: 50, maxWindowMs: 10 },
);
const alice = await userBatch.load(1);See the collapsible Reference sections below for full API signatures, Redis adapters, serialization rules, error contracts, and agent integration notes.
Every primitive exposes per-call or per-instance options with safe defaults:
// SingleFlight: isolate caller references and bound flight lifetime
const user = await singleFlight.do(
`user:${id}`,
(signal) => db.getUser(id, signal),
{ timeoutMs: 2_000, clone: true, maxFlightWindowMs: 500 },
);
// StampedeShield: dynamic TTL, miss filtering, serverless keepalive, soft purge
const item = await shield.getOrSet(
`item:${id}`,
(signal) => db.getItem(id, signal),
{
ttlMs: (val) => (val === null ? 5_000 : 300_000),
staleTtlMs: 120_000,
beta: 1,
shouldCache: (val) => val !== null,
waitUntil: ctx.waitUntil.bind(ctx),
onBackgroundError: (err, key) => logger.warn({ err, key }),
},
);
await shield.softPurge(`item:${id}`);
// BatchFlight: control batch ceiling, collection window, and key identity
const batch = new BatchFlight<string, Record>(
(keys, signal) => fetchRecords(keys, signal),
{ maxBatchSize: 50, maxWindowMs: 10, timeoutMs: 3_000 },
);SingleFlight — concurrent call deduplication and lifecycle control
Collapses concurrent calls sharing the same string key into a single execution of fn. Subsequent calls made after the active flight settles start a new flight.
class SingleFlight {
get inFlightCount(): number;
do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>, options?: FlightOptions<T>): Promise<T>;
doWithMeta<T>(key: string, fn: (signal: AbortSignal) => Promise<T>, options?: FlightOptions<T>): Promise<FlightResult<T>>;
wrap<Args extends unknown[], T>(
fn: (...args: Args) => Promise<T>,
options?: FlightOptions<T> & { keyFn?: (...args: Args) => string },
): (...args: Args) => Promise<T>;
forget(key: string): boolean;
abort(key: string): boolean;
}
export const defaultSingleFlight: SingleFlight; // singleton on globalThis
export const singleFlight: SingleFlight; // alias of defaultSingleFlight| Option | Type | Default | Behavior |
|---|---|---|---|
timeoutMs |
number |
undefined |
Aborts the internal AbortSignal after timeoutMs ms and rejects all waiters. Must be finite and >= 0. |
clone |
boolean | ((val: T) => T) |
false |
Clones the resolved value per caller (including initiator). true tries structuredClone, falls back to JSON.parse(JSON.stringify(v)), then identity if uncloneable (functions, symbols, circular without toJSON). |
maxFlightWindowMs |
number |
undefined |
Evicts the active key from the in-flight map after maxFlightWindowMs ms without aborting running work; subsequent callers start a new flight. Timer is .unref()'d. |
| Field | Type | Description |
|---|---|---|
value |
T |
Resolved payload for this caller. |
shared |
boolean |
true when coalescedCount > 1. |
coalescedCount |
number |
Total callers attached to this flight. |
| API | Effect on in-flight map | Effect on AbortSignal / active waiters |
Return |
|---|---|---|---|
forget(key) |
Evicts key if present (ABA reference-checked) |
Does not abort; current waiters finish undisturbed | boolean (true if found) |
abort(key) |
Evicts key immediately |
Fires AbortController.abort(); all waiters reject |
boolean (true if found) |
timeoutMs |
Evicts key when timeout aborts signal |
Fires AbortSignal.timeout(timeoutMs); all waiters reject |
— |
maxFlightWindowMs |
Evicts key when timer fires |
Running work & current waiters settle normally | — |
// Instantiate an isolated SingleFlight instance for separate domains/subsystems
import { SingleFlight, singleFlight } from "flight-shield";
const authFlights = new SingleFlight();
console.log(authFlights.inFlightCount); // 0
// Preserves `this` context for class/object methods and distinguishes
// `fn()` from `fn(undefined)` when `keyFn` is omitted.
const loadUser = singleFlight.wrap(
async (id: string) => db.getUser(id),
{ keyFn: (id) => `user:${id}`, clone: true },
);
// Telemetry / observability with doWithMeta
const { value, shared, coalescedCount } = await singleFlight.doWithMeta(
`user:${id}`,
(signal) => db.getUser(id, signal),
);
if (shared) {
metrics.increment("coalesced_waiters", { coalescedCount });
}Note: wrap(fn) forwards the original call arguments (fn.apply(receiver, args)) without injecting signal. Use singleFlight.do(key, (signal) => ...) whenever cancellation propagation via AbortSignal is needed.
StampedeShield and CacheAdapter — SWR, XFetch, shouldCache, dynamic ttlMs, waitUntil, softPurge
Provides a stale-while-revalidate (SWR) cache layer with XFetch probabilistic early-expiry and in-flight coalescing via SingleFlight.
class StampedeShield<T> {
readonly cache: CacheAdapter<T>;
readonly singleFlight: SingleFlight;
constructor(cache?: CacheAdapter<T>, singleFlightInstance?: SingleFlight);
getOrSet(
key: string,
loader: (signal: AbortSignal) => Promise<T>,
options?: ShieldOptions<T>,
): Promise<T>;
softPurge(key: string): Promise<void>;
}| Option | Type | Default | Behavior |
|---|---|---|---|
ttlMs |
number | ((value: T) => number) |
60_000 |
Fresh lifetime in ms. Function form computes TTL after loader resolves; returning 0 skips caching; returning negative or non-finite throws RangeError. |
staleTtlMs |
number |
0 |
Additional stale-serving window in ms after ttlMs. Total store lifetime passed to CacheAdapter.set is resolvedTtlMs + staleTtlMs. |
beta |
number |
1 |
XFetch aggressiveness (0 disables probabilistic early refresh). Finite and >= 0. |
shouldCache |
(value: T) => boolean |
undefined |
Evaluated after loader resolves. Returning false returns value to callers without storing it in cache. |
waitUntil |
(promise: Promise<unknown>) => void |
undefined |
Receives background refresh promises so serverless runtimes (Cloudflare Workers, Vercel, Next.js unstable_after) do not terminate refreshes early. |
onBackgroundError |
(error: unknown, key: string) => void | Promise<void> |
undefined |
Invoked if a background refresh rejects; omissions and throws inside this hook are caught safely. |
clone |
boolean | ((val: T) => T) |
false |
Applied once when getOrSet returns cached or loaded values. |
timeoutMs |
number |
undefined |
Aborts the loader AbortSignal via SingleFlight. |
maxFlightWindowMs |
number |
undefined |
Forwarded to SingleFlight for foreground loads. |
| Cache state | Condition (now = Date.now()) |
Caller response | Upstream loader work |
|---|---|---|---|
| Fresh hit | now < envelope.expiry and XFetch condition false |
Immediate envelope.value |
None |
| Fresh hit (XFetch early trigger) | now < envelope.expiry and now - max(1, deltaMs) * beta * ln(max(EPSILON, rand)) >= expiry |
Immediate envelope.value |
At most 1 background refresh (guarded per key) |
| Stale hit | envelope.expiry <= now < envelope.staleExpiry |
Immediate envelope.value |
At most 1 background refresh (coalesced via SingleFlight) |
| Cold miss / hard expired | Absent or now >= envelope.staleExpiry |
Waits on coalesced foreground flight | At most 1 foreground load (all concurrent callers wait together) |
// Pattern A: never cache missing rows (every lookup hits DB, burst still coalesces)
const userA = await shield.getOrSet(`user:${id}`, () => db.findUser(id), {
ttlMs: 300_000,
shouldCache: (v) => v !== null,
});
// Pattern B: short negative-cache TTL for nulls, long TTL for real objects
const userB = await shield.getOrSet(`user:${id}`, () => db.findUser(id), {
ttlMs: (v) => (v === null ? 5_000 : 300_000),
staleTtlMs: 60_000,
});Use shield.softPurge(key) after writes instead of cache.delete(key) when staleTtlMs > 0. It rewrites envelope.expiry = 0 while keeping envelope.staleExpiry and remaining pxMs intact (or deletes the entry if staleExpiry has already elapsed). The next read returns stale data immediately and initiates one background refresh.
interface ShieldEnvelope<T> {
value: T;
deltaMs: number;
expiry: number;
staleExpiry: number;
}
interface CacheAdapter<T> {
get(key: string): ShieldEnvelope<T> | null | undefined | Promise<ShieldEnvelope<T> | null | undefined>;
set(key: string, envelope: ShieldEnvelope<T>, pxMs: number): void | Promise<void>;
delete(key: string): void | Promise<void>;
}Contract for custom adapters:
- Always expire stored entries using
pxMs(equal tottlMs + staleTtlMs), notenvelope.expiry. Usingenvelope.expirydrops stale entries before the stale window runs. - Return
undefinedornullon a miss.
MemoryCacheAdapter<T>: bounded LRU cache in memory (new MemoryCacheAdapter(maxEntries) or new MemoryCacheAdapter({ maxEntries }), default 1_000, positive safe integer). cache.size evicts expired entries before returning count; .get(key) promotes the entry to most-recently-used; .clear() removes all entries.
Using redis (node-redis v4+):
import { createClient } from "redis";
import { StampedeShield, type CacheAdapter, type ShieldEnvelope } from "flight-shield";
const redis = createClient();
class RedisCacheAdapter<T> implements CacheAdapter<T> {
async get(key: string): Promise<ShieldEnvelope<T> | undefined> {
const raw = await redis.get(key);
return raw ? (JSON.parse(raw) as ShieldEnvelope<T>) : undefined;
}
async set(key: string, envelope: ShieldEnvelope<T>, pxMs: number): Promise<void> {
if (pxMs <= 0) return;
await redis.set(key, JSON.stringify(envelope), { PX: Math.ceil(pxMs) });
}
async delete(key: string): Promise<void> {
await redis.del(key);
}
}
export const shield = new StampedeShield(new RedisCacheAdapter());Using ioredis:
import Redis from "ioredis";
import { StampedeShield, type CacheAdapter, type ShieldEnvelope } from "flight-shield";
const redis = new Redis();
class IORedisCacheAdapter<T> implements CacheAdapter<T> {
async get(key: string): Promise<ShieldEnvelope<T> | undefined> {
const raw = await redis.get(key);
return raw ? (JSON.parse(raw) as ShieldEnvelope<T>) : undefined;
}
async set(key: string, envelope: ShieldEnvelope<T>, pxMs: number): Promise<void> {
if (pxMs <= 0) return;
await redis.set(key, JSON.stringify(envelope), "PX", Math.ceil(pxMs));
}
async delete(key: string): Promise<void> {
await redis.del(key);
}
}
export const shield = new StampedeShield(new IORedisCacheAdapter());BatchFlight — adaptive micro-batching and response contracts
Accumulates individual .load(key) calls over a sliding window (maxWindowMs) up to maxBatchSize unique keys and invokes batchFn(keys, signal) once per batch.
interface BatchOptions<K> {
maxBatchSize?: number; // default: 50 (positive safe integer)
maxWindowMs?: number; // default: 10 (finite >= 0)
keySerializer?: (key: K) => string; // default: serializeKey
timeoutMs?: number; // default: undefined (finite >= 0)
}
class BatchFlight<K, V> {
constructor(
batchFn: (
keys: readonly K[],
signal: AbortSignal,
) => Promise<ReadonlyArray<V | Error> | ReadonlyMap<K, V | Error>>,
options?: BatchOptions<K>,
);
load(key: K): Promise<V>;
loadMany(keys: readonly K[]): Promise<Array<V | Error>>;
}- In-window deduplication: Concurrent calls to
load(k)(orloadMany([k, k])) resolving to the same serialized key coalesce onto one pending entry.batchFnreceives uniquekeysonly. - Array response length check: When
batchFnreturns an Array,response.lengthmust equalkeys.length(the deduplicated slice passed tobatchFn). Mismatches reject all callers in that batch with an explicit length-mismatchErrorto prevent off-by-one cross-key leaks (for example SQLWHERE id IN (...)returning fewer rows than requested keys). - Map response matching: When
batchFnreturns aMap(orReadonlyMap), keys are indexed throughkeySerializer(defaultserializeKey), so equivalent object keys still match across serialization boundaries. Missing keys reject or return per-itemErrors rather than throwing across sibling keys. - Per-item errors: Values in
ArrayorMapthat areinstanceof Errorreject only that key in.load(), and resolve asErrorinstances at the corresponding index in.loadMany(). - Empty input:
loadMany([])resolves immediately to[]without starting a flush timer or callingbatchFn. - Batch timer: Flush timers call
.unref()so idle batches do not hold the Node.js event loop open.
SQL databases return rows in arbitrary order and omit missing IDs. Always index rows by key or map them back in keys order:
const users = new BatchFlight<number, User>(async (ids, signal) => {
const rows = await db.query<User>(
"SELECT * FROM users WHERE id = ANY($1)",
[ids],
{ signal },
);
// Option 1: Return a Map (missing IDs automatically become per-item errors)
return new Map(rows.map((row) => [row.id, row]));
// Option 2: Or map into an aligned Array matching `ids.length`
// const byId = new Map(rows.map((row) => [row.id, row]));
// return ids.map((id) => byId.get(id) ?? new Error(`User ${id} not found`));
});serializeKey — deterministic type-tagged key serialization
Converts arbitrary JavaScript values into canonical, type-tagged strings safe for Map keys and cache identifiers.
import { serializeKey } from "flight-shield";
serializeKey({ b: 2, a: 1 }) === serializeKey({ a: 1, b: 2 }); // true
serializeKey(new Set(["b", "a"])) === serializeKey(new Set(["a", "b"])); // true
serializeKey(new Set([1, "1"])); // distinct: number:1 vs string:"1"| Input | Output format | Notes |
|---|---|---|
null / undefined |
null / undefined |
Distinct tags |
string / boolean |
string:"..." / boolean:true |
Prevents "1" vs 1 collision |
number |
number:NaN, number:-0, number:Infinity, number:-Infinity, number:42 |
Special IEEE-754 values distinguished |
bigint |
bigint:123n |
Safe without JSON.stringify crash |
symbol |
symbol:global:"k" or symbol:Symbol(...) |
Global registry symbols distinguished |
Date |
date:"2026-..." or date:Invalid Date |
Distinguishes timestamps vs plain {} |
RegExp |
regexp:"src"/"flags" |
Source and flags preserved |
Array |
array:[...] |
Sparse slots encoded as hole |
Set / Map |
Sorted canonical entries | Order-independent serialization |
| Plain & class objects | Sorted enumerable keys | Unreadable getters encoded as unreadable |
| Circular references | ref:N |
Tracked per serialization via WeakMap |
Framework and runtime recipes — HTTP APIs, Next.js, Cloudflare Workers, GraphQL
import { unstable_after as waitUntil } from "next/server";
import { StampedeShield } from "flight-shield";
import { redisAdapter } from "@/lib/cache";
const productShield = new StampedeShield(redisAdapter);
export async function getProduct(id: string) {
return productShield.getOrSet(
`product:${id}`,
(signal) => fetch(`https://api.internal/products/${id}`, { signal }).then((r) => r.json()),
{
ttlMs: 30_000,
staleTtlMs: 300_000,
waitUntil,
shouldCache: (p) => p !== null,
clone: true,
},
);
}
export async function updateProduct(id: string, patch: unknown) {
await db.products.update(id, patch);
await productShield.softPurge(`product:${id}`);
}import { StampedeShield, MemoryCacheAdapter } from "flight-shield";
const isolateShield = new StampedeShield(new MemoryCacheAdapter(500));
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const key = new URL(request.url).pathname;
const data = await isolateShield.getOrSet(
`route:${key}`,
(signal) => fetchOrigin(key, signal),
{
ttlMs: 15_000,
staleTtlMs: 120_000,
waitUntil: ctx.waitUntil.bind(ctx),
onBackgroundError: (err, k) => console.warn("SWR refresh failed", k, err),
},
);
return Response.json(data);
},
};Create request-dependent BatchFlight instances per HTTP request in GraphQL/API context so auth headers or tenant scopes never mix:
function createLoaders(viewerTenantId: string) {
return {
users: new BatchFlight<number, User>(async (ids, signal) => {
const rows = await db.getUsersForTenant(viewerTenantId, ids, signal);
return new Map(rows.map((u) => [u.id, u]));
}),
};
}SingleFlight, StampedeShield, and BatchFlight pass an AbortSignal into loader callbacks so timeouts cancel underlying fetch() or driver queries cleanly:
const payload = await singleFlight.do(
`external:${serializeKey(params)}`,
(signal) => fetch(url, { signal }).then((res) => res.json()),
{ timeoutMs: 1_500 },
);Comparison, XFetch tuning, module formats, and FAQ
| Situation | Use |
|---|---|
| Hot endpoint receives 100 simultaneous requests for the exact same uncached key | singleFlight.do() |
| Read endpoint tolerates brief staleness and needs instant responses during refresh | StampedeShield |
Loop or GraphQL resolvers trigger dozens of findById(id) calls in one tick |
BatchFlight |
Need order-independent canonical string keys from nested objects, BigInt, Set, Map |
serializeKey() |
- Conservative baseline:
ttlMs: 30_000, staleTtlMs: 120_000, beta: 1(XFetch standard default). - Aggressive pre-warming: raise
betato2–3for slow loaders where expiry spikes are costly. - Deterministic expiry (no early refresh): set
beta: 0; refresh only triggers oncenow >= expiryinsidestaleTtlMs. - Disable SWR entirely (pure cached single-flight): set
staleTtlMs: 0, beta: 0.
| Target | Entry | Types | Notes |
|---|---|---|---|
ESM (import) |
./dist/index.js |
./dist/index.d.ts |
"type": "module", Node.js >= 20.0.0 |
CommonJS (require) |
./dist/index.cjs |
./dist/index.d.cts |
Verified via @arethetypeswrong/cli |
| Tree-shaking | — | — | "sideEffects": false |
- Is
flight-shielddistributed across multiple pods? No. All coordination is process-local. Share cache state across instances by implementingCacheAdapteragainst Redis or Memcached. - Should write operations (
POST,PATCH,DELETE) be coalesced? No. Only coalesce idempotent reads where every waiter expects an identical result. - What happens if
batchFnreturns fewer rows than uniquekeys? Array responses whose length differs fromkeys.lengthreject the entire batch cleanly instead of shifting results across callers. Return aMap<K, V | Error>when partial keys may be missing. - Why does
softPurge(key)beatcache.delete(key)? Deleting a key removes the stale fallback, causing the next concurrent read burst to block on a cold miss.softPurge(key)keeps the stale value available so readers return immediately while one background refresh updates the store.
Agent integration, constraints, and error matrix
Machine-readable specifications ship inside the published package at AGENTS.md and llms.txt.
- Do not coalesce mutations: Writes (
INSERT,UPDATE,DELETE) carry distinct caller intent and must never share a flight. - Pass
pxMs, neverenvelope.expiry, to Redis TTLs:CacheAdapter.set(key, envelope, pxMs)passesttlMs + staleTtlMsaspxMs. Expiring keys onenvelope.expirydeletes stale entries prematurely and breaks SWR. - Always pass
waitUntilin serverless environments: Runtimes such as Cloudflare Workers, Vercel Functions, and Next.js App Router freeze or cancel background promises once the HTTP response finishes unless registered withwaitUntil. - Use
shield.softPurge(key)after writes: Avoidcache.delete(key)whenstaleTtlMs > 0. - Scope multi-tenant keys explicitly: Always embed tenant/auth identifiers inside keys (
tenant:${tenantId}:...).
| Failure source | SingleFlight |
StampedeShield |
BatchFlight |
|---|---|---|---|
| Upstream loader rejects | Waiters for that flight reject; key evicted for fresh retry | Cold foreground load rejects; background SWR failure serves stale and calls onBackgroundError |
All keys in that batch reject |
timeoutMs expires |
AbortSignal aborts; waiters reject |
Loader AbortSignal aborts; cold load rejects |
Batch AbortSignal aborts; batch rejects |
Item-level Error in batch result |
— | — | Only that key rejects in load(); returned inline in loadMany() |
Missing key in Map batch result |
— | — | Treated as per-item Error |
Length mismatch in Array batch result |
— | — | Entire batch rejects with length-mismatch Error |
Uncloneable value with clone: true |
Falls back structuredClone -> JSON -> original ref |
Same fallback | — |
Benchmarks, tests, and package verification
Measured with mitata (node --expose-gc benchmarks/coalesce.bench.mjs) on Node.js v26.13.1 (x64-win32), AMD Ryzen 5 5600H, 200 concurrent callers, 10 ms simulated upstream I/O:
| Measurement | Without coalescing | With SingleFlight |
Delta |
|---|---|---|---|
| Single 200-caller burst upstream calls | 200 | 1 | 200x fewer upstream calls |
| Single 200-caller burst heap delta | +231.61 KiB | +158.84 KiB | -31.4% heap allocation |
| Mitata full run upstream executions | 9,000 | 44 | -99.5% total upstream calls |
| Mitata p99 allocation range (per iter) | 244.94 KiB | 139.53 KiB | -43.0% p99 memory |
serializeKey (nested object + BigInt + Map) |
— | 14.63 µs/iter | 68,337 ops/s |
Note on burst wall-clock time: coalesced callers share a single I/O round-trip (10 ms) plus microtask fan-out, yielding ~16 ms average iteration time in mitata (16.23 ms baseline vs 16.54 ms coalesced under unbounded in-memory concurrency). Real database pools amplify throughput savings because baseline calls queue on finite connection limits.
npm install
npm test # 63 regression tests via vitest
npm run build # ESM + CJS + .d.ts / .d.cts via tsup
npm run check:exports # publint validation
npm run check:types # publint + @arethetypeswrong/cli tarball check
npm run bench # build + mitata coalescing benchmarkMIT — see CHANGELOG, Contributing, Code of Conduct, and Security.