Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(api): aggregator failover always answers inside the LB deadline

nirholas6b45373e1142
diff --git a/api/_lib/aggregator.js b/api/_lib/aggregator.js
index c6d20f110..8fa2ba134 100644
--- a/api/_lib/aggregator.js
+++ b/api/_lib/aggregator.js
@@ -15,6 +15,21 @@ import { readBody } from './http.js';
const UPSTREAM_TIMEOUT_MS = 20_000;
+// The external HTTPS load balancer cuts every response at 30s (three-ws-backend
+// timeoutSec: 30), so the whole call, retries included, must answer inside
+// that. One shared deadline per executeUpstream call; every attempt's abort
+// timer fits in whatever remains, and a retry never starts with less than
+// MIN_ATTEMPT_MS on the clock. Without this, a blackholed primary (20s) plus
+// one alternate (20s) overruns the LB and the caller sees its 502 instead of
+// our answer.
+const TOTAL_UPSTREAM_BUDGET_MS = 25_000;
+const MIN_ATTEMPT_MS = 1_000;
+
+// A pooled provider treats a host this slow as down: aborting early leaves
+// budget to actually use the alternates the pool exists for. Single-host
+// providers keep the full UPSTREAM_TIMEOUT_MS, since waiting is all they can do.
+const POOLED_ATTEMPT_TIMEOUT_MS = 10_000;
+
// How many distinct upstream hosts one call may try before giving up. Only
// applies to providers that declare alternates (`provider.bases`); everything
// else makes exactly one attempt, as before.
@@ -104,6 +119,10 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, ap
// caller's query params. See the `solana` provider in api/v1/_providers.js.
const upstreamMethod = endpoint.upstreamMethod || endpoint.method;
+ const hasPool = typeof provider.bases === 'function';
+ const deadline = Date.now() + TOTAL_UPSTREAM_BUDGET_MS;
+ const perAttemptCap = hasPool ? POOLED_ATTEMPT_TIMEOUT_MS : UPSTREAM_TIMEOUT_MS;
+
// One attempt against one upstream host. Everything host-independent (the
// query builder, the body builder) is re-run per attempt because applyKey may
// write the key into the URL, which differs per host.
@@ -127,7 +146,7 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, ap
provider.applyKey(headers, url, apiKey);
const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);
+ const timer = setTimeout(() => controller.abort(), Math.min(perAttemptCap, deadline - Date.now()));
let res;
try {
res = await fetch(url, {
@@ -213,6 +232,9 @@ export async function executeUpstream({ provider, endpoint, query = {}, body, ap
let lastErr = firstErr ?? null;
const budget = MAX_UPSTREAM_ATTEMPTS - (firstErr ? 1 : 0);
for (const base of ordered.slice(0, budget)) {
+ // A retry that cannot get a meaningful slice of the deadline is not worth
+ // starting; surface the best error we have while the LB is still listening.
+ if (lastErr && deadline - Date.now() < MIN_ATTEMPT_MS) break;
try {
const out = await attempt(base);
markGood(base);
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 64cffaf71..b5ba3970e 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -3327,9 +3327,11 @@ aggregator walks that pool inside a single request when a host answers 429, a
5xx, or is unreachable (up to 3 hosts per call; caller-fault 4xx never
retries). A host that just failed is skipped for a short cooldown window while
an alternate exists, so an upstream outage costs one discovery, not one per
-request. The `solana` provider fronts the platform's full priority-ordered RPC
-pool this way; single-host providers behave as plain pass-throughs with one
-attempt.
+request. The whole chain runs under a 25s deadline (pooled attempts abort at
+10s each) so the caller always gets the aggregator's answer, never a load
+balancer timeout. The `solana` provider fronts the platform's full
+priority-ordered RPC pool this way; single-host providers behave as plain
+pass-throughs with one attempt.
### The free tier
diff --git a/tests/aggregator-upstream-failover.test.js b/tests/aggregator-upstream-failover.test.js
index ad56c5d08..2ab769f80 100644
--- a/tests/aggregator-upstream-failover.test.js
+++ b/tests/aggregator-upstream-failover.test.js
@@ -209,6 +209,44 @@ describe('aggregator upstream failover', () => {
expect(seen[seen.length - 1]).toBe('primary.invalid');
});
+ it('answers inside the 25s total budget even when every host blackholes', async () => {
+ vi.useFakeTimers();
+ try {
+ const seen = [];
+ // Every host hangs until its abort timer fires; only the deadline can
+ // end this call.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ (input, init) =>
+ new Promise((_, reject) => {
+ seen.push(hostOf(input));
+ init.signal.addEventListener('abort', () => reject(new Error('aborted')));
+ }),
+ ),
+ );
+
+ const started = Date.now();
+ const pending = executeUpstream({
+ provider: providerWithPool(['https://backup-a.invalid', 'https://backup-b.invalid']),
+ endpoint,
+ query: {},
+ apiKey: null,
+ }).catch((err) => ({ err, settledAt: Date.now() }));
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ const { err, settledAt } = await pending;
+
+ // Pooled attempts abort at 10s each; the third gets only the 5s left in
+ // the budget, so the caller has an answer at 25s, inside the LB's 30s.
+ expect(err).toMatchObject({ code: 'upstream_unreachable' });
+ expect(seen).toEqual(['primary.invalid', 'backup-a.invalid', 'backup-b.invalid']);
+ expect(settledAt - started).toBeLessThanOrEqual(25_000);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('gives a skipped primary a last chance when every alternate fails', async () => {
const seen = [];
vi.stubGlobal(