fix(usage): honor 429 Retry-After to stop self-sustaining rate-limit loop

The Claude usage poller retried /api/oauth/usage every 60s, but the endpoint
returns 429 with a longer Retry-After window (~93s). Retrying mid-cooldown
re-tripped the limit so the 429s never cleared and usage data never populated.

Record a cooldownUntil from the 429 Retry-After header (5min fallback when
absent) and skip the API until it closes; cleared on success. Dashboard now
shows a "429" indicator instead of a stale value when rate-limited.

Adds regression tests proving the cooldown outlasts the 60s throttle and
releases once the window passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-06-20 20:55:35 +09:00
parent f9b1e74838
commit 2be6c8db8d
5 changed files with 304 additions and 30 deletions

View File

@@ -55,6 +55,30 @@ interface UsageCacheEntry {
fetchedAt: number;
/** Timestamp of last API *attempt* including failures (use for throttling). */
lastAttemptAt?: number;
/**
* HTTP status of the most recent *failed* attempt (e.g. 429), cleared on a
* successful fetch. Used so the dashboard can render a live error indicator
* instead of a stale value.
*/
lastErrorStatus?: number;
/**
* Epoch-ms before which we MUST NOT retry, derived from a 429 `Retry-After`
* header (or a default backoff when the header is absent). Cleared on a
* successful fetch. Without this we re-poll every MIN_FETCH_INTERVAL_MS (60s)
* even though the endpoint's rate-limit window is longer (~90s+), so the
* cooldown never clears and the 429s become self-sustaining.
*/
cooldownUntil?: number;
}
/**
* Outcome of a usage fetch. `rateLimited` is true when the most recent attempt
* hit a 429 — callers use it to surface an error in the UI rather than the
* last cached value.
*/
export interface UsageFetchResult {
usage: ClaudeUsageData | null;
rateLimited: boolean;
}
let usageDiskCache: Record<string, UsageCacheEntry> = {};
@@ -117,11 +141,35 @@ export function getUsageCacheReadKeys(
// resolution — at worst the gate fires ~60s after a window crosses 95%.
const MIN_FETCH_INTERVAL_MS = 60_000;
// Small margin added on top of a server-provided Retry-After so we wait until
// just *after* the cooldown window closes rather than racing its edge.
const RATE_LIMIT_MARGIN_MS = 5_000;
// Fallback cooldown when a 429 carries no usable Retry-After header.
const DEFAULT_RATE_LIMIT_COOLDOWN_MS = 5 * 60_000;
/**
* Parse an HTTP `Retry-After` header into milliseconds from now.
* Accepts either a delta-seconds integer ("93") or an HTTP-date.
* Returns null when the header is missing or unparseable.
*/
export function parseRetryAfterMs(header: string | null): number | null {
if (!header) return null;
const trimmed = header.trim();
if (/^\d+$/.test(trimmed)) {
return Number(trimmed) * 1000;
}
const dateMs = Date.parse(trimmed);
if (Number.isFinite(dateMs)) {
return Math.max(0, dateMs - Date.now());
}
return null;
}
async function fetchUsageForToken(
token: string,
accountIndex?: number,
refreshAttempted = false,
): Promise<ClaudeUsageData | null> {
): Promise<UsageFetchResult> {
loadUsageDiskCache();
// Return cached data if attempted recently (avoid API rate-limit)
@@ -150,13 +198,51 @@ async function fetchUsageForToken(
cached = usageDiskCache[writeKey];
saveUsageDiskCache();
}
/**
* Record this attempt's timestamp (and error status) at the write key,
* creating the entry if it does not exist yet. Recording even when there is
* no prior cached usage is what makes the MIN_FETCH_INTERVAL_MS throttle
* apply to *failures* too — without it an empty cache means every dashboard
* refresh hits the API, which itself sustains the very 429s we then report.
*/
const recordAttempt = (errorStatus?: number, cooldownUntil?: number): void => {
const now = Date.now();
const entry: UsageCacheEntry = usageDiskCache[writeKey] ?? {
usage: {},
fetchedAt: 0,
};
entry.lastAttemptAt = now;
entry.lastErrorStatus = errorStatus;
entry.cooldownUntil = cooldownUntil;
usageDiskCache[writeKey] = entry;
saveUsageDiskCache();
};
// Honour an active rate-limit cooldown from a prior 429's Retry-After. This
// is what actually breaks the self-sustaining 429 loop: the endpoint hands
// back a ~90s+ window, so retrying on the 60s MIN_FETCH_INTERVAL would keep
// hitting it mid-cooldown and never recover.
if (
!refreshAttempted &&
cached?.cooldownUntil &&
Date.now() < cached.cooldownUntil
) {
return { usage: null, rateLimited: true };
}
const lastAttempt = cached?.lastAttemptAt ?? cached?.fetchedAt ?? 0;
if (
!refreshAttempted &&
cached &&
Date.now() - lastAttempt < MIN_FETCH_INTERVAL_MS
) {
return cached.usage;
// Within the throttle window: replay the last outcome without an API call.
// On a 429 we report rateLimited and DO NOT serve the stale value.
if (cached.lastErrorStatus === 429) {
return { usage: null, rateLimited: true };
}
return { usage: cached.usage ?? null, rateLimited: false };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
@@ -208,29 +294,30 @@ async function fetchUsageForToken(
? 'Claude usage API: token expired or invalid (401)'
: 'Claude usage API: forbidden — token missing required scope (403)',
);
if (cached) {
cached.lastAttemptAt = Date.now();
saveUsageDiskCache();
}
return cached?.usage ?? null;
recordAttempt(res.status);
return { usage: cached?.usage ?? null, rateLimited: false };
}
if (res.status === 429) {
const staleMs = cached ? Date.now() - cached.fetchedAt : 0;
const retryAfterMs = parseRetryAfterMs(res.headers.get('retry-after'));
const cooldownMs = retryAfterMs ?? DEFAULT_RATE_LIMIT_COOLDOWN_MS;
const cooldownUntil = Date.now() + cooldownMs + RATE_LIMIT_MARGIN_MS;
logger.warn(
{
account: accountIndex != null ? accountIndex + 1 : '?',
tokenKey: legacyTokenCacheKey(token),
cacheKey: writeKey,
staleMinutes: Math.round(staleMs / 60_000),
retryAfterSec: retryAfterMs != null ? Math.round(retryAfterMs / 1000) : null,
cooldownSec: Math.round(cooldownMs / 1000),
},
'Claude usage API: rate limited (429), returning cached data',
'Claude usage API: rate limited (429)',
);
// Record attempt time so we don't retry for MIN_FETCH_INTERVAL_MS
if (cached) {
cached.lastAttemptAt = Date.now();
saveUsageDiskCache();
}
return cached?.usage ?? null;
// Back off until the server-provided Retry-After window closes (plus a
// margin) so we stop re-tripping the limit. Surfaces a 429 indicator and
// does NOT serve the stale value.
recordAttempt(429, cooldownUntil);
return { usage: null, rateLimited: true };
}
if (!res.ok) {
logger.warn(
@@ -242,11 +329,8 @@ async function fetchUsageForToken(
},
`Claude usage API: unexpected status ${res.status}`,
);
if (cached) {
cached.lastAttemptAt = Date.now();
saveUsageDiskCache();
}
return cached?.usage ?? null;
recordAttempt(res.status);
return { usage: cached?.usage ?? null, rateLimited: false };
}
const data = (await res.json()) as UsageApiResponse;
@@ -258,12 +342,14 @@ async function fetchUsageForToken(
seven_day_opus: mapWindow(data.seven_day_opus),
};
// Persist to disk cache — success: update both fetchedAt and lastAttemptAt
// Persist to disk cache — success: update fetchedAt + lastAttemptAt and
// clear any prior error status.
const now = Date.now();
usageDiskCache[writeKey] = {
usage: result,
fetchedAt: now,
lastAttemptAt: now,
lastErrorStatus: undefined,
};
saveUsageDiskCache();
@@ -278,7 +364,7 @@ async function fetchUsageForToken(
'Claude usage API: fetched successfully',
);
return result;
return { usage: result, rateLimited: false };
} catch (err) {
if ((err as Error).name === 'AbortError') {
logger.warn(
@@ -301,11 +387,8 @@ async function fetchUsageForToken(
);
}
// Record attempt time so we back off on persistent failures
if (cached) {
cached.lastAttemptAt = Date.now();
saveUsageDiskCache();
}
return cached?.usage ?? null;
recordAttempt();
return { usage: cached?.usage ?? null, rateLimited: false };
} finally {
clearTimeout(timer);
}
@@ -329,7 +412,7 @@ export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
logger.debug('No Claude OAuth token available for usage check');
return null;
}
return fetchUsageForToken(token, undefined);
return (await fetchUsageForToken(token, undefined)).usage;
}
export interface ClaudeAccountProfile {
@@ -471,6 +554,11 @@ export interface ClaudeAccountUsage {
isActive: boolean;
isRateLimited: boolean;
usage: ClaudeUsageData | null;
/**
* True when the most recent usage-API attempt for this account hit a 429.
* The dashboard renders a "429" indicator instead of a stale value.
*/
usageRateLimited?: boolean;
}
/**
@@ -484,7 +572,7 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
const credsToken = readCredentialsAccessToken(0);
const token = credsToken || getConfiguredClaudeTokens()[0];
if (!token) return [];
const usage = await fetchUsageForToken(token, 0);
const { usage, rateLimited } = await fetchUsageForToken(token, 0);
return [
{
index: 0,
@@ -492,6 +580,7 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
isActive: true,
isRateLimited: false,
usage,
usageRateLimited: rateLimited,
},
];
}
@@ -505,13 +594,17 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
// by token-refresh.ts, so it always carries the full scope set.
const credsToken = readCredentialsAccessToken(t.index);
const tokenForFetch = credsToken || t.token;
const usage = await fetchUsageForToken(tokenForFetch, t.index);
const { usage, rateLimited } = await fetchUsageForToken(
tokenForFetch,
t.index,
);
results.push({
index: t.index,
masked: t.masked,
isActive: t.isActive,
isRateLimited: t.isRateLimited,
usage,
usageRateLimited: rateLimited,
});
}
return results;