Manual rate-limit backoff
Catch a 429 / 503, honor Retry-After, and retry — taking over from the SDK's built-in auto-retry when you need to.
The HTTP client already retries transport failures and 503 responses for the
idempotent verbs (encode, whoami, capabilities) with exponential backoff,
honoring a server Retry-After. For most callers that is the right behavior —
you do nothing. The non-idempotent verbs (recall, forget, link, unlink,
plan, reason) run exactly once and are never auto-retried.
When you want different behavior — enqueue the write, log it, or fall through to
a degraded path — catch the typed error yourself. Every HTTP failure throws a
BrainHttpError carrying status, code, and message (status: 0 means a
transport failure or timeout).
import { BrainHttpClient, BrainHttpError } from '@brain-db/sdk';
const brain = new BrainHttpClient({ apiKey: process.env.BRAIN_API_KEY! });
async function encodeOrEnqueue(text: string) {
try {
return await brain.encode({ text });
} catch (err) {
if (err instanceof BrainHttpError && (err.status === 429 || err.status === 503)) {
// Enqueue for a worker to retry later instead of blocking here.
await jobQueue.enqueue('brain-encode', { text, notBefore: Date.now() + 1000 });
return null;
}
throw err; // 4xx (bad request, auth) and everything else: propagate.
}
}from brain_db_sdk import BrainHttpClient, BrainHttpError
brain = BrainHttpClient(os.environ['BRAIN_API_KEY'])
def encode_or_enqueue(text: str):
try:
return brain.encode(text)
except BrainHttpError as err:
if err.status in (429, 503):
job_queue.enqueue('brain-encode', {'text': text, 'not_before': time.time() + 1})
return None
raise # 4xx and everything else: propagate.Manual retry with backoff
If you want retry behavior but with your own logging, do it yourself. Honor a
server Retry-After when present, otherwise back off exponentially:
async function recallWithRetry(query: string, attempts = 3) {
let delay = 250;
for (let i = 0; i < attempts; i++) {
try {
return await brain.recall({ query });
} catch (err) {
const retryable = err instanceof BrainHttpError && (err.status === 429 || err.status === 503);
if (!retryable || i === attempts - 1) throw err;
console.warn(`brain ${err.status}, retrying in ${delay}ms`, { attempt: i });
await new Promise((r) => setTimeout(r, delay));
delay *= 2;
}
}
throw new Error('unreachable');
}On the wire client
The wire client (BrainClient) raises a ServerError whose category is
ResourceExhausted (rate/quota) or Unavailable (shard busy), and those carry
a retryAfterMs hint. Use the isRetryable(err) helper to branch, or let the
built-in withRetry combinator drive it. See
Errors and Retries.
Don't loop indefinitely. If the server is genuinely overloaded the retry budget is cooperation — a few attempts with backoff is the polite ceiling. After that, propagate the error and let the caller degrade.
The two sources of back-pressure
A 429 and a 503 come from different places and mean different things, which
decides whether retrying is even the right move.
| Status | Code | Who said it | What it means |
|---|---|---|---|
429 | quota.exceeded | The edge's plan metering | A commercial ceiling was reached. Refused before the request touched Brain. |
503 | engine.unavailable | Brain | Rate limiting, out of slots, overloaded, restarting or in maintenance. Both the ResourceExhausted and Unavailable wire categories collapse here. |
503 | llm_credential.unavailable | The broker | A provider key exists but could not be used. |
409 | llm_credential.missing | The broker | No key is registered. Not retryable — deliberately a 409 so clients do not spin forever. |
Two different 503s want different handling: engine.unavailable clears on
its own, llm_credential.unavailable may need an operator. Retrying both
identically is fine for a while and tells you nothing when it does not clear.
Cap the server's hint
A Retry-After header overrides your computed backoff — but cap it with your
own maximum. A header you did not generate can park a worker for an hour, and
the failure is indistinguishable from a hang.
Treat the hint as a floor rather than a target and add jitter over it: a fleet that all waits exactly the hinted interval returns as one wave, which is how a recovering shard gets knocked over a second time. The SDK's own combinator does exactly this — it waits a random interval between the server's floor and the computed backoff.
Retrying is only safe because of the request id
When you retry a write yourself, send the same request rather than
rebuilding it. The wire builders mint a fresh request id on every build(),
so re-building is not retrying: it produces a second, distinct write that
content dedup may or may not catch.
On the HTTP tier the edge generates the id per request, which is why encode
is on the auto-retry list and the non-idempotent verbs are not. See
Idempotency.
Was this page helpful?
Walk the entity graph
Encode a transcript, list the entities the pipeline extracted, and walk the relation graph with /v1/entities and /v1/graph.
Integrations
Five ways to wire Brain into a stack — Next.js, FastAPI, LangChain, the OpenAI Responses API, or the first-party MCP server — and the one question that decides which.