# Production checklist

What to settle before real traffic: retries and idempotency keys, rate-limit headers, the error codes worth branching on, the response cache, prompt-cache ordering, secrets, and measuring the time to the first word.

Source: https://docs.omazy.ai/build-on-omazy/production-checklist/

import { Tabs, TabItem } from '@astrojs/starlight/components'

Each item is short. Each one has cost a product in production an afternoon.

## Retries and idempotency keys

The client already retries what is safe to retry: a `429`, `502`, `503`, `504`
or a dropped connection, twice, with backoff, on routes that read or compute,
and on changes that are safe to repeat: a knowledge document changed or
deleted, the agent's settings, one of its MCP servers changed or removed. A completion is one of
them. A `Retry-After` longer than 30 seconds is not
waited out: it comes back to you as an error, so a stalled caller shows up as
a stalled caller.

A request that changes something is sent once, unless you name it with an
idempotency key. With a key, the platform runs it once and answers a repeat
with the first answer, so the client retries it like a read.

```ts
export async function confirmDelivery(orderId: string, phone: string) {
  // The key names this request. A retry with the same key rings the phone once.
  return omazy.voice.calls.place(
    { to: phone, purpose: 'confirmation', consent_basis: 'transaction', opening: 'Hello, this is about your delivery.' },
    { idempotencyKey: `delivery-${orderId}-confirm` },
  )
}

export async function postNote(conversationId: string, text: string) {
  return omazy.conversations.postMessage(conversationId, [{ type: 'text', markdown: text }], {
    idempotencyKey: randomUUID(),
  })
}
```

- **Make the key from your own ids** when the request belongs to something you
  already track: an order and the step it is for. A retry from a second
  process, or after a deploy, then uses the same key. A random key protects
  only retries inside one process.
- **One key, one request.** The same key with a different body is refused with
  `422 IDEMPOTENCY_KEY_REUSED`.
- **Keys last 24 hours.** Only a success is remembered: after a refusal you
  can send the same key again.

