Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(router): escalating cooldown for repeated 429s (credits @meliani) (#92)

Tashfeendd46dafea3a0
diff --git a/README.md b/README.md
index f7ce1ff9..e23c9dcb 100644
--- a/README.md
+++ b/README.md
@@ -306,6 +306,8 @@ PRs should include a test, keep the existing test suite green, and match the `.e
<a href="https://github.com/danscMax"><img src="https://images.weserv.nl/?url=github.com/danscMax.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@danscMax" /></a>
<a href="https://github.com/jhash"><img src="https://images.weserv.nl/?url=github.com/jhash.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@jhash" /></a>
<a href="https://github.com/JammyJames1234"><img src="https://images.weserv.nl/?url=github.com/JammyJames1234.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@JammyJames1234" /></a>
+<a href="https://github.com/Sumit4codes"><img src="https://images.weserv.nl/?url=github.com/Sumit4codes.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@Sumit4codes" /></a>
+<a href="https://github.com/meliani"><img src="https://images.weserv.nl/?url=github.com/meliani.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@meliani" /></a>
## Terms of Service review
diff --git a/server/src/__tests__/services/ratelimit.test.ts b/server/src/__tests__/services/ratelimit.test.ts
index 85062e36..e2f51ce8 100644
--- a/server/src/__tests__/services/ratelimit.test.ts
+++ b/server/src/__tests__/services/ratelimit.test.ts
@@ -6,6 +6,7 @@ import {
recordRequest,
recordTokens,
getRateLimitStatus,
+ getNextCooldownDuration,
} from '../../services/ratelimit.js';
function removeDbFile(dbPath: string) {
@@ -89,6 +90,31 @@ describe('Rate Limiter', () => {
});
});
+ describe('escalating cooldown', () => {
+ it('escalates the 2nd/3rd/4th hit within 24h to 10m / 1h / 24h', () => {
+ const id = Math.floor(Math.random() * 1_000_000);
+ const args = ['cerebras', `escalating-model-${id}`, id] as const;
+ // 1st: 2 minutes
+ expect(getNextCooldownDuration(...args)).toBe(2 * 60 * 1000);
+ // 2nd: 10 minutes
+ expect(getNextCooldownDuration(...args)).toBe(10 * 60 * 1000);
+ // 3rd: 1 hour
+ expect(getNextCooldownDuration(...args)).toBe(60 * 60 * 1000);
+ // 4th: 24 hours
+ expect(getNextCooldownDuration(...args)).toBe(24 * 60 * 60 * 1000);
+ // 5th+ stays at 24h (quarantined until next quota window)
+ expect(getNextCooldownDuration(...args)).toBe(24 * 60 * 60 * 1000);
+ });
+
+ it('counts independently per (platform, model, key)', () => {
+ const id = Math.floor(Math.random() * 1_000_000);
+ // Different keys for the same model should each start at 2m, not share state.
+ expect(getNextCooldownDuration('groq', `m-${id}`, id)).toBe(2 * 60 * 1000);
+ expect(getNextCooldownDuration('groq', `m-${id}`, id + 1)).toBe(2 * 60 * 1000);
+ expect(getNextCooldownDuration('groq', `m-${id}-other`, id)).toBe(2 * 60 * 1000);
+ });
+ });
+
describe('persistent state', () => {
it('preserves per-key usage and cooldowns after the limiter module reloads', async () => {
process.env.ENCRYPTION_KEY = '0'.repeat(64);
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index 892247fd..884d05d9 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -4,7 +4,7 @@ import type { Request, Response } from 'express';
import { z } from 'zod';
import type { ChatMessage } from '@freellmapi/shared/types.js';
import { routeRequest, recordRateLimitHit, recordSuccess, type RouteResult } from '../services/router.js';
-import { recordRequest, recordTokens, setCooldown } from '../services/ratelimit.js';
+import { recordRequest, recordTokens, setCooldown, getNextCooldownDuration } from '../services/ratelimit.js';
import { getDb, getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
@@ -441,7 +441,12 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// Put this model+key on cooldown and try the next one
const skipId = `${route.platform}:${route.modelId}:${route.keyId}`;
skipKeys.add(skipId);
- setCooldown(route.platform, route.modelId, route.keyId, 120_000);
+ setCooldown(
+ route.platform,
+ route.modelId,
+ route.keyId,
+ getNextCooldownDuration(route.platform, route.modelId, route.keyId),
+ );
recordRateLimitHit(route.modelDbId);
lastError = err;
console.log(`[Proxy] ${err.message.slice(0, 60)} from ${route.displayName}, falling back (attempt ${attempt + 1}/${MAX_RETRIES})`);
diff --git a/server/src/services/ratelimit.ts b/server/src/services/ratelimit.ts
index 0a8d9a4c..3f342ae4 100644
--- a/server/src/services/ratelimit.ts
+++ b/server/src/services/ratelimit.ts
@@ -208,6 +208,31 @@ export function recordTokens(
// Cooldown: when a provider returns 429, block that model+key for a period
const cooldowns = new Map<string, number>(); // key -> expiry timestamp
+// Escalating cooldown: track hits per key over a rolling 24h window so a
+// daily-quota exhaustion (OpenRouter free: 50/day, Cohere free: 33/day, etc.)
+// quarantines the key for the rest of the day instead of looping through
+// the 2-minute cooldown 20 times per request and consuming every fallback slot.
+// In-memory only — state resets on restart, which is fine (a clean restart
+// will re-escalate on the next 429 if the quota is genuinely exhausted).
+const cooldownHits = new Map<string, number[]>(); // key -> timestamps of recent cooldown set events
+const HOUR = 60 * MINUTE;
+const COOLDOWN_DURATIONS = [
+ 2 * MINUTE, // 1st hit in 24h
+ 10 * MINUTE, // 2nd
+ HOUR, // 3rd
+ DAY, // 4th and beyond
+];
+
+export function getNextCooldownDuration(platform: string, modelId: string, keyId: number): number {
+ const key = `${platform}:${modelId}:${keyId}`;
+ const now = Date.now();
+ const hits = (cooldownHits.get(key) ?? []).filter(t => t > now - DAY);
+ hits.push(now);
+ cooldownHits.set(key, hits);
+ const idx = Math.min(hits.length - 1, COOLDOWN_DURATIONS.length - 1);
+ return COOLDOWN_DURATIONS[idx]!;
+}
+
function persistedCooldownExpiry(
platform: string,
modelId: string,