Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion mcp/src/readme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ as real queueing, latency and failures, measured from simulated requests.
finishes when they all answer. So a service wired to a cache and a
database calls both. To model "cache first, database on a miss", wire
service to cache and cache to database: a \`cache\` answers hits itself
and only passes misses on (\`hitRate\`).
and only passes misses on (\`hitRate\`). Two caches in a row with only
\`hitRate\` set multiply their misses; set \`cacheKeys\` on both (how many
of the 64 keys each holds) for a hit rate measured from the clients'
keys, where the second cache sees only what the first could not keep.
- A node with no outgoing edge answers the request itself.
- A \`queue\` acknowledges at once and buffers; \`worker\` nodes wired from it
drain it. Always draw queue to worker. A worker wired to a queue drains
Expand Down
9 changes: 8 additions & 1 deletion src/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,14 @@ export function isTopology(value: unknown): value is Topology {
]) {
if (!Number.isFinite(cfg[key])) return false;
}
for (const key of ['chargeable', 'idempotencyKeys', 'flushEveryMs', 'freshReads']) {
for (const key of [
'chargeable',
'idempotencyKeys',
'flushEveryMs',
'freshReads',
'cacheKeys',
'cacheTtlMs',
]) {
if (cfg[key] !== undefined && !Number.isFinite(cfg[key])) return false;
}
if (ids.has(n.id)) return false;
Expand Down
112 changes: 99 additions & 13 deletions src/components/Inspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ import {
canPause,
takesCorrectness,
} from '../sim/behaviour';
import { hottestKeyShare, MAX_KEY_SKEW } from '../sim/keys';
import { hottestKeyShare, KEYSPACE, MAX_KEY_SKEW } from '../sim/keys';
import {
DEFAULT_CACHE_KEYS,
effectiveCacheKeys,
MAX_CACHE_TTL_MS,
} from '../sim/cacheKeys';
import { DEFAULT_TRAFFIC_PERIOD_S } from '../sim/types';
import {
DEFAULT_BURST_SIZE,
Expand Down Expand Up @@ -145,7 +150,9 @@ type Field =
| 'trafficPeriodS'
| 'burstSize'
| 'herdSize'
| 'herdSpreadMs';
| 'herdSpreadMs'
| 'cacheKeys'
| 'cacheTtlMs';

const FIELDS_BY_KIND: Record<NodeKind, Field[]> = {
// The client generates load and decides how long to wait for an answer.
Expand Down Expand Up @@ -178,7 +185,18 @@ const FIELDS_BY_KIND: Record<NodeKind, Field[]> = {
'retries',
],
// Only the cache has a hit rate. That single knob is the interesting one.
cache: ['hitRate', 'instances', 'capacity', 'serviceMs', 'serviceCv', 'queueLimit'],
// With keys tracked, the hit rate is measured, so the slider gives way to
// how many keys it holds and how long one stays; see shownFields.
cache: [
'hitRate',
'cacheKeys',
'cacheTtlMs',
'instances',
'capacity',
'serviceMs',
'serviceCv',
'queueLimit',
],
// A database is slots, service time, and the write lock: the read/write
// mix and the per-writer lock wait are what make it more than a service.
db: [
Expand Down Expand Up @@ -231,7 +249,15 @@ const FIELDS_BY_KIND: Record<NodeKind, Field[]> = {
// A CDN is a cache whose whole story is the hit rate: how much load never
// reaches you. Capacity and service time are shown because a saturated
// edge is still a real failure mode.
cdn: ['hitRate', 'instances', 'capacity', 'serviceMs', 'queueLimit'],
cdn: [
'hitRate',
'cacheKeys',
'cacheTtlMs',
'instances',
'capacity',
'serviceMs',
'queueLimit',
],
// A limiter has exactly two knobs, and the pair is the lesson: sustained
// rate, and how much burst you forgive on top of it.
ratelimiter: ['rateLimitRps', 'burst'],
Expand Down Expand Up @@ -436,7 +462,7 @@ const KIND_BLURB: Record<NodeKind, string> = {
service:
'The workhorse. How many it handles at once, divided by how long each takes, is the ceiling everything else queues behind.',
cache:
'Answers hits without touching downstream. Each cache rolls its own hit chance, independently of the others, so stacking them multiplies misses rather than treating later caches as filters on earlier misses.',
'Answers hits without touching downstream. With a set hit rate, each cache rolls its own chance, so stacking them multiplies misses. Turn on remembering keys and a later cache only sees what the earlier one could not keep.',
db: 'Works on a few requests at once. When they are all busy, the rest wait in line here.',
queue:
'A buffer. Depth is the whole story: it absorbs bursts up to the limit, then turns work away.',
Expand All @@ -450,7 +476,7 @@ const KIND_BLURB: Record<NodeKind, string> = {
'Watches one node and adds capacity when it runs hot. New capacity takes warmup time to arrive, so load always leads it.',
region:
'Sends traffic to one region at a time. If that region dies, failover costs you a full outage window before the next one takes over.',
cdn: 'An edge cache in front of everything. At a 0.9 hit rate one CDN leaves a tenth of the traffic for the origin, and that chance is rolled independently of every other cache on the path. It is still the cheapest capacity you will ever add.',
cdn: 'An edge cache in front of everything. At a 0.9 hit rate one CDN leaves a tenth of the traffic for the origin, and with a set hit rate that chance is rolled independently of every other cache on the path. It is still the cheapest capacity you will ever add.',
ratelimiter:
'A token bucket. Refuses excess traffic instantly instead of queueing it, which is what stops a busy system turning into a dead one.',
breaker:
Expand Down Expand Up @@ -625,6 +651,13 @@ const SHAPE_FIELDS: Partial<Record<Field, ReadonlySet<string>>> = {
/** This kind's fields, less the ones the node's traffic shape does not read. */
function shownFields(kind: NodeKind, config: NodeConfig): readonly Field[] {
const fields = FIELDS_BY_KIND[kind];
if (kind === 'cache' || kind === 'cdn') {
// A cache that tracks keys measures its hit rate instead of taking one.
const keyed = effectiveCacheKeys(config) > 0;
return fields.filter((f) =>
f === 'hitRate' ? !keyed : f === 'cacheKeys' || f === 'cacheTtlMs' ? keyed : true,
);
}
if (kind !== 'client') return fields;
const shape = config.traffic ?? 'steady';
return fields.filter((f) => SHAPE_FIELDS[f]?.has(shape) ?? true);
Expand Down Expand Up @@ -654,6 +687,8 @@ const ABSENT_FIELD: Partial<Record<Field, number>> = {
burstSize: DEFAULT_BURST_SIZE,
herdSize: DEFAULT_HERD_SIZE,
herdSpreadMs: 0,
cacheKeys: DEFAULT_CACHE_KEYS,
cacheTtlMs: 0,
};

/** A choice field's value, or its first option when absent. */
Expand Down Expand Up @@ -729,7 +764,7 @@ const FIELD_SPECS: Record<Field, FieldSpec> = {
term: 'hit-rate',
label: 'Hit rate',
unit: 'percent',
hint: 'Each cache or CDN rolls this chance on its own. Two at 80% leave about 4% of traffic for whatever is behind them, because the chances multiply.',
hint: 'Each cache or CDN rolls this chance on its own. Two at 80% leave about 4% of traffic for whatever is behind them, because the chances multiply. Turn on Remember which keys it holds for a hit rate that comes from the traffic instead.',
min: 0,
max: 1,
step: 0.01,
Expand Down Expand Up @@ -828,6 +863,26 @@ const FIELD_SPECS: Record<Field, FieldSpec> = {
? 'Every one of the 64 keys is equally likely, about 1.6% of requests each.'
: `The hottest of the 64 keys gets ${formatPct(hottestKeyShare(v))} of requests, and a sharded store sends all of them to one partition.`,
},
cacheKeys: {
control: 'number',
label: 'Keys it holds',
unit: `of the ${KEYSPACE} keys`,
hint: 'When it is full, the key used least recently makes room. Hot keys stay, so the hotter the traffic, the more it hits.',
min: 1,
max: KEYSPACE,
step: 1,
},
cacheTtlMs: {
control: 'slider',
term: 'ttl',
label: 'Forget a key after',
unit: 'milliseconds, 0 keeps it until it is pushed out',
hint: 'Once a key is this old, the next read of it goes to the store again. Every key expiring at once is a stampede.',
min: 0,
max: MAX_CACHE_TTL_MS,
step: 500,
display: (v) => (v <= 0 ? 'never' : formatMs(v)),
},
traffic: {
control: 'choice',
term: 'traffic-shape',
Expand Down Expand Up @@ -1406,6 +1461,8 @@ const FIELD_GROUPS: { title: string; fields: ReadonlySet<Field> }[] = [
'herdSpreadMs',
'keySkew',
'hitRate',
'cacheKeys',
'cacheTtlMs',
'replicaCount',
'replicationLagMs',
'readFraction',
Expand Down Expand Up @@ -2271,11 +2328,19 @@ function KindStatRows({
switch (kind) {
case 'cache':
return (
<StatRow
label="Hit rate right now"
term="hit-rate"
value={formatPct(stats.hitRate)}
/>
<>
<StatRow
label="Hit rate right now"
term="hit-rate"
value={formatPct(stats.hitRate)}
/>
{stats.cachedKeys !== undefined && (
<StatRow
label="Keys held"
value={`${stats.cachedKeys} of ${effectiveCacheKeys(config)}`}
/>
)}
</>
);

case 'cdn':
Expand All @@ -2290,6 +2355,12 @@ function KindStatRows({
label="Fetched from origin"
value={formatRate(stats.originFetchRate)}
/>
{stats.cachedKeys !== undefined && (
<StatRow
label="Keys held"
value={`${stats.cachedKeys} of ${effectiveCacheKeys(config)}`}
/>
)}
</>
);

Expand Down Expand Up @@ -3586,9 +3657,24 @@ function SingleInspector({
</Section>
)}

{grouped.map((group) => (
{grouped.map((group, gi) => (
<Section key={group.title} title={group.title}>
<div className="ins-fields">
{gi === 0 && (node.kind === 'cache' || node.kind === 'cdn') && (
<ToggleRow
label="Remember which keys it holds"
about="remembering keys"
hint={`Hits only on keys it really holds, so hot keys raise its hit rate. Off, every request rolls the hit rate on its own. On, it holds real keys out of the ${KEYSPACE} the clients ask for, fills one when the store behind it answers a read, and loses them all if it crashes or restarts. Its hit rate then comes from how hot the keys are, and a second cache behind it only sees the keys this one could not keep.`}
checked={effectiveCacheKeys(cfg) > 0}
locked={lockedFields?.includes('cacheKeys') ? lockNote : undefined}
onChange={(on) =>
onChange(node.id, {
cacheKeys: on ? DEFAULT_CACHE_KEYS : undefined,
cacheTtlMs: undefined,
})
}
/>
)}
{group.fields.map((field) => {
const spec = specFor(node.kind, field);
const locked = lockedFields?.includes(field) ?? false;
Expand Down
15 changes: 12 additions & 3 deletions src/content/glossary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ export const GLOSSARY: GlossaryEntry[] = [
id: 'cache',
term: 'Cache',
short: 'Remembers recent answers so the work is not repeated',
why: 'A hit is answered immediately; a miss costs a full trip to whatever is behind it. For one cache, at 90% the database sees a tenth of the traffic. Each cache rolls that chance independently, so stacking two 80% caches leaves about 4% of traffic for whatever is behind them.',
why: 'A hit is answered immediately; a miss costs a full trip to whatever is behind it. For one cache, at 90% the database sees a tenth of the traffic. By default each cache rolls that chance independently, so stacking two 80% caches leaves about 4% of traffic for whatever is behind them. Turn on remembering keys and it holds real keys instead: the second cache then only sees what the first could not keep, and hits far less.',
category: 'component',
intro: {
what: 'Fast memory that keeps recent answers so they do not have to be worked out again.',
Expand All @@ -473,7 +473,7 @@ export const GLOSSARY: GlossaryEntry[] = [
id: 'hit-rate',
term: 'Hit rate',
short: 'The share of requests a cache can answer by itself',
why: 'Small changes here have outsized effects. Going from 90% to 80% hit rate on one cache does not add 10% more database load: it doubles it. Each hop rolls independently, so chaining caches multiplies miss chances rather than sharing what the first one missed.',
why: 'Small changes here have outsized effects. Going from 90% to 80% hit rate on one cache does not add 10% more database load: it doubles it. With the hit rate set, each hop rolls independently, so chaining caches multiplies miss chances. A cache that remembers its keys measures its hit rate instead: it hits more when a few keys are hot and less when traffic is spread evenly.',
category: 'component',
aliases: ['cache hit'],
see: ['cache', 'cdn'],
Expand Down Expand Up @@ -623,7 +623,16 @@ export const GLOSSARY: GlossaryEntry[] = [
why: 'Real traffic looks like this: a few popular users, products or videos, and many rare ones. The average load can look fine while whatever owns the top key is full. This simulator has only 64 keys, so its tail is much shorter than a real one with millions.',
category: 'component',
aliases: ['zipf', 'skew', 'key skew', 'key spread', 'power law', 'popular keys'],
see: ['hot-key', 'shard'],
see: ['hot-key', 'shard', 'ttl'],
},
{
id: 'ttl',
term: 'TTL',
short: 'How long a cached answer is kept before it is fetched again',
why: 'A short TTL keeps answers fresh but sends more reads to the store. When a hot key expires, every reader that misses it goes to the store at the same moment, and a cache that restarts empty does the same for every key at once. That rush is called a cache stampede.',
category: 'component',
aliases: ['time to live', 'expiry', 'cache stampede', 'stampede', 'cold cache'],
see: ['cache', 'hit-rate'],
},
{
id: 'read-replica',
Expand Down
13 changes: 8 additions & 5 deletions src/content/glossary.wiring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,20 @@ describe('glossary wiring', () => {
});

it('states independent hit-rate rolls on the cache and CDN inspector copy', () => {
// Issue #31: the engine is a per-hop coin flip. The inspector blurbs
// and the hit-rate hint have to say so, or stacking caches reads as a
// hierarchy the numbers do not model.
// Issue #31: with a set hit rate the engine is a per-hop coin flip. The
// inspector blurbs and the hit-rate hint have to say so, or stacking
// caches reads as a hierarchy that model does not have.
const inspector = Object.entries(SOURCES).find(([path]) =>
path.endsWith('/Inspector.tsx'),
)?.[1];
expect(inspector, 'Inspector.tsx not in the glob').toBeTruthy();
expect(inspector).toMatch(
/Each cache rolls its own hit chance, independently of the others/,
/With a set hit rate, each cache rolls its own chance, so stacking them multiplies misses/,
);
// And it points at the model that does treat a later cache as a filter.
expect(inspector).toMatch(
/a later cache only sees what the earlier one could not keep/,
);
expect(inspector).toMatch(/treating later caches as filters on earlier misses/);
expect(inspector).toMatch(/rolled independently of every other cache on the path/);
expect(inspector).toMatch(/Each cache or CDN rolls this chance on its own/);
expect(inspector).toMatch(
Expand Down
2 changes: 2 additions & 0 deletions src/share/wire.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ describe('protocol tables', () => {
burstSize: true,
herdSize: true,
herdSpreadMs: true,
cacheKeys: true,
cacheTtlMs: true,
};
for (const field of Object.keys(every)) expect(WIRE_FIELDS).toContain(field);
});
Expand Down
18 changes: 16 additions & 2 deletions src/share/wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ const FIELDS = [
'burstSize',
'herdSize',
'herdSpreadMs',
'cacheKeys',
'cacheTtlMs',
] as const satisfies readonly ConfigField[];

/** Every field the wire can carry; exported so a test can prove it is complete. */
Expand Down Expand Up @@ -295,7 +297,13 @@ const SCHEMA: Record<NodeKind, readonly ConfigField[]> = {
],
lb: [...COMMON, ...CORRECTNESS],
service: [...COMMON, ...CORRECTNESS],
cache: ['hitRate', ...COMMON.filter((f) => f !== 'hitRate'), ...CORRECTNESS],
cache: [
'hitRate',
...COMMON.filter((f) => f !== 'hitRate'),
...CORRECTNESS,
'cacheKeys',
'cacheTtlMs',
],
db: ['readFraction', 'lockMs', ...COMMON, ...CORRECTNESS, 'flushEveryMs'],
queue: COMMON,
worker: [...COMMON, ...CORRECTNESS],
Expand All @@ -309,7 +317,13 @@ const SCHEMA: Record<NodeKind, readonly ConfigField[]> = {
...COMMON,
],
region: ['regions', 'activeRegion', 'failoverMs', ...COMMON, ...CORRECTNESS],
cdn: ['hitRate', ...COMMON.filter((f) => f !== 'hitRate'), ...CORRECTNESS],
cdn: [
'hitRate',
...COMMON.filter((f) => f !== 'hitRate'),
...CORRECTNESS,
'cacheKeys',
'cacheTtlMs',
],
ratelimiter: ['rateLimitRps', 'burst', ...COMMON, ...CORRECTNESS],
breaker: [
'errorThreshold',
Expand Down
Loading
Loading