Notes

Preventing Prompt Loop Quota Exhaustion with 402 HTTP Circuit Breakers

Cloud Billing, Gemini API, Tokenomics

When a Google Cloud Spend Cap fuses, new API calls return a quota error. If your agent does not catch this explicitly, it can crash mid-execution and leave database state partially mutated.

Always wrap Gemini API calls in a circuit breaker that intercepts quota errors and returns a structured HTTP 402 Payment Required to the calling agent, allowing the client to safely checkpoint its progress.

circuitBreaker.ts
export async function callWithSpendCapGuard(apiCall) {
  try {
    return await apiCall();
  } catch (err) {
    if (err.status === 429 || err.code === "RESOURCE_EXHAUSTED") {
      const error = new Error("Spend cap reached or quota exhausted. Safe checkpoint created.");
      error.statusCode = 402;
      error.isFatalQuota = true;
      throw error;
    }
    throw err;
  }
}

All 7 notes