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(ratelimit): escalate NULL-limit providers via hit-count heuristic (#392)

Jasnoor Gill8c9cf94843a4
diff --git a/server/src/__tests__/services/ratelimit.test.ts b/server/src/__tests__/services/ratelimit.test.ts
index d8f996da..13f3392d 100644
--- a/server/src/__tests__/services/ratelimit.test.ts
+++ b/server/src/__tests__/services/ratelimit.test.ts
@@ -8,6 +8,7 @@ import {
getRateLimitStatus,
getNextCooldownDuration,
getCooldownDurationForLimit,
+ recentHitCount,
canUseProvider,
providerDailyRequestCount,
getProviderDailyRequestCap,
@@ -131,14 +132,69 @@ describe('Rate Limiter', () => {
expect(getCooldownDurationForLimit(...args, { rpd: 1000, tpd: null })).toBe(90 * 1000);
});
- it('treats a null daily limit as never-exhausted (always transient)', () => {
+ it('stays transient for the first 429 with null daily limits (heuristic threshold)', () => {
const id = Math.floor(Math.random() * 1_000_000);
- for (let i = 0; i < 50; i++) recordRequest('mistral', `nolimit-${id}`, id);
+ // 1st 429 → transient (no signal yet). Subsequent 429s stay transient
+ // until the threshold is crossed.
expect(
getCooldownDurationForLimit('mistral', `nolimit-${id}`, id, { rpd: null, tpd: null }),
).toBe(90 * 1000);
});
+ it('escalates null-limit 429s through the same ladder as documented RPD exhaustion', () => {
+ // Documented RPD path (see "escalates only once the daily request limit
+ // is actually reached"): 1st call after counter ≥ limit → 2min (idx=0),
+ // 2nd → 10min (idx=1), 3rd → HOUR (idx=2), 4th+ → DAY (idx=3).
+ //
+ // Null-limit path mirrors that sequence starting at the 2nd 429 (1st
+ // is transient — no signal yet). Uses an independent counter so the
+ // ladder index isn't inflated by the heuristic's own hits.
+ const id = Math.floor(Math.random() * 1_000_000);
+ const platform = 'ollama';
+ const model = `nolimit-esc-${id}`;
+ // 1st 429 — no history → transient
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(90 * 1000);
+ // 2nd 429 — heuristic threshold (2) crossed → 2min (ladder idx=0)
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(2 * 60 * 1000);
+ // 3rd 429 → 10min (idx=1)
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(10 * 60 * 1000);
+ // 4th 429 → HOUR (idx=2)
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(60 * 60 * 1000);
+ // 5th 429 → DAY (idx=3, capped)
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(24 * 60 * 60 * 1000);
+ // 6th+ stays at DAY
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(24 * 60 * 60 * 1000);
+ });
+
+ it('does NOT trigger the heuristic when limits are known (even after 5+ hits)', () => {
+ // rpd=1000 known: counters track it, daily-exhausted check uses the
+ // counter, not the hit count. The null-limits heuristic only fires
+ // when BOTH rpd AND tpd are null. With a known cap, repeated 429s
+ // stay transient (the counter-based path takes over instead).
+ const id = Math.floor(Math.random() * 1_000_000);
+ const platform = 'openrouter';
+ const model = `known-${id}`;
+ for (let i = 0; i < 5; i++) {
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: 1000, tpd: null })).toBe(90 * 1000);
+ }
+ expect(recentHitCount(platform, model, id, Date.now())).toBe(0);
+ });
+
+ it('clears null-limit hit history after a successful request', () => {
+ const id = Math.floor(Math.random() * 1_000_000);
+ const platform = 'ollama';
+ const model = `nolimit-success-${id}`;
+
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(90 * 1000);
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(2 * 60 * 1000);
+ expect(recentHitCount(platform, model, id, Date.now())).toBe(2);
+
+ recordRequest(platform, model, id);
+
+ expect(recentHitCount(platform, model, id, Date.now())).toBe(0);
+ expect(getCooldownDurationForLimit(platform, model, id, { rpd: null, tpd: null })).toBe(90 * 1000);
+ });
+
it('escalates only once the daily request limit is actually reached', () => {
const id = Math.floor(Math.random() * 1_000_000);
const platform = 'openrouter';
diff --git a/server/src/services/ratelimit.ts b/server/src/services/ratelimit.ts
index 9eb9e5e8..1741f099 100644
--- a/server/src/services/ratelimit.ts
+++ b/server/src/services/ratelimit.ts
@@ -251,6 +251,7 @@ export function recordRequest(platform: string, modelId: string, keyId: number)
getWindow(rpdKey).timestamps.push(now);
recordUsage(platform, modelId, keyId, 'request', 0, now);
+ clearNullLimitHits(platform, modelId, keyId);
}
export function recordTokens(
@@ -316,19 +317,62 @@ export const PAYMENT_REQUIRED_COOLDOWN_MS = DAY;
// the router fail over to a model the key can actually serve. See issue #256.
export const MODEL_FORBIDDEN_COOLDOWN_MS = DAY;
+// When RPD/TPD limits are NULL (provider's published daily quota is unknown or
+// not yet seeded — common for ollama, cloudflare, nvidia, huggingface, mistral,
+// kilo, llm7, pollinations), we cannot check a counter against a cap. Fall back
+// to a hit-count heuristic: after 2+ 429s within this rolling window, treat as
+// "effectively daily-exhausted" and enter the standard escalation ladder at
+// the same step the documented-RPD path would. Without this, these providers
+// stay stuck at TRANSIENT_COOLDOWN_MS forever even when every request is a
+// 429 (observed in production: ollama 130× 429s in 1h with all 90s cooldowns
+// expired before the next request). Cheaper than waiting for the operator to
+// seed per-provider limits (Option A), still reversible — a successful call
+// clears the hit window via the normal path.
+//
+// Separate counter from `cooldownHits` (used by getNextCooldownDuration's
+// escalation ladder). The shared Map would make this state path-coupled to
+// the ladder index, which would over-skip steps because the ladder also
+// pushes a hit on each call.
+const NULL_LIMIT_HIT_THRESHOLD = 2;
+const NULL_LIMIT_HIT_WINDOW_MS = HOUR;
+const nullLimitHits = new Map<string, number[]>(); // key -> timestamps
+
+function recordNullLimitHit(platform: string, modelId: string, keyId: number, now: number): void {
+ const key = `${platform}:${modelId}:${keyId}`;
+ const hits = nullLimitHits.get(key) ?? [];
+ hits.push(now);
+ nullLimitHits.set(key, hits);
+}
+
+function clearNullLimitHits(platform: string, modelId: string, keyId: number): void {
+ nullLimitHits.delete(`${platform}:${modelId}:${keyId}`);
+}
+
+export function recentHitCount(
+ platform: string,
+ modelId: string,
+ keyId: number,
+ now: number,
+ windowMs: number = NULL_LIMIT_HIT_WINDOW_MS,
+): number {
+ const key = `${platform}:${modelId}:${keyId}`;
+ const hits = nullLimitHits.get(key) ?? [];
+ return hits.filter(t => t > now - windowMs).length;
+}
+
// Decide how long to bench a model+key after an upstream 429. Escalate to the
-// long quarantine (getNextCooldownDuration, up to 24h) ONLY when the model is
-// genuinely at its DAILY limit (RPD or TPD) — that won't recover until the
-// provider's daily reset, so a long bench avoids hammering a truly-dead key.
+// long quarantine (getNextCooldownDuration, up to 24h) when the model is at its
+// DAILY limit (RPD/TPD counter ≥ cap), OR — when limits are unknown — when
+// recentHitCount crosses the heuristic threshold. Either way, a long bench
+// avoids hammering a truly-dead key.
//
-// A transient RPM/TPM 429 gets a short fixed cooldown and does NOT count toward
-// escalation. This is the common case for providers with a tight per-minute
-// token budget but a large daily quota — e.g. groq gpt-oss-120b has rpd=1000
-// yet tpm=8000, so a single burst of large prompts 429s on TPM while the daily
-// quota is barely touched. Without this split, those transient bursts escalated
-// (2m → 10m → 1h → 24h) and quarantined a perfectly healthy provider for the
-// rest of the day. Daily counters are persisted (countPersistedRequests /
-// sumPersistedTokens), so this verdict is stable across restarts.
+// A transient RPM/TPM 429 with healthy daily counters gets a short fixed
+// cooldown and does NOT count toward escalation. This is the common case for
+// providers with a tight per-minute token budget but a large daily quota —
+// e.g. groq gpt-oss-120b has rpd=1000 yet tpm=8000, so a single burst of large
+// prompts 429s on TPM while the daily quota is barely touched. Daily counters
+// are persisted (countPersistedRequests / sumPersistedTokens), so this verdict
+// is stable across restarts.
export function getCooldownDurationForLimit(
platform: string,
modelId: string,
@@ -341,7 +385,20 @@ export function getCooldownDurationForLimit(
limits.rpd !== null && requestCount(platform, modelId, keyId, DAY, now) >= limits.rpd;
const tpdExhausted =
limits.tpd !== null && tokenCount(platform, modelId, keyId, DAY, now) >= limits.tpd;
- const base = (rpdExhausted || tpdExhausted)
+ // No daily quota published → use repeated-429 heuristic: 2+ 429s in the
+ // last hour is treated as effectively daily-exhausted. This unsticks
+ // providers that publish no daily cap (ollama, cloudflare, etc.) from the
+ // 90s-cooldown-loop without requiring operator-side limit seeding.
+ const unknownLimits = limits.rpd === null && limits.tpd === null;
+ let heuristicallyExhausted = false;
+ if (unknownLimits) {
+ // The current hit is recorded first so the threshold can be reached across
+ // consecutive 429s, but only for providers where counters cannot decide.
+ recordNullLimitHit(platform, modelId, keyId, now);
+ heuristicallyExhausted =
+ recentHitCount(platform, modelId, keyId, now) >= NULL_LIMIT_HIT_THRESHOLD;
+ }
+ const base = (rpdExhausted || tpdExhausted || heuristicallyExhausted)
? getNextCooldownDuration(platform, modelId, keyId)
: TRANSIENT_COOLDOWN_MS;
// Honor an upstream Retry-After as a floor: never bench shorter than our own