# Fallbacks and timeouts

> Nobody waits on Zigbongo. If a decision doesn't come back in 150 ms, or anything goes wrong, the SDK returns your default and tells Zigbongo not to learn from that call.

## The 150 ms timeout

`decide()`, and a registered flow's `start()` and `next()`, wait at most 150 ms for Zigbongo. If the answer doesn't come in time, Zigbongo can't be reached, or it answers with an error, the call returns your default instead. These calls never throw.

```js
const zb = new Zigbongo({
  apiKey: process.env.ZIGBONGO_KEY,
  baseUrl: "https://zigbongo.com",
  timeoutMs: 150, // the default
});
```

`timeoutMs` changes the budget. A longer one gives a slow answer more time, and makes your page wait that much longer when Zigbongo is slow.

Errors fall back too, not only timeouts. A `400` for a malformed call, a `401` for a revoked key or a `429` over your [rate limit](https://zigbongo.com/docs/retries-and-rate-limits.md) all return your default, so a mistake in your integration shows up as fallbacks, not exceptions. Watch for them with `onError` (below) and on the dashboard.

A connection that closes before Zigbongo answers, as a proxy can do when it retires one, doesn't cost a fallback: the call is sent once more at once, within the same 150 ms ([Retries and rate limits](https://zigbongo.com/docs/retries-and-rate-limits.md)).

## The connection, and warm()

Opening a connection to Zigbongo takes a DNS lookup and a TLS handshake on top of the call itself, and that counts against the 150 ms. From servers far from Zigbongo, a call that has to open one can miss its budget.

So the Node.js SDK keeps one HTTP/2 connection open between calls, shared by every client in the process, however many calls you make at once. It closes the connection after 50 seconds without a call. Only the first call after your server starts, or after a quiet spell, waits for a new one. An idle connection never keeps your process from exiting.

To open the connection before your first visitor arrives, call `warm()` when your server starts, or in a serverless function's init:

```js
const zb = new Zigbongo({
  apiKey: process.env.ZIGBONGO_KEY,
  baseUrl: "https://zigbongo.com",
});
await zb.warm(); // opens the connection
```

`warm()` never throws. If Zigbongo can't be reached or the key is refused, the error goes to `onError` and your server starts anyway, with decisions falling back to your defaults until Zigbongo answers.

Calls go through Node's own `fetch` instead when a proxy variable (`HTTPS_PROXY` or `HTTP_PROXY`) is set, when `baseUrl` is plain `http:`, or when you pass your own `fetch` (a mock in your tests, or your own dispatcher). Node's `fetch` closes a connection after 4 seconds without a call, so more calls wait for a new one.

## What a fallback returns

From `decide()`:

```js
{ option: "monthly", arm: "fallback", fallback: true, sessionId: null, decisionId: null }
```

- `option` is the `default` you sent. Show it as usual.
- `arm` is `"fallback"` and `fallback` is `true`.
- `decisionId` is null: there's no decision to report a result for. The session helper drops the `result` you pass at the next call, and the session carries on.
- `sessionId` is the one you passed, or null when the fallback started no session.

From a registered flow, the step comes from your definition's defaults, with `fallback: true`, `arm: "fallback"` and no `decisionId`. From then on the run follows the defaults to its end without calling Zigbongo again ([Registered flows](https://zigbongo.com/docs/registered-flows.md)).

An outcome you report after a fallback still counts. With no session, the session helper and a registered run report it by subject instead.

## Fallbacks aren't learned from

A call can time out on your side and still reach Zigbongo, which would then record a decision the person never saw. So every `decide`, `start` and `next` carries an `Idempotency-Key`, and on a fallback the SDK reports it to `POST /v1/fallbacks` with that key and the reason (`timeout`, `network`, `http_503`, and so on):

- If the decision reached Zigbongo, it's marked and forgotten while its session's window is open. For a registered flow, every decision that call made is forgotten.
- If the report arrives before the decision does, the two are matched when the decision lands.
- Reports for calls that never arrived are kept, so they count in the fallback rate.

The dashboard shows, at each decision point, the share of calls that fell back.

If you call the HTTP API yourself, do the same: send an `Idempotency-Key` header (1 to 200 visible ASCII characters) with each decide, and report a call you gave up on:

```sh
curl -X POST https://zigbongo.com/v1/fallbacks \
  -H "Authorization: Bearer $ZIGBONGO_KEY" \
  -H "Content-Type: application/json" \
  -d '{"flowKey": "checkout", "requestId": "7d1f0c2e-5b9a-4c55-9e0f-2a8d4b1c6e31", "node": "plan", "reason": "timeout"}'
```

`requestId` is the decide call's `Idempotency-Key`. The answer is `{"status": "recorded"}`; a repeated report is kept once, and may answer `duplicate`.

## flush() and serverless functions

In Node.js the fallback report goes out in the background, after `decide()` has returned your default. A serverless function can be frozen or stopped as soon as it returns, with the report unsent. Wait for it first:

```js
export async function handler(event) {
  const offer = await zb.decide("checkout", { subjectId: event.userId, node: "upsell", options: ["none", "annual"], default: "none" });
  const body = render(offer.option);
  await zb.flush(); // waits for any fallback reports
  return { statusCode: 200, body };
}
```

`flush()` returns at once when nothing is waiting.

PHP has nothing running in the background, so its reports wait in the client and go out when you call `flush()`, when the client is destroyed, or when the script ends, even after a fatal error. They all share one budget, `fallbackReportTimeoutMs` (1,000 ms by default), so a page that fell back can take up to that much longer to finish:

- Under PHP-FPM, finish the response first with `fastcgi_finish_request()` (Symfony and Laravel already do), or lower `fallbackReportTimeoutMs`.
- In a long-running worker (queues, RoadRunner, Swoole), call `$zb->flush()` after each job.

Before PHP 8.5, each request that decides opens a new connection to Zigbongo, and the handshake counts against the 150 ms. From PHP 8.5 the worker keeps the connection between requests.

## onError

Every error the client absorbs instead of throwing goes to `onError`: decide fallbacks, a registered run's failed starts, steps and abandons, and fallback reports that couldn't be sent.

```js
const zb = new Zigbongo({
  apiKey: process.env.ZIGBONGO_KEY,
  baseUrl: "https://zigbongo.com",
  onError: (e) => logger.warn({ reason: e.reason, status: e.status, code: e.code }, e.message),
});
```

```php
$zb = new Zigbongo(
    apiKey: getenv('ZIGBONGO_KEY'),
    baseUrl: 'https://zigbongo.com',
    onError: fn (\Zigbongo\ZigbongoException $e) => error_log("zigbongo {$e->reason} {$e->status} {$e->errorCode}: {$e->getMessage()}"),
);
```

- `reason` is `timeout`, `network`, `http` (Zigbongo answered with an error) or `invalid_response`; PHP adds `invalid_request`, for a request that can't be encoded, such as a `NAN` value.
- `status` is the HTTP status when Zigbongo answered, and the error code (`code` in Node.js, `errorCode` in PHP) is Zigbongo's, such as `invalid_input` or `rate_limited`.
- Keep `onError` short. Both SDKs ignore an `onError` that throws (or, in Node.js, returns a promise that rejects), so a mistake in it can't make a call throw or stop your process, though what it was about to log is lost.

A steady stream of `timeout` errors points at the network between your servers and Zigbongo, or at Zigbongo being slow; `http` errors with a 4xx status usually mean a mistake in the calls.

---

The Markdown of https://zigbongo.com/docs/fallbacks-and-timeouts/. Every docs page: https://zigbongo.com/llms.txt