The routes that take a key are placing a call, posting a message,
publishing, an agent turn, a voice job, adding a document, importing a file,
adding a crawl source and crawling it, and connecting an MCP server.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
await omazy.voice.calls.place(call, { idempotencyKey: `delivery-${orderId}-confirm` })
```

</TabItem>
<TabItem label="Python">

```python
omazy.voice.calls.place(to, "confirmation", "transaction", idempotency_key=f"delivery-{order_id}-confirm")
```

</TabItem>
<TabItem label="Go">

```go
ctx := omazy.WithIdempotencyKey(ctx, "delivery-"+orderID+"-confirm")
res, err := c.Voice.PlaceCall(ctx, call)
```

</TabItem>
</Tabs>

If you run your own retry loop (a turn that retries a failed model call
once, for example), set `maxRetries: 0` on that client so the two loops do not
multiply.

## Errors and rate limits

Every refusal is an `OmazyError` with `status`, `code`, `message`,
`requestId` and, when the API said, `retryAfter`. Branch on `code`. Log
`message` and `requestId`.

```ts
export async function ask(question: string) {
  try {
    const { result, response } = await omazy.withResponse((o) =>
      o.ai.complete({ messages: [{ role: 'user', content: question }], cache_ttl: 0 }),
    )
    const rate = response.rateLimit
    if (rate && rate.remaining < rate.limit / 10) console.warn('rate bucket nearly full', rate)
    if (response.tokenIsPrevious) console.warn('still on the token a rotation replaced')
    return result.text
  } catch (e) {
    if (!(e instanceof OmazyError)) throw e
    console.error('omazy refused', e.status, e.code, e.message, e.requestId)
    switch (e.code) {
      case 'RATE_LIMIT_EXCEEDED':
        // The client waited and tried already. Retry-After is longer than 30 seconds.
        return `Busy. Try again in ${e.retryAfter ?? 60} seconds.`
      case 'PLAN_LIMIT_REACHED':
      case 'PAYMENT_REQUIRED':
      case 'SUBSCRIPTION_PAUSED':
      case 'WORKSPACE_INACTIVE':
        // Retrying will not help. Hide the feature and tell the owner.
        return null
      default:
        throw e
    }
  }
}
```

The codes worth their own branch:

| Code | Means | Do |
|---|---|---|
| `UNAUTHORIZED`, `FORBIDDEN` | The token is wrong, revoked, expired, or lacks the scope | Alert. A deployment problem, not the user's |
| `RATE_LIMIT_EXCEEDED` | Over the token's rate, or the provider is rate-limiting | Wait `retryAfter` seconds |
| `PLAN_LIMIT_REACHED` | The plan's AI turns or voice minutes are used up | Stop calling until the period resets |
| `PAYMENT_REQUIRED` | A spend budget is used up | Stop calling until the budget is raised |
| `WORKSPACE_INACTIVE` | The workspace is suspended or closed | Stop calling |
| `SUBSCRIPTION_PAUSED` | The workspace's subscription is paused | Stop calling |
| `STREAM_ERROR` | A stream ended without finishing | Show what you have as unfinished, or retry |
| `NETWORK_ERROR` | No answer arrived at all | Retry later |

For `PLAN_LIMIT_REACHED`, `PAYMENT_REQUIRED`, `WORKSPACE_INACTIVE` and
`SUBSCRIPTION_PAUSED`, retrying cannot help. Hide the feature
rather than showing an error on every click. A refused call costs nothing.

Rate limits are per token, over a sliding ten minutes. Each response says
where the bucket stands:

| Field | Header |
|---|---|
| `rateLimit.limit` | `X-RateLimit-Limit`: the size of the bucket |
| `rateLimit.remaining` | `X-RateLimit-Remaining` |
| `rateLimit.resetSeconds` | `X-RateLimit-Reset`: seconds until a place frees |
| `requestId` | `X-Request-Id` |
| `tokenIsPrevious` | `X-Omazy-Token-Use: previous` |
| `replayed` | `Idempotent-Replayed: true` |

Read them for one call with `withResponse`, as above. `omazy.last` holds the
same fields for the client's most recent response, whichever call it
answered. A Worker or a server that runs requests at once shares one client
between them, so `last` can belong to another request by the time you read
it, even straight after your own `await`. Use `last` only where one call runs
at a time, such as a script.

<Tabs syncKey="sdk-lang">
<TabItem label="TypeScript">

```ts
const { result, response } = await omazy.withResponse((o) => o.ai.complete(req))
console.log(response.requestId, response.rateLimit?.remaining)
```

</TabItem>
<TabItem label="Python">

```python
with omazy.with_response() as response:
    answer = omazy.ai.complete(messages)
print(response.request_id, response.rate_remaining)
```

`response` holds what this thread received, so threads that share a client
never mix their headers.

</TabItem>
<TabItem label="Go">

```go
var info omazy.ResponseInfo
res, err := c.AI.Complete(omazy.WithResponseInfo(ctx, &info), req)
log.Println(info.RequestID, info.RateRemaining)
```

</TabItem>
</Tabs>

An `OmazyError` already carries the `requestId` of the response that refused
the call.

The full list is on [Errors and limits](/reference/core-api/errors-and-limits/).

## The response cache: 0 on live data

The gateway can answer a repeated request from its store, free and in
milliseconds. It matches on the whole request. That is safe for a question
about your opening hours and wrong for a prompt that holds a booking you read
a second ago: the request can be the same while the answer has changed.

- Send `cache_ttl: 0` on every request that carries live data: a tool result,
  a calendar, a stock level, an account balance.
- Send a bounded `cache_ttl`, such as `300`, on requests built only from
  things that change slowly.
- There is no early clear. A short TTL is how a stored reply stays fresh.

`cache_hit: true` on the result says the reply came from the store.

## The prompt cache: fixed text first

The model provider has a cache of its own, for the start of a prompt it has
seen recently. It serves that part faster and cheaper. It only works if the
start is the same from one call to the next.

```ts
const FIXED = [
  'You are the front desk assistant for Nordwell.',
  'Answer in at most three sentences.',
  // ...the long part that never changes: rules, tone, tool guidance
].join('\n')

export async function turn(question: string, visitorName: string, passages: string[]) {
  return omazy.ai.complete({
    // Fixed text first, so the provider can serve it from its prompt cache.
    // What changes on every turn goes after it.
    system: `${FIXED}\n\nToday is ${new Date().toISOString().slice(0, 10)}. The visitor is ${visitorName}.\n\n${passages.join('\n\n')}`,
    messages: [{ role: 'user', content: question }],
    cache_ttl: 0,
  })
}
```

Put everything that never changes first: the role, the rules, the tool
guidance. Put what changes on every turn after it: the date, who the person
is, the passages from search. A product in production that ordered its prompt
this way served 64 to 98 percent of its input from the provider's cache. A
date on the first line would have made it zero.

`usage.cached_input_tokens` on each answer says how much was served from the
cache. Watch it after any change to the prompt.

## Secrets stay on servers

- An install token and an account key live in your server's secrets: Worker
  secrets, a secrets manager, an environment variable. Never in a browser
  bundle, a mobile app, `wrangler.toml` `vars`, a repository, or a log line.
- A browser talks to your backend, and your backend to Omazy. That includes
  live speech: relay it, as [Speech](/build-on-omazy/speech/#relay-from-a-browser)
  shows.
- Customers' tokens are stored encrypted, as
  [Many customers](/build-on-omazy/many-customers/#keep-each-token-encrypted) shows.
- Every endpoint of yours that calls Omazy checks that the caller is a
  signed-in user of yours. Omazy's rate limit protects Omazy. It does not stop
  a stranger spending your budget through your own endpoint.
- Log the token's prefix (`cai_` and the twelve characters after it), never
  the token.

## Measure the first-token time

For anything a person waits on, the number that matters is the time to the
first word, not the time to the whole answer. Stream, and record both.

```ts
export async function timed(question: string) {
  const started = performance.now()
  let firstToken: number | undefined
  let text = ''
  // A client of its own for this turn, so o.last is this stream's response.
  await omazy.withResponse(async (o) => {
    for await (const ev of o.ai.stream({ messages: [{ role: 'user', content: question }] })) {
      if (ev.type === 'delta') {
        firstToken ??= performance.now() - started
        text += ev.text
      } else {
        console.log(
          JSON.stringify({
            evt: 'omazy_turn',
            first_token_ms: Math.round(firstToken ?? -1),
            total_ms: Math.round(performance.now() - started),
            request_id: o.last.requestId,
            cached_input_tokens: ev.result.usage.cached_input_tokens,
            input_tokens: ev.result.usage.input_tokens,
            cache_hit: ev.result.cache_hit ?? false,
          }),
        )
      }
    }
  })
  return text
}
```

What a product in production measured, and what it learned:

- The model's first token, about one second, is the floor of a turn.
- A smaller model was not faster to the first token.
- What helped was removing model rounds: fetching what a tool would fetch
  before the call, and answering common questions straight from a template
  without a model at all.
- Every network call inside a turn adds to the wait. Knowledge searched from
  a local copy first (see [Knowledge](/build-on-omazy/knowledge/#a-local-copy-searched-first))
  took one call out of most turns.

Log `requestId` beside the timings. When a turn is slow, it is what lets Omazy
find the call.

## Before launch

- [ ] Each token has only the scopes its code calls.
- [ ] Every write that matters has an idempotency key made from your own ids.
- [ ] `cache_ttl: 0` on every request with live data.
- [ ] The fixed part of each prompt comes first.
- [ ] `PLAN_LIMIT_REACHED`, `PAYMENT_REQUIRED` and `WORKSPACE_INACTIVE` hide the feature instead of failing on every click.
- [ ] `requestId` is in every error log.
- [ ] `tokenIsPrevious` raises an alert.
- [ ] No token in a browser, an app, a repository or a log.
- [ ] First-token time is recorded per request.
