About: how pages are checked

tests/sims/stampede.test.ts

The automated tests for the /simulators/thundering-herd simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. With no protection, each expiry triggers about 1 + λ·cost recomputes (Poisson arrivals during the recompute).
  2. A lock recomputes once per expiry and waiting requests wait cost/2 on average.
  3. Serve-stale never makes a request wait, and XFetch refreshes before expiry so nothing is stale.
  4. TTL jitter spreads expiries of many keys and lowers the peak.
// /simulators/thundering-herd: cache stampede with no protection, a lock, serve-stale and XFetch.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { simulate, type Params } from '../../src/lib/sims/stampede.ts';

const base: Params = { strategy: 'none', rate: 2, keys: 1, ttl: 1000, jitter: 0, cost: 100, beta: 1, duration: 20000 };

test('with no protection, each expiry triggers about 1 + λ·cost recomputes (Poisson arrivals during the recompute)', () => {
	const r = simulate(base);
	const want = 1 + (base.rate / base.keys) * base.cost;
	const sd = Math.sqrt(want / r.expiries);
	assert.ok(Math.abs(r.perExpiry - want) < 4 * sd, `${r.perExpiry} per expiry vs ${want}`);
	assert.equal(r.waited, r.recomputes);
});

test('a lock recomputes once per expiry and waiting requests wait cost/2 on average', () => {
	const none = simulate(base), lock = simulate({ ...base, strategy: 'lock' });
	assert.equal(lock.recomputes, lock.expiries);
	assert.equal(lock.peak, 1);
	assert.equal(lock.waited, none.waited); // same seed, same arrivals: the same requests find the key missing
	assert.ok(Math.abs(lock.meanWait - base.cost / 2) < 5, `mean wait ${lock.meanWait}`);
});

test('serve-stale never makes a request wait, and XFetch refreshes before expiry so nothing is stale', () => {
	const swr = simulate({ ...base, strategy: 'swr' });
	assert.equal(swr.waited, 0);
	assert.equal(swr.recomputes, swr.expiries);
	assert.ok(swr.stale > 0);
	const x = simulate({ ...base, strategy: 'xfetch' });
	assert.equal(x.waited, 0);
	assert.equal(x.stale, 0);
	assert.ok(x.perExpiry < 1.1, `xfetch ${x.perExpiry} recomputes per refresh`);
});

test('TTL jitter spreads expiries of many keys and lowers the peak', () => {
	const many: Params = { ...base, keys: 200, rate: 20, ttl: 2000 };
	let prev = Infinity;
	for (const j of [0, 0.1, 0.3]) {
		const p = simulate({ ...many, jitter: j }).peak;
		assert.ok(p < prev, `jitter ${j}: peak ${p} not below ${prev}`);
		prev = p;
	}
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published