# Optimization insights

**Last updated:** 2026-11-21T09:54:10-03:00 (UTC-3)

Optimization insights explain what the gateway's cost features did and where more could be saved, with evidence you can check: the sample, the window, the exact approved rate revision behind every dollar, and why a comparison is or is not valid. Flag: `optimization_insights` (default `false`).

They complement the [cost optimization panel](/docs/features/exact-cache/) (savings at today's catalog price) with [approved rates](/docs/features/budgets-and-tpm/#approved-rates) in exact decimal arithmetic and immutable baselines. Every request is priced with the rules that value a single request: the service tier the provider reported, the long-context tier when its input is above the threshold, and cache reads and five-minute and one-hour cache writes at their own prices (see [pricing rules](#pricing-rules)). Nothing here changes a policy, and no figure is a guaranteed or causal saving: these are estimates from approved rates, not provider charges. Provider charges are compared in [provider cost connectors](/docs/features/billing-connectors/).

## Enable it

```yaml
features:
  usage_analytics: true          # required
  optimization_insights: true
quotas:
  rates:                         # approved rates value the effects
    - provider_id: openai
      model: gpt-4.1-mini
      connection: "<hash shown in the console>"
      input_usd_per_million: "0.40"
      output_usd_per_million: "1.60"
      cache_read_usd_per_million: "0.10"   # needed for prompt-cache effects
      cache_write_usd_per_million: "0.50"  # optional: five-minute writes
      cache_write_1h_usd_per_million: "0.80" # optional: one-hour writes
      long_context:                        # optional: the whole request above the threshold
        threshold_tokens: 200000
        input_usd_per_million: "0.80"
        output_usd_per_million: "3.20"
        cache_read_usd_per_million: "0.20"
      service_tiers:                       # optional: tiers the provider may report
        priority: {input_usd_per_million: "0.70", output_usd_per_million: "2.80", cache_read_usd_per_million: "0.18"}
      revision: rev-1
```

The flag is an operator control, applies at runtime and needs PostgreSQL (migration 148 creates `gateway_optimization_baselines`; migration 149 adds the cache counters described below). A model is valued only when its alias has one target and an approved rate for that exact provider, model and connection; otherwise its requests are counted as unpriced, never as zero. Cache writes are known only for requests that `usage_valuation` priced from the answer's own split.

## Pricing rules

Each request is priced in one price set, chosen as for a single request:

| Rule | Behavior |
| --- | --- |
| Service tier | The tier the provider reported (`service_tier` of the answer) selects that tier's approved prices from `service_tiers`. No tier, `default` or `auto` is the standard price. A tier the rate does not approve leaves the request **unpriced**; it is never valued at the standard price. So is a request that asked for a tier its answer did not report (valuation reason `service_tier_unreported`): it is grouped as tier `(unreported)`, which no rate prices. |
| Long context | A request whose input (cache reads and writes included) is **strictly above** `long_context.threshold_tokens` is priced entirely at the long-context prices: input, output, cache reads and writes. At the threshold the standard prices apply. An approved service tier has no long-context price of its own, so a tiered request above the threshold is unpriced, as quota settlement decides it. |
| Cache reads and writes | Reads at `cache_read_usd_per_million`, five-minute writes at `cache_write_usd_per_million` and one-hour writes at `cache_write_1h_usd_per_million`, in the selected price set. A category with tokens and no price is unpriced, never valued as plain input. |

From migration 149 on, usage events record the measured split: `measured_input_tokens` (every input token, cache included, which some dialects leave out of `input_tokens`), `cache_read_tokens`, `cache_write_tokens` (five-minute) and `cache_write_1h_tokens`. The split is recorded only when the valuation priced the request from it (`known`, `text_token_estimate`); a measurement the valuation refused, for example because the answer omitted a cache counter the price requires (`cache_usage_unreported`), proves no zero. They are nullable: older events, and requests without a proven split, keep NULL, which means unknown. When the price set publishes a cache-write price, a served request with unknown writes is counted in `cache_write_unknown_requests` and left out of the prompt-cache value, never assumed to have written nothing; when it publishes none, unknown writes are treated as none, as the rate bills them.

Without a known split the side of the threshold is read from `input_tokens`, which some dialects count without the cache reads: when the threshold lies between `input_tokens` and `input_tokens` plus the reported cache reads, the side is unknown and the request is unpriced at that rate (for the served model, or for the routing candidate).

Requests are aggregated in SQL by model, route, reported tier, the side of each rate's threshold (for the served model and, for a routed request, for the routing candidate) and whether the split is known. The rows stay bounded, and every request of a row has the same prices.

## Measured effects

`GET /api/v1/admin/optimization?from=...&to=...&team=...&baseline_id=...` (RFC 3339, at most 92 days, default the last 30; `team` filters before aggregation) reads successful usage events and returns one row per effect:

| Effect | What is measured | Valued as |
| --- | --- | --- |
| `gateway_cache` | Answers served by the [exact or semantic cache](/docs/features/exact-cache/), which made no provider call | The stored answer's input and output tokens at the model's rate, in the long-context tier when the avoided input is above the threshold |
| `provider_prompt_cache` | Provider-reported cache reads and writes on served requests | **Net**: cache-read tokens × (input price − cache-read price), minus the write premium, five-minute writes × (write price − input price) plus one-hour writes × (one-hour write price − input price), in the request's price set. `gross_savings_usd` and `write_premium_usd` give the two parts; the net is negative when writes outweigh reads |
| `auto_routing` | Served requests of a routed alias | Input and output tokens at the most expensive candidate's price minus the served model's price, at full price, each in the request's reported tier and in its own long-context tier |
| `prompt_compression` | `not_measured` | The removed bytes are not recorded per request; no effect is claimed |
| `reasoning_control` | `not_measured` | Avoided reasoning tokens are not observable; no effect is claimed |

Each request belongs to one class: a cache hit is never also a prompt-cache or routing saving, and a served routed request splits exactly into its routing difference plus its net prompt-cache difference, so the effects add up without double counting. `unpriced_requests` counts requests whose rate, tier or long-context price (or the routing candidate's) is missing or whose cache category has no price, cache hits whose stored answer had no usage, and rows reporting more cache tokens than input; they are excluded from `estimated_usd`. `cache_write_unknown_requests` (prompt-cache effect only) counts every served request whose writes are unknown while the price set prices writes, with or without cache reads, so it can exceed the effect's `requests`; those with reads are in `requests` and excluded from the value.

Routing effects do not measure answer quality. Use [evaluations](/docs/features/evals/) before relying on a cheaper model.

## Baselines

A baseline freezes a window's usage per model, reported tier, long-context side and cache reads and writes, together with the approved rates in force when it was captured (body `version` 2). It cannot be updated, deleted or truncated, and its fingerprint covers its name, team, window and body.

Baselines captured before this version (no body `version`, reported as `body_version` 1) still load and verify unchanged. They recorded no tier, long-context side or cache writes, so their rows are valued only at a frozen rate that approves no service tier, long-context tier or cache-write price; at any other rate their models are `unpriced`. At such a rate a legacy row's tier is assumed standard, as the release that captured it valued it. Capture a new baseline to compare with tiers, long context and writes.

```bash
curl -b "$COOKIE_FILE" -H "X-CSRF-Token: $CSRF" -X POST -H 'Content-Type: application/json' \
  -d '{"name":"before prompt caching","from":"2026-10-01T00:00:00Z","to":"2026-10-31T00:00:00Z"}' \
  http://localhost:8080/api/v1/admin/optimization/baselines
```

| Field | Rules |
| --- | --- |
| `name` | 1-120 characters |
| `from`, `to` | RFC 3339, `from` before `to`, at most 92 days |
| `team` | Optional team ID; a report compared with this baseline must use the same team |

`GET /api/v1/admin/optimization/baselines` lists the last 100 (`id`, `name`, `team`, window, `fingerprint`, `created_at`).

With `baseline_id`, the window must not overlap the baseline's window (`400 window_overlaps_baseline`), and the report values **both** windows at the baseline's rates, so a later price change never shows up as a saving, and adds one row per model:

| `state` | Meaning |
| --- | --- |
| `comparable` | Both windows have at least 50 served requests, priced, with mean input and output tokens per request within ±50%: `baseline_estimated_usd_per_request` and `window_estimated_usd_per_request` are shown |
| `insufficient_sample` | Fewer than 50 served requests in either window |
| `workload_changed` | The mean prompt or answer length moved by more than half: the workload differs and costs are not compared |
| `incomplete` | Some served request in either window has no reported token count, reports more cache tokens than input, or has unknown cache writes while the rate prices writes: it would lower the means and the cost per request without a real saving |
| `truncated` | Either side hit the 2,000-row bound |
| `unpriced` | No approved rate in the baseline, or some request's tier, long-context price or cache category has no approved price |
| `no_baseline` | No baseline selected |

Cost per request includes cache hits at zero provider cost, so it reflects all effects together; served requests are priced with their tier, long-context tier, cache reads and writes. `reconciled` explains why the model's figure is not reconciled with provider charges: provider reports are organization-wide, not per model. Compare per day and provider in [the reconciliation](/docs/features/billing-connectors/#daily-reconciliation).

## Recommendations

`recommendations` lists advisory opportunities, each with its `sample_requests`, `confidence` (`low` from 50 served requests, `medium` from 200), `basis` (which rates), `ceiling_usd`, `prerequisites` and `caveats`. The response always carries `applies_changes: false`.

| Kind | When | Ceiling |
| --- | --- | --- |
| `prompt_cache_underused` | Every served request's price set has a cache-read price, at least 50 served requests, at least 1,024 input tokens per request on average and under 10% of input read from cache | Every input token not already read from or written to the cache valued at the cache-read price instead of the input price, in each request's tier and long-context tier: an upper bound, not an expectation, and without the write premium that filling the cache costs |

## Console

**Budget & TPM → Finance & reconciliation → Optimization insights** shows the effects (with the prompt cache's read savings, write premium and unknown writes), the per-model comparison against a selected baseline and the recommendations. A global administrator can capture a baseline of the 30 days before the default 30-day window, so the two never overlap. The panel lists gateway-wide baselines; team-scoped baselines are used through the API.

## Who can

Reading needs global `quotas:read`; capturing a baseline needs a global administrator with `quotas:manage`, CSRF and same origin, and is audited (`optimization.baseline.create`). Team roles are refused. Responses are `no-store`.

## Limits

- Successful requests only; tokens the provider did not report are left out of the sums.
- At most 2,000 aggregated rows per window (`truncated` says when more exist; figures are then a lower bound).
- Approved rates carry no discount or margin, so none is applied.
- **Upgrade.** Migration 148 creates the baseline table. Migration 149 adds four nullable columns to `gateway_usage_events` with no default, and a check added `NOT VALID`, so the table is neither rewritten nor scanned; existing events keep NULL (unknown). Upgrade every replica before relying on cache-write figures: an older replica records no split, which counts as unknown.

## Admin API routes

Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/).

| Route | What it does |
| --- | --- |
| `GET /api/v1/admin/savings` | What the gateway cache, provider prompt caching and the auto-router saved across every key, or one team's, with the top ten keys |
| `POST /api/v1/admin/optimization/baselines` | Freezes a window's usage and approved rates as a baseline later windows are compared with |
