perf(metering): read the global usage total as one paced listing (#4772)
Backend Tests / changes (push) Waiting to run
Benchmarks / changes (push) Waiting to run
Notify HeyPuter / notify (push) Waiting to run

getGlobalUsage got every shard of a month by key, 10,000 keys in batches
of 100 with several in flight. It now lists the shards by prefix, a page
at a time, and waits between pages so the read stays under a fixed
number of read units per second.

getGlobalUsageByMonth returns every month from the same listing, for a
caller that shows more than one.
This commit is contained in:
Daniel Salazar authored and GitHub committed 2026-11-24 22:25:30 -07:00
1 parent a53319baac
commit 5e5ad4953a
3 files changed
+110 -27

No files matched your search

@@ -20,7 +20,9 @@
import { describe, expect, it, vi } from 'vitest';
import { MeteringService } from './MeteringService.ts';
const GLOBAL_SHARD_COUNT = MeteringService.GLOBAL_SHARD_COUNT;
const SHARDS = 8;
const PER_SHARD = 1000;
const MONTH = new Date().toISOString().slice(0, 7);
/** `checkRateOfChange` is private; call it through this narrowed view. */
type RateCheckable = { checkRateOfChange(): Promise<void> };
@@ -30,15 +32,24 @@ const makeService = (
baseline: unknown,
): {
svc: RateCheckable;
kv: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
kv: {
get: ReturnType<typeof vi.fn>;
list: ReturnType<typeof vi.fn>;
set: ReturnType<typeof vi.fn>;
};
alarmCreate: ReturnType<typeof vi.fn>;
} => {
const kv = {
get: vi.fn(async ({ key }: { key: string | string[] }) =>
Array.isArray(key)
? { res: key.map(() => ({ total: 1 })) }
: { res: baseline },
),
get: vi.fn(async () => ({ res: baseline })),
list: vi.fn(async () => ({
res: {
items: Array.from({ length: SHARDS }, (_, shard) => ({
key: `metering:v2:puter:${shard}:${MONTH}`,
value: { total: PER_SHARD },
})),
},
usage: { read: 0, write: 0, cachedRead: 0 },
})),
set: vi.fn(async () => ({ res: true })),
};
const alarmCreate = vi.fn();
@@ -62,6 +73,7 @@ describe('MeteringService.checkRateOfChange', () => {
await svc.checkRateOfChange();
expect(kv.get).not.toHaveBeenCalled();
expect(kv.list).not.toHaveBeenCalled();
expect(kv.set).not.toHaveBeenCalled();
expect(alarmCreate).not.toHaveBeenCalled();
},
@@ -75,17 +87,16 @@ describe('MeteringService.checkRateOfChange', () => {
await svc.checkRateOfChange();
expect(kv.get).toHaveBeenCalledTimes(2);
expect(kv.get).toHaveBeenCalledTimes(1);
expect(kv.get.mock.calls[0][0].key).toBe(
'metering:lastGlobalUsageCheck',
);
const secondKey = kv.get.mock.calls[1][0].key;
expect(Array.isArray(secondKey)).toBe(true);
expect(secondKey).toHaveLength(GLOBAL_SHARD_COUNT);
expect(kv.list).toHaveBeenCalledTimes(1);
expect(kv.list.mock.calls[0][0].keyPrefix).toBe('metering:v2:puter:');
expect(kv.set).toHaveBeenCalledTimes(1);
const setArg = kv.set.mock.calls[0][0];
expect(setArg.value.total).toBe(GLOBAL_SHARD_COUNT);
expect(setArg.value.total).toBe(SHARDS * PER_SHARD);
expect(typeof setArg.value.timestamp).toBe('number');
expect(alarmCreate).not.toHaveBeenCalled();
@@ -134,6 +145,7 @@ describe('MeteringService.checkRateOfChange', () => {
await svc.checkRateOfChange();
expect(kv.get).toHaveBeenCalledTimes(1);
expect(kv.list).not.toHaveBeenCalled();
expect(kv.set).not.toHaveBeenCalled();
expect(alarmCreate).not.toHaveBeenCalled();
});
@@ -6,6 +6,7 @@ import {
describe,
expect,
it,
onTestFinished,
vi,
} from 'vitest';
import murmurhash from 'murmurhash';
@@ -3477,6 +3478,38 @@ describe('MeteringService', () => {
expect((await target.getGlobalUsage('1999-02')).total).toBe(0);
});
it('sums every month in one listing, across pages', async () => {
const ctor = target.constructor as typeof MeteringService;
const pageItems = ctor.SHARD_SWEEP_PAGE_ITEMS;
ctor.SHARD_SWEEP_PAGE_ITEMS = 3;
onTestFinished(() => {
ctor.SHARD_SWEEP_PAGE_ITEMS = pageItems;
});
const months = ['1998-01', '1998-02', '1998-03'];
for (const [i, month] of months.entries()) {
for (let shard = 0; shard < ctor.GLOBAL_SHARD_COUNT; shard++) {
await server.stores.kv.set({
key: `${METRICS_V2_PREFIX}:puter:${shard}:${month}`,
value: { total: 10 ** i },
});
}
}
// Under the prefix, but not a shard.
await server.stores.kv.set({
key: `${METRICS_V2_PREFIX}:puter:notes:1998-01`,
value: { total: 5000 },
});
const list = vi.spyOn(server.stores.kv, 'list');
const totals = await target.getGlobalUsageByMonth();
expect(months.map((month) => totals.get(month))).toEqual(
[1, 10, 100].map((each) => each * ctor.GLOBAL_SHARD_COUNT),
);
expect(list.mock.calls.length).toBeGreaterThan(1);
list.mockRestore();
});
it('returns total only, with no per-model breakdown', async () => {
const user1: Actor = { user: makeUser() };
await target.incrementUsage(user1, 'kv:read', 1, 100);
@@ -18,6 +18,7 @@
*/
import { randomInt } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import murmurhash from 'murmurhash';
import type { Actor } from '../../core/actor';
import { isSystemActor } from '../../core/actor';
@@ -116,6 +117,15 @@ type UsageWriteResult = {
detail: Promise<FlatUsageDetail>;
};
/** Every month's global shard sits under this, as `<shard>:<YYYY-MM>`. */
const GLOBAL_USAGE_PREFIX = `${METRICS_V2_PREFIX}:puter:`;
const GLOBAL_SHARD_KEY_RE = /^\d+:(\d{4}-\d{2})$/;
/**
* Read units a sweep of the global shards draws per second. Their partition
* serves 3,000 and every request's metering reads share it.
*/
const SHARD_SWEEP_READ_UNITS_PER_SECOND = 1000;
/** Compares fleet-wide spend against `maxGlobalUsagePerMinute`. */
const GLOBAL_RATE_CHECK_JOB = 'metering.globalRateCheck';
const GLOBAL_RATE_CHECK_EVERY_MS = 25 * 60 * 1000;
@@ -183,6 +193,8 @@ export class MeteringService extends PuterService {
*/
static GLOBAL_SHARD_COUNT = 10000;
static APP_SHARD_COUNT = 10000;
/** Shards one page of a sweep reads; the pause between pages is the pacing. */
static SHARD_SWEEP_PAGE_ITEMS = 1000;
/**
* Share of the allowance past which an approximate running total is no
@@ -2522,24 +2534,50 @@ export class MeteringService extends PuterService {
);
}
/**
* Summed over every global shard for `month` (default: this one) — each is
* `{ total }` only.
*/
/** The global total for `month` (default: this one). */
async getGlobalUsage(
month: string = this.monthYearString(),
): Promise<UsageByType> {
const keyPrefix = `${METRICS_V2_PREFIX}:puter:`;
const keys = Array.from(
{ length: MeteringService.GLOBAL_SHARD_COUNT },
(_, shard) => `${keyPrefix}${shard}:${month}`,
);
const totals = await this.getGlobalUsageByMonth();
return { total: totals.get(month) ?? 0 } as UsageByType;
}
const { res } = await this.stores.kv.get({ key: keys });
const usages = (res ?? []) as (UsageByType | null)[];
let total = 0;
for (const entry of usages) total += entry?.total || 0;
return { total } as UsageByType;
/**
* The global total of every month on record, by `YYYY-MM`. Shards sort by
* number before month, so one listing covers them all; it is charged by
* bytes read, where getting each shard by key is charged per key.
*/
async getGlobalUsageByMonth(): Promise<Map<string, number>> {
const totals = new Map<string, number>();
let cursor: string | undefined;
do {
const startedAt = Date.now();
const { res, usage } = await this.stores.kv.list({
as: 'entries',
keyPrefix: GLOBAL_USAGE_PREFIX,
limit: MeteringService.SHARD_SWEEP_PAGE_ITEMS,
cursor,
});
const page = res as {
items: { key: string; value: unknown }[];
cursor?: string;
};
for (const { key, value } of page.items) {
const month = GLOBAL_SHARD_KEY_RE.exec(
key.slice(GLOBAL_USAGE_PREFIX.length),
)?.[1];
if (!month) continue;
const total = Number((value as UsageByType | null)?.total);
if (Number.isFinite(total))
totals.set(month, (totals.get(month) ?? 0) + total);
}
cursor = page.cursor;
const waitMs =
(usage.read / SHARD_SWEEP_READ_UNITS_PER_SECOND) * 1000 -
(Date.now() - startedAt);
if (cursor && waitMs > 0) await sleep(waitMs);
} while (cursor);
return totals;
}
async updateAddonCredit(
@@ -2640,7 +2678,7 @@ export class MeteringService extends PuterService {
const hash =
murmurhash.v3(`${userId}:${appId}`) %
MeteringService.GLOBAL_SHARD_COUNT;
return `${METRICS_V2_PREFIX}:puter:${hash}:${currentMonth}`;
return `${GLOBAL_USAGE_PREFIX}${hash}:${currentMonth}`;
}
private appUsageKey(