Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(batch): global rate-limit header cache with 60s TTL + 24h retry window (#2299)

diegosouzapwc9c6c6321670
diff --git a/open-sse/services/batchProcessor.ts b/open-sse/services/batchProcessor.ts
index c18bd1dbe2..2f13bdb77e 100644
--- a/open-sse/services/batchProcessor.ts
+++ b/open-sse/services/batchProcessor.ts
@@ -293,17 +293,22 @@ async function startBatch(batch: any): Promise<void> {
}
}
+let prevHeaders: Headers | null = null;
+let prevHeadersTimestamp: number = 0;
+const HEADERS_CACHE_TTL_MS = 60_000;
+
async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]): Promise<void> {
const state = createBatchState(batch);
const apiKey = await resolveApiKey(batch);
- let prevHeaders: Headers | null = null;
for (const item of items) {
if (isBatchCancelled(batch.id)) break;
- if (prevHeaders) {
- const delay = maybeThrottle(prevHeaders);
+ const cachedHeaders =
+ prevHeaders && Date.now() - prevHeadersTimestamp < HEADERS_CACHE_TTL_MS ? prevHeaders : null;
+ if (cachedHeaders) {
+ const delay = maybeThrottle(cachedHeaders);
if (delay) {
await sleep(delay);
}
@@ -333,10 +338,12 @@ async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]):
state.results.push(wrapped);
applyItemResult(state, response.status, responseBody);
prevHeaders = response.headers;
+ prevHeadersTimestamp = Date.now();
} catch (exception) {
// Track processing-level errors separately (items that failed to be processed)
state.errors.push({ custom_id: item.customId ?? null, error: String(exception) });
prevHeaders = null;
+ prevHeadersTimestamp = 0;
}
maybePersistProgress(batch.id, state);
@@ -357,8 +364,12 @@ async function resolveApiKey(batch: BatchRecord): Promise<any> {
}
async function processSingleItemWithRetry(item: BatchRequestItem, apiKey: string) {
+ // Time-based retry limit: individual batch items can retry for up to 24 hours.
+ // This accommodates large batches against heavily rate-limited providers.
// TODO: expose as configurable parameter
- const maxRetries = 10;
+ const MAX_RETRY_DURATION_MS = 24 * 60 * 60 * 1_000; // 24h
+ const maxRetries = 200; // safety ceiling — time limit should kick in first
+ const retryStartedAt = Date.now();
let response: Response = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
@@ -376,6 +387,13 @@ async function processSingleItemWithRetry(item: BatchRequestItem, apiKey: string
(response.status === 429 || response.status === 502 || response.status === 504) &&
attempt < maxRetries
) {
+ // Bail if we've been retrying for longer than the allowed window
+ if (Date.now() - retryStartedAt >= MAX_RETRY_DURATION_MS) {
+ console.warn(
+ `[BATCH] Item ${item.customId ?? "(no id)"} exceeded 24h retry window after ${attempt} attempts — giving up`
+ );
+ return response;
+ }
const delay = getRetryDelayMs(response.headers) ?? getBackoffDelayMs(attempt);
await sleep(delay);
continue;
@@ -413,8 +431,8 @@ export function buildRequestBody(item: BatchRequestItem) {
function getBackoffDelayMs(attempt: number) {
// TODO: expose in config
- let baseMs = 500;
- let maxMs = 30_000;
+ const baseMs = 5_000;
+ const maxMs = 3_600_000;
// exponential: 2^attempt * base
const exp = Math.min(maxMs, baseMs * 2 ** attempt);
@@ -775,3 +793,12 @@ function failBatch(batchId: string, reason: string): void {
export async function waitForAllBatches(): Promise<void> {
await Promise.all(Array.from(activeProcesses));
}
+
+// Test helpers
+export function getCachedHeaders(): { headers: Headers | null; timestamp: number } {
+ return { headers: prevHeaders, timestamp: prevHeadersTimestamp };
+}
+export function resetCachedHeaders(): void {
+ prevHeaders = null;
+ prevHeadersTimestamp = 0;
+}
diff --git a/tests/unit/batch-processor.test.ts b/tests/unit/batch-processor.test.ts
index 40949bb9ec..997fe7e6fb 100644
--- a/tests/unit/batch-processor.test.ts
+++ b/tests/unit/batch-processor.test.ts
@@ -15,7 +15,7 @@ const core = await import("@/lib/db/core.ts");
const localDb = await import("@/lib/localDb");
const { dispatch } = await import("@/lib/batches/dispatch");
const batchProcessor = await import("../../open-sse/services/batchProcessor.ts");
-const { waitForAllBatches } = batchProcessor;
+const { waitForAllBatches, getCachedHeaders, resetCachedHeaders } = batchProcessor;
const ORIGINAL_OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY;
const ORIGINAL_ROUTER_API_KEY = process.env.ROUTER_API_KEY;
@@ -41,6 +41,8 @@ async function reset() {
delete process.env.OMNIROUTE_API_KEY;
delete process.env.ROUTER_API_KEY;
+
+ resetCachedHeaders();
}
test.beforeEach(async () => {
@@ -226,3 +228,93 @@ test("processPendingBatches should fail a batch with mismatched endpoint", async
assert.ok(updatedBatch?.errors?.length === 1);
assert.ok(updatedBatch?.errors![0].message.includes("does not match batch endpoint"));
});
+
+test("processPendingBatches caches rate-limit headers across sequential batches", async () => {
+ // Helper to create a 1-item batch with a given id prefix
+ async function createOneItemBatch(prefix: string) {
+ const content =
+ JSON.stringify({
+ custom_id: `${prefix}-req`,
+ method: "POST",
+ url: "/v1/chat/completions",
+ body: { model: "gpt-4", messages: [{ role: "user", content: prefix }] },
+ }) + "\n";
+
+ const file = await localDb.createFile({
+ bytes: Buffer.byteLength(content),
+ filename: `${prefix}_input.jsonl`,
+ purpose: "batch_input",
+ content: Buffer.from(content),
+ });
+
+ const batch = await localDb.createBatch({
+ endpoint: "/v1/chat/completions",
+ status: "validating",
+ inputFileId: file.id,
+ completionWindow: "24h",
+ });
+ return batch;
+ }
+
+ // Initial cache state
+ const initial = getCachedHeaders();
+ assert.strictEqual(initial.headers, null);
+ assert.strictEqual(initial.timestamp, 0);
+
+ // Create first batch
+ const batchA = await createOneItemBatch("cache-test-a");
+
+ // Mock to return rate-limit headers (triggers cache)
+ let callCount = 0;
+ mock.method(dispatch, "dispatchBatchApiRequest", async () => {
+ callCount++;
+ return new Response(
+ JSON.stringify({
+ id: "chatcmpl-cache-a",
+ choices: [{ message: { content: "from a" } }],
+ usage: { prompt_tokens: 10, completion_tokens: 5 },
+ }),
+ {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ "x-ratelimit-remaining-req-minute": "5",
+ "x-ratelimit-limit-req-minute": "100",
+ "x-ratelimit-remaining-tokens-minute": "5000",
+ "x-ratelimit-tokens-query-cost": "50",
+ },
+ }
+ );
+ });
+
+ await batchProcessor.processPendingBatches();
+
+ // Wait for batch A to complete
+ const waitForStatusA = async () => {
+ for (let i = 0; i < 40; i++) {
+ const b = await localDb.getBatch(batchA.id);
+ if (b?.status === "completed" || b?.status === "failed") return b;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ throw new Error(`Batch A did not finish within timeout`);
+ };
+ const resultA = await waitForStatusA();
+ assert.strictEqual(resultA?.status, "completed");
+ assert.ok(callCount >= 1, "dispatch should have been called at least once");
+
+ // After batch A, cache should be populated
+ const afterA = getCachedHeaders();
+ assert.notStrictEqual(afterA.headers, null, "headers should be cached after first batch");
+ assert.strictEqual(
+ afterA.headers!.get("x-ratelimit-remaining-req-minute"),
+ "5",
+ "cached header value should match response"
+ );
+ assert.ok(Date.now() - afterA.timestamp < 60_000, "cached timestamp should be within TTL");
+
+ // Verify cache survives a resetCachedHeaders call
+ resetCachedHeaders();
+ const afterReset = getCachedHeaders();
+ assert.strictEqual(afterReset.headers, null, "reset should clear cached headers");
+ assert.strictEqual(afterReset.timestamp, 0, "reset should clear cached timestamp");
+});