Brain Docs
Build

Wire it in

Drop it into an existing loopA chatbot that remembersHandling corrections

Production

Alongside your RAGOne space per customerErasing a subject

Working with the API

Error handlingRetries and cancellationIdempotencyStreamingGraph queriesFaithfulness checkingIdentity walkthroughNamespace lifecycle

Reference

Brain/Docs
✦ ASKBrain on GitHubDashboard
BuildRetries and cancellation

Retries and cancellation

Retry wire calls safely with the request-id contract and bound calls with timeouts — the SDK takes no external AbortSignal.

PURPOSE

Set retry behaviour that matches your latency budget, retry wire calls without double-writing, and bound every call with a deadline. Full policy semantics live in the retries reference; this guide is the task recipe.

◇Prerequisites
  • A Brain client.
  • Familiarity with Error handling.
  • A latency budget you want calls to respect.
▸What you'll build

A configuration that retries only what is safe, backs off with jitter, honors a server hint, and fails fast when a deadline is blown.

What retries automatically, and what doesn't

BrainClient does no automatic retry — you retry explicitly. The stable requestId minted by each request builder makes a resend idempotent server-side (24-hour window), so a retry that reuses the same request object collapses to one logical write.

Step-by-step

The wire client does not retry for you. Build the request once so its requestId is stable, then re-run while the error is retryable. Reusing the same request object is what keeps the resend idempotent — a rebuild mints a new id and defeats it.

import { ForgetBuilder, isRetryable } from "@brain-db/sdk";

const req = new ForgetBuilder(memoryId).build(); // build once → stable requestId
for (let attempt = 1; ; attempt++) {
  try {
    await client.forget(req);
    break;
  } catch (e) {
    if (!isRetryable(e) || attempt >= 3) throw e;
    await new Promise((r) => setTimeout(r, 100 * 2 ** (attempt - 1)));
  }
}

The SDK also ships a withRetry combinator that wraps this loop with jittered backoff — see Retries.

from brain_db_sdk import ForgetBuilder, with_retry

req = ForgetBuilder(memory_id).build()   # build once → stable request_id
res = with_retry(lambda: client.forget(req))
use std::time::Duration;
use brain_db_sdk::ForgetBuilder;

let req = ForgetBuilder::new(memory_id).build(); // build once → stable request_id
let mut attempt = 1u32;
loop {
    match client.forget(&req).await {
        Ok(_) => break,
        Err(e) => {
            if !e.is_retryable() || attempt >= 3 {
                return Err(e.into());
            }
            tokio::time::sleep(Duration::from_millis(100 * 2u64.pow(attempt - 1))).await;
            attempt += 1;
        }
    }
}

The SDK also ships a with_retry combinator that wraps this loop with jittered backoff — see Errors.

The client takes no external AbortSignal. A call is bounded by its configured timeout, which fires an internal abort on expiry.

// connect + per-response read deadlines; a miss rejects with BrainTimeout.
const client = await BrainClient.connect("127.0.0.1", 9090, {
  auth: { kind: "token", token: tokenBytes },
  requestTimeoutMs: 5_000,
});
# The per-response read deadline is configured on the client at connect time;
# a miss raises BrainTimeout. See the wire client reference.
use std::net::SocketAddr;
use std::time::Duration;
use brain_db_sdk::{Auth, BrainClient, ClientConfig};

// connect + per-response read deadlines; a miss fails with BrainError::Timeout.
let addr: SocketAddr = "127.0.0.1:9090".parse()?;
let mut config = ClientConfig::new(Auth::Token(token_bytes));
config.request_timeout = Some(Duration::from_secs(5));
let client = BrainClient::connect_with(addr, config).await?;

BrainTimeout is classified retryable by isRetryable. To cancel work in flight beyond the deadline, close the client — that tears down the connection.

What each tier retries for you

HTTP client
Wire client
Automatic
Yes, on idempotent verbs only
No — it ships the primitives and you write the loop
Retried on
Transport failure (status 0), 429, 503
Closed, timeout, transport, plus ResourceExhausted and Unavailable
Never retried
Every 4xx; plus putLlmCredential and subscribe, deliberately
Protocol errors and version mismatches
Backoff cap
2 s by default
5 s by default — note they differ

Two exclusions on the HTTP tier are worth knowing rather than discovering. putLlmCredential is not retried because a PUT that may have landed is not safe to repeat blind against a live credential. subscribe is not retried because a retry would reopen the feed at the original position and re-deliver everything already seen — where to resume is the caller's decision, since only the caller knows where it got to.

Retrying only on 429 is not enough

Brain's own rate limiting arrives as 503 engine.unavailable, not 429. The only 429 on this API is the edge's plan metering. A client that treats 429 as "slow down" and every 5xx as fatal gives up on a perfectly recoverable condition. See Errors.

Cancellation stops work; abandoning does not

Dropping a promise or a future does not tell the server to stop computing. On the wire, cancelStream ends an in-flight stream by id — the right move when a long enumeration or traversal is no longer needed. Over HTTP, closing the response body is the whole cancellation story.

Budgeting total time

A retrying call's worst case is roughly maxAttempts × timeout + accumulated backoff. If a route handler has a 30 s deadline, don't pair a 30 s per-attempt timeout with 5 retries — the retry loop alone can outrun the handler. Tighten the per-attempt timeout and cap maxAttempts so the product fits your budget.

A transport drop is reported retryable, but the wire client does not transparently reconnect a dead socket — a retry over a closed connection re-fails fast. Recover by opening a fresh BrainClient.connect(...).

Don't rebuild a wire request inside the retry loop. A fresh build() mints a new requestId, so the server treats the retry as a new logical write instead of deduplicating it.

See also
Error handlingWhich failures are retryable in the first place.IdempotencyWhy reusing the request id makes a retry safe.Retries referenceFull policy fields and the withRetry combinator.StreamingDeadlines also bound streamed frame reads.

Was this page helpful?

Error handling

Catch the BrainError hierarchy from the wire client, decide retry vs surface, and know which of the nine error categories are transient.

Idempotency

Two mechanisms keep writes safe to repeat — request_id idempotency (same id, same response) and content dedup (BLAKE3 fingerprint, was_deduplicated).

On this page

What retries automatically, and what doesn'tStep-by-stepWhat each tier retries for youCancellation stops work; abandoning does notBudgeting total time
Suggest an editOpen in Playground