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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix: resolve CPU leak from Bottleneck limiter accumulation and unbounded in-memory caches
soyelmismoc6f17d8e7887
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex 5c9c571148..36dfb78f5e 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -1518,7 +1518,10 @@ export async function handleChatCore({comboName: comboName || undefined,});});+ const traceEnabled =+ process.env.OMNIRROUTE_TRACE === "true" || process.env.DEBUG === "true";const trace = (label: string, extra?: Record<string, unknown>) => {+ if (!traceEnabled) return;const elapsed = Date.now() - startTime;const suffix = extra ? ` ${JSON.stringify(extra)}` : "";log?.info?.("STAGE_TRACE", `${traceId} ${label} t=${elapsed}ms${suffix}`);@@ -2351,7 +2354,7 @@ export async function handleChatCore({let cavemanOutputModeIntensity: string | null = null;let preCompressionBody: typeof body | null = null;if (body && Array.isArray(allMessages) && allMessages.length > 0) {- let estimatedTokens = estimateTokens(JSON.stringify(allMessages));+ let estimatedTokens = estimateTokens(allMessages);let promptCompressionEnabled = false;let compressionSettings: CompressionConfig | null = null;@@ -2582,7 +2585,7 @@ export async function handleChatCore({body = outputMode.body as typeof body;cavemanOutputModeApplied = true;cavemanOutputModeIntensity = config.cavemanOutputMode.intensity;- estimatedTokens = estimateTokens(JSON.stringify(body?.messages ?? body?.input ?? []));+ estimatedTokens = estimateTokens(body?.messages ?? body?.input ?? []);log?.debug?.("COMPRESSION", "Caveman output mode instruction applied");} else if (outputMode.skippedReason && outputMode.skippedReason !== "disabled") {log?.debug?.("COMPRESSION", `Caveman output mode skipped: ${outputMode.skippedReason}`);@@ -2792,7 +2795,7 @@ export async function handleChatCore({const COMPRESSION_THRESHOLD = 0.7;let reservedTokens = 0;if (Array.isArray(body.tools)) {- reservedTokens = estimateTokens(JSON.stringify(body.tools));+ reservedTokens = estimateTokens(body.tools);}const threshold = Math.max(1,@@ -4913,8 +4916,10 @@ export async function handleChatCore({// Save structured call log with full payloadsconst cacheUsageLogMeta = buildCacheUsageLogMeta(usage);if (usage && typeof usage === "object") {- const msg = `[${new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit" })}] 📊 [USAGE] ${provider.toUpperCase()} | ${formatUsageLog(usage)}${connectionId ? ` | account=${connectionId.slice(0, 8)}...` : ""}`;- console.log(`${COLORS.green}${msg}${COLORS.reset}`);+ if (traceEnabled) {+ const msg = `[${new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit" })}] 📊 [USAGE] ${provider.toUpperCase()} | ${formatUsageLog(usage)}${connectionId ? ` | account=${connectionId.slice(0, 8)}...` : ""}`;+ console.log(`${COLORS.green}${msg}${COLORS.reset}`);+ }saveRequestUsage({provider: provider || "unknown",diff --git a/open-sse/services/apiKeyRotator.ts b/open-sse/services/apiKeyRotator.tsindex 1814fb833d..abf2d7ccb5 100644--- a/open-sse/services/apiKeyRotator.ts+++ b/open-sse/services/apiKeyRotator.ts@@ -21,6 +21,9 @@ const _keyIndexes = new Map<string, number>();// Tracks which connections have extra API keys (for A3 guard in chatCore.ts)// Used to prevent disabling an entire connection when only one key fails.const _connectionExtraKeys = new Map<string, boolean>();+// Eviction limits to prevent unbounded memory growth under heavy load+const MAX_KEY_HEALTH_ENTRIES = 500;+const MAX_CONNECTION_EXTRA_KEYS = 500;/*** Record whether a connection has extra API keys.@@ -28,6 +31,10 @@ const _connectionExtraKeys = new Map<string, boolean>();*/export function trackConnectionExtraKeys(connectionId: string, extraKeys: string[]): void {const validExtras = extraKeys.filter((k) => typeof k === "string" && k.trim().length > 0);+ if (_connectionExtraKeys.size >= MAX_CONNECTION_EXTRA_KEYS) {+ const oldest = _connectionExtraKeys.keys().next().value;+ if (oldest !== undefined) _connectionExtraKeys.delete(oldest);+ }_connectionExtraKeys.set(connectionId, validExtras.length > 0);}@@ -64,6 +71,10 @@ const FAILURE_THRESHOLD = 2; // Mark as invalid after 2 consecutive failuresfunction getOrCreateHealth(connectionId: string, keyId: string): KeyHealth {const scopedKey = `${connectionId}:${keyId}`;if (!_keyHealth.has(scopedKey)) {+ if (_keyHealth.size >= MAX_KEY_HEALTH_ENTRIES) {+ const oldest = _keyHealth.keys().next().value;+ if (oldest !== undefined) _keyHealth.delete(oldest);+ }_keyHealth.set(scopedKey, {status: "active",failures: 0,@@ -265,6 +276,10 @@ export function syncHealthFromDB(connectionId: string, health?: Record<string, Kif (!health) return;for (const [keyId, keyHealth] of Object.entries(health)) {+ if (_keyHealth.size >= MAX_KEY_HEALTH_ENTRIES) {+ const oldest = _keyHealth.keys().next().value;+ if (oldest !== undefined) _keyHealth.delete(oldest);+ }_keyHealth.set(`${connectionId}:${keyId}`, keyHealth);}}@@ -336,6 +351,11 @@ export function removeConnectionHealth(connectionId: string): void {export function removeConnectionIndex(connectionId: string): void {_keyIndexes.delete(connectionId);_connectionExtraKeys.delete(connectionId);+ for (const key of _keyHealth.keys()) {+ if (key.startsWith(`${connectionId}:`)) {+ _keyHealth.delete(key);+ }+ }}export type { KeyHealth };diff --git a/open-sse/services/codexQuotaFetcher.ts b/open-sse/services/codexQuotaFetcher.tsindex f800f3dedb..a572485971 100644--- a/open-sse/services/codexQuotaFetcher.ts+++ b/open-sse/services/codexQuotaFetcher.ts@@ -76,6 +76,7 @@ interface CodexConnectionMeta {const MAX_CONNECTIONS = 100;const connectionRegistry = new Map<string, CodexConnectionMeta>();+const MAX_QUOTA_CACHE_ENTRIES = 200;/*** Register Codex connection metadata for quota fetching.@@ -123,6 +124,13 @@ function getCodexConnectionMeta(if (accessToken) {const meta = { accessToken, ...(workspaceId ? { workspaceId } : {}) };+ if (connectionRegistry.size >= MAX_CONNECTIONS) {+ const oldestKey = connectionRegistry.keys().next().value;+ if (oldestKey !== undefined) {+ quotaCache.delete(oldestKey);+ connectionRegistry.delete(oldestKey);+ }+ }connectionRegistry.set(connectionId, meta);return meta;}@@ -204,6 +212,10 @@ export async function fetchCodexQuota(if (!quota) return null;// Store in cache+ if (quotaCache.size >= MAX_QUOTA_CACHE_ENTRIES) {+ const oldestCacheKey = quotaCache.keys().next().value;+ if (oldestCacheKey !== undefined) quotaCache.delete(oldestCacheKey);+ }quotaCache.set(connectionId, { quota, fetchedAt: Date.now() });return quota;} catch {diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 84e6849b9e..a0ddb3646a 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -414,6 +414,10 @@ export async function validateResponseQuality(// In-memory atomic counter per combo for round-robin distribution// Resets on server restart (by design — no stale state)+// Eviction limits to prevent unbounded memory growth+const MAX_RR_COUNTERS = 500;+const MAX_RESET_AWARE_CACHE = 200;+const rrCounters = new Map<string, number>();const resetAwareConnectionCache = new Map<@@ -1546,6 +1550,10 @@ async function getQuotaAwareConnectionsForTarget(const activeConnections = Array.isArray(connections)? (connections as Array<Record<string, unknown>>): [];+ if (resetAwareConnectionCache.size >= MAX_RESET_AWARE_CACHE) {+ const oldest = resetAwareConnectionCache.keys().next().value;+ if (oldest !== undefined) resetAwareConnectionCache.delete(oldest);+ }resetAwareConnectionCache.set(provider, {connections: activeConnections,fetchedAt: Date.now(),@@ -1677,6 +1685,10 @@ async function fetchResetAwareQuotaWithCache({const refreshPromise = fetcher(connectionId, connection).then((quota) => {if (quota) {+ if (resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE) {+ const oldest = resetAwareQuotaCache.keys().next().value;+ if (oldest !== undefined) resetAwareQuotaCache.delete(oldest);+ }resetAwareQuotaCache.set(cacheKey, {quota,fetchedAt: Date.now(),@@ -1690,6 +1702,10 @@ async function fetchResetAwareQuotaWithCache({.catch((error) => {const previous = resetAwareQuotaCache.get(cacheKey);if (previous) {+ if (resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE) {+ const oldest = resetAwareQuotaCache.keys().next().value;+ if (oldest !== undefined) resetAwareQuotaCache.delete(oldest);+ }resetAwareQuotaCache.set(cacheKey, { ...previous, refreshPromise: null });}log.warn?.("COMBO", "Reset-aware quota fetch failed.", {@@ -1702,6 +1718,10 @@ async function fetchResetAwareQuotaWithCache({return null;});+ if (resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE) {+ const oldest = resetAwareQuotaCache.keys().next().value;+ if (oldest !== undefined) resetAwareQuotaCache.delete(oldest);+ }resetAwareQuotaCache.set(cacheKey, {quota: existing?.quota ?? cached?.quota ?? null,fetchedAt: existing?.fetchedAt ?? cached?.fetchedAt ?? 0,@@ -1825,6 +1845,10 @@ async function orderTargetsByResetAwareQuota(if (tiedTargets.length > 1) {const key = `reset-aware:${comboName}`;const counter = rrCounters.get(key) || 0;+ if (rrCounters.size >= MAX_RR_COUNTERS) {+ const oldest = rrCounters.keys().next().value;+ if (oldest !== undefined) rrCounters.delete(oldest);+ }rrCounters.set(key, counter + 1);const startIndex = counter % tiedTargets.length;orderedTiedTargets = [...tiedTargets.slice(startIndex), ...tiedTargets.slice(0, startIndex)];@@ -1984,6 +2008,10 @@ async function orderTargetsByResetWindow(const key = `reset-window:${comboName}`;const counter = rrCounters.get(key) || 0;+ if (rrCounters.size >= MAX_RR_COUNTERS) {+ const oldest = rrCounters.keys().next().value;+ if (oldest !== undefined) rrCounters.delete(oldest);+ }rrCounters.set(key, counter + 1);const startIndex = counter % tiedTargets.length;const orderedTiedTargets = [@@ -3196,7 +3224,7 @@ export async function handleComboChat({if (isModelAvailable) {const available = await isModelAvailable(modelStr, targetForAttempt);if (!available) {- log.info("COMBO", `Skipping ${modelStr} — no credentials available or model excluded`);+ log.debug?.("COMBO", `Skipping ${modelStr} — no credentials available or model excluded`);if (i > 0) fallbackCount++;return null;}@@ -3709,7 +3737,7 @@ export async function handleComboChat({? Math.min(cooldownMs, fallbackDelayMs): 0;if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {- log.info("COMBO", `Waiting ${fallbackWaitMs}ms before fallback to next model`);+ log.debug?.("COMBO", `Waiting ${fallbackWaitMs}ms before fallback to next model`);await new Promise((resolve) => {const timer = setTimeout(resolve, fallbackWaitMs);signal?.addEventListener(@@ -3893,6 +3921,10 @@ async function handleRoundRobinCombo({// Get and increment atomic counterconst counter = rrCounters.get(combo.name) || 0;+ if (rrCounters.size >= MAX_RR_COUNTERS) {+ const oldest = rrCounters.keys().next().value;+ if (oldest !== undefined) rrCounters.delete(oldest);+ }rrCounters.set(combo.name, counter + 1);const startIndex = counter % modelCount;@@ -3929,7 +3961,7 @@ async function handleRoundRobinCombo({if (isModelAvailable) {const available = await isModelAvailable(modelStr, targetForAttempt);if (!available) {- log.info("COMBO-RR", `Skipping ${modelStr} — no credentials available or model excluded`);+ log.debug?.("COMBO-RR", `Skipping ${modelStr} — no credentials available or model excluded`);if (offset > 0) fallbackCount++;continue;}@@ -4170,7 +4202,7 @@ async function handleRoundRobinCombo({isAllAccountsRateLimited);if (providerExhausted) {exhaustedProviders.add(provider);- log.info("COMBO-RR", `Provider ${provider} quota exhausted — marking for skip (#1731)`);+ log.debug?.("COMBO-RR", `Provider ${provider} quota exhausted — marking for skip (#1731)`);} else if (result.status === 429 &&!isTokenLimitBreach &&@@ -4227,7 +4259,7 @@ async function handleRoundRobinCombo({? Math.min(cooldownMs, fallbackDelayMs): 0;if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {- log.info("COMBO-RR", `Waiting ${fallbackWaitMs}ms before fallback to next model`);+ log.debug?.("COMBO-RR", `Waiting ${fallbackWaitMs}ms before fallback to next model`);await new Promise((resolve) => {const timer = setTimeout(resolve, fallbackWaitMs);signal?.addEventListener(diff --git a/open-sse/services/rateLimitManager.ts b/open-sse/services/rateLimitManager.tsindex a46a016574..c5a4a181ae 100644--- a/open-sse/services/rateLimitManager.ts+++ b/open-sse/services/rateLimitManager.ts@@ -192,6 +192,20 @@ function reconcileEnabledConnections(function watchdogTick() {const now = Date.now();+ // Clean up idle limiters that haven't been used recently+ for (const [key, limiter] of Array.from(limiters)) {+ const lastUsed = limiterLastUsed.get(key) ?? 0;+ if (now - lastUsed > INACTIVE_LIMITER_MS) {+ const counts = limiter.counts();+ if (counts.QUEUED === 0 && counts.RUNNING === 0 && counts.EXECUTING === 0) {+ limiters.delete(key);+ lastDispatchAt.delete(key);+ limiterLastUsed.delete(key);+ logRateLimit(`🧹 [RATE-LIMIT] Evicting idle limiter: ${key} (inactive for ${Math.round((now - lastUsed) / 1000)}s)`);+ trackAsyncOperation(limiter.disconnect());+ }+ }+ }for (const [key, limiter] of Array.from(limiters)) {const counts = limiter.counts();if (counts.QUEUED === 0) continue;@@ -211,6 +225,7 @@ function watchdogTick() {);limiters.delete(key);lastDispatchAt.delete(key);+ limiterLastUsed.delete(key);// Do NOT call limiter.stop() — it permanently rejects future .schedule() calls with// "This limiter has been stopped". In-flight requests still holding a reference to// the old instance cannot be redirected to a new one, causing spurious 502 bursts.@@ -257,6 +272,7 @@ function shutdownLimiters(): void {}limiters.clear();lastDispatchAt.clear();+ limiterLastUsed.clear();}// Only register shutdown handlers when there are active limiters to shut down.@@ -349,6 +365,7 @@ export function disableRateLimitProtection(connectionId) {if (key.includes(connectionId)) {limiters.delete(key);lastDispatchAt.delete(key);+ limiterLastUsed.delete(key);trackAsyncOperation(limiter.disconnect());}}@@ -403,8 +420,10 @@ function getLimiter(provider, connectionId, model = null) {limiters.set(key, limiter);lastDispatchAt.set(key, Date.now());+ limiterLastUsed.set(key, Date.now());}+ limiterLastUsed.set(key, Date.now());return limiters.get(key);}@@ -626,6 +645,7 @@ export function updateFromHeaders(provider, connectionId, headers, status, model// the abandoned Bottleneck; under sustained quota pressure that is a real leak.limiters.delete(limiterKey);lastDispatchAt.delete(limiterKey);+ limiterLastUsed.delete(limiterKey);trackAsyncOperation(limiter.disconnect());return;}@@ -799,6 +819,7 @@ export async function __resetRateLimitManagerForTests() {enabledConnections.clear();initialized = false;lastDispatchAt.clear();+ limiterLastUsed.clear();shutdownHandlersRegistered = false;for (const key of Object.keys(learnedLimits)) {