Brain Docs

Reference

TypeScript SDKInstallationHTTP clientWire client
ErrorsRetriesPagination
Brain/Docs
✦ ASKBrain on GitHubDashboard
TypeScript SDKRetries

Retries

Both retry layers — the HTTP client's built-in policy with its idempotent-only verb list, and the wire tier's backoff primitives.

PURPOSE

The two tiers retry differently. The HTTP client retries for you, on a list of verbs it considers safe to repeat. The wire client does not retry at all — it exports the primitives and leaves the loop to you. This page documents both, and the server hint that overrides your backoff.

HTTP tier

BrainHttpClient applies an HttpRetryPolicy automatically.

ParameterTypeRequired
maxAttemptsnumberrequired

Total attempts including the first. 1 disables retry.

baseDelayMsnumberrequired

First backoff; doubles each subsequent attempt.

maxDelayMsnumberrequired

Upper bound on any single backoff — and it also caps a server's Retry-After.

Two policies ship:

OptionTypeDefault / Env
DEFAULT_HTTP_RETRY3 / 100ms / 2s

Three attempts, 100 ms base, 2 s cap. Applied when you pass no retry.

NO_HTTP_RETRY1 / 0 / 0

A single attempt. Use it when the caller owns the retry decision.

const brain = new BrainHttpClient({
  apiKey: process.env.BRAIN_API_KEY!,
  retry: { maxAttempts: 5, maxDelayMs: 10_000 },  // partial: merged with the default
});

What is retried

Only three conditions, and only on verbs the client marks idempotent:

ConditionRetried
status === 0 — transport failure or timeout, never reached the edgeYes
503 — service unavailableYes
429 — rate limitedYes
Every other statusNo, terminal
Not every verb is retried, and the choices are deliberate

putLlmCredential is not retried: a PUT that may have landed is not safe to repeat blind when what it replaces is a live credential. subscribe is not retried: a retry would reopen the feed at the original position and re-deliver everything already seen — where to resume is the caller's decision, because only the caller knows where it got to.

A server Retry-After header, when present and parseable as integer seconds, overrides the computed backoff — capped at maxDelayMs.

Wire tier

BrainClient does not retry a verb on its own — retrying a wire call is opt-in, because the connection is yours and only you know whether a dropped socket is worth another attempt. The SDK gives you the pieces:

ParameterTypeRequired
isRetryable(err)booleanrequired

Whether this failure is worth repeating. See Errors.

backoffMs(policy, attempt, serverHintMs)number | nullrequired

The delay for an attempt. Returns the server hint — capped at maxDelayMs — when one is given; otherwise baseDelayMs * 2 ** (attempt - 1), capped. null means do not wait.

DEFAULT_RETRY_POLICYRetryPolicyoptional

3 attempts, 100 ms base, 5 s cap — note the cap differs from the HTTP tier's 2 s.

NO_RETRYRetryPolicyoptional
A single attempt.

…and a combinator that composes them:

ParameterTypeRequired
withRetry(op, policy?)Promise<T>required

Runs op, re-running it while the error is retryable and attempts remain. policy defaults to DEFAULT_RETRY_POLICY. Honours a server retryAfterMs as a floor, and jitters the actual sleep.

import { withRetry, DEFAULT_RETRY_POLICY } from "@brain-db/sdk";

const req = new RecallBuilder("what did Priya decide?").limit(6).build();
const answer = await withRetry(() => brain.recall(req), DEFAULT_RETRY_POLICY);
Pass a thunk that reuses the request

withRetry re-invokes op from scratch each attempt, so what you hand it has to rebuild the call, not the request. () => brain.recall(req) reuses one req and so one requestId, which is what makes the retry idempotent server-side. () => brain.recall(builder.build()) mints a fresh id per attempt, and the server sees distinct writes rather than a repeat — see Idempotency on the wire below.

withRetry is wire-tier only

It classifies with isRetryable, which understands the wire error taxonomy — so it is exported from the package root and not from @brain-db/sdk/http. The HTTP client does its own retrying internally and needs no combinator; see the HTTP tier above for what it absorbs. Python and Rust have the same function (with_retry, and Rust's with_default_retry).

If you want different behaviour than the combinator's, the pieces are public and the loop is short:

import { backoffMs, isRetryable, DEFAULT_RETRY_POLICY, ServerError } from "@brain-db/sdk";

async function withBackoff<T>(op: () => Promise<T>, policy = DEFAULT_RETRY_POLICY) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await op();
    } catch (err) {
      if (attempt >= policy.maxAttempts || !isRetryable(err)) throw err;
      const hint = err instanceof ServerError ? err.retryAfterMs : null;
      const delay = backoffMs(policy, attempt, hint);
      if (delay !== null) await new Promise((r) => setTimeout(r, delay));
    }
  }
}

Jitter

The server's retryAfterMs is a floor, not a target: withRetry waits a random interval between that floor and the computed backoff, so a fleet told to retry after the same hint does not return as one wave. Note that the hand- rolled loop above does not do this — it sleeps the computed delay exactly. If you write your own, add the jitter: synchronised retries are how a recovering shard is knocked back over.

Idempotency on the wire

Retrying a wire write is only safe because the request carries a requestId. The builders generate a fresh one on every .build(), so re-building is not retrying — it produces a new id and the server sees a second, distinct write.

const req = new EncodeBuilder("...").build();  // build ONCE
await withBackoff(() => client.encode(req));   // reuse the same request

Replaying the same requestId with different parameters is IdempotencyConflict.

See also
ErrorsWire clientHTTP client

Was this page helpful?

Errors

Both error taxonomies — the wire BrainError hierarchy with its nine categories and the eighty-odd codes, and the HTTP tier's BrainHttpError.

Pagination

Cursor-based enumeration on the HTTP tier, frame-based streaming on the wire, and the terminator each one uses.

On this page

HTTP tierWhat is retriedWire tierJitterIdempotency on the wire
Suggest an editOpen in Playground