When the Spend Cap Trips, Return a 402 So the Agent Can Checkpoint
When a Firebase spend cap trips, new usage of that one service pauses for the rest of the month, and your client-side app will start throwing errors for that service. Enforcement can lag by several minutes, and anything spent in that window is billed. If your agent does not catch those errors explicitly, it can crash mid-execution and leave database state partially mutated.
Always wrap Gemini API calls in a circuit breaker, but don't treat every 429 as the cap. Most are per-minute rate limits, and the docs say to retry those with exponential backoff. The docs also don't name the error code a paused service returns, so the recipe trips on persistence instead: a 402, or a 429 or 5xx that survives four retries, opens the breaker. Every later call then fails fast without reaching the API, and the calling agent gets a structured HTTP 402 Payment Required, allowing the client to safely checkpoint its progress.
// status is the HTTP status on the SDK's error, such as ApiError.status in @google/genai
export class CheckpointRequired extends Error {
readonly statusCode = 402; // Payment Required: the agent saves its progress and stops
}
const RETRIES = 4;
let breakerOpen = false; // stays open until resetBreaker() runs after the cap is lifted
export const resetBreaker = () => { breakerOpen = false; };
export async function callWithSpendCapGuard<T>(apiCall: () => Promise<T>): Promise<T> {
if (breakerOpen) throw new CheckpointRequired("Breaker open: model calls are paused. Checkpoint and stop.");
for (let attempt = 0; ; attempt++) {
try {
return await apiCall();
} catch (err) {
const status = (err as { status?: number }).status ?? 0;
if (status !== 402 && status !== 429 && status < 500) throw err; // the request itself is wrong
if (status === 402 || attempt === RETRIES) {
breakerOpen = true;
throw new CheckpointRequired(`Still failing with ${status} after ${attempt} retries. Checkpoint and stop.`);
}
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** attempt)); // 429s are usually transient
}
}
}
Get the next essay by email
One email per new essay: a production failure, taken apart, and the code that fixed it. Reply to any of them to unsubscribe.