Back to Cloudflare

Put AI Calls Behind Observable Controls

November 5, 2026 Wasil Zafar 28 min read

Plan gateway routing, credentials, budgets, and data handling

Table of Contents

  1. The Gateway Sits Between Your App and Model Providers
  2. Routing and Retries Can Change Cost and Semantics
  3. Cache Keys and Prompt Data Need Explicit Policy
  4. Observability, Limits, and Evaluation Feedback
  5. Design a Gateway Policy for Two Model Providers
  6. Test Provider Failure and Inspect Redacted Usage Evidence

The Gateway Sits Between Your App and Model Providers

A two-person team ships a support assistant that summarizes tickets. The model id is a constant in a Worker, the provider key is a Worker secret, and the retry logic is three lines inside a catch block. A year later the provider starts returning 503 on one request in five. Sending that traffic to a second provider means editing code, redeploying, adding a secret, and rebuilding the cost dashboard. Nobody can answer a simpler question either: what did tenant Acme spend yesterday?

All of those problems come from one design choice — the provider is wired directly into the application. AI Gateway removes that wiring by putting a proxy in the path. Your app sends an ordinary HTTP request; the gateway authenticates the caller, picks an upstream provider, injects the right credential, applies limits and caching, returns the response, and writes a log entry describing what happened.

Four terms matter before configuration. An upstream provider is the service that actually generates tokens. A gateway id is the named configuration object (support-prod) that owns routes, keys, limits, and logs. A route is a named rule that resolves a request to a model, optionally branching on content, budget, or percentage. BYOK means the provider credential is stored on the gateway in Secrets Store instead of shipped from the client.

The cleanest model splits the gateway into two planes. The control plane is configuration: gateways, stored keys, published routes, cache defaults, spend limits. It changes rarely and should be reviewed like code. The data plane is the per-request path: authenticate, resolve the route, check the cache, enforce limits, call the provider, stream back, write the log. Figure 1 traces it, including the two early exits — a cache hit and a limit rejection.

The Gateway Sits Between Your App and Model Providers
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart LR
    APP[Your app] --> AUTH[Gateway auth]
    AUTH --> ROUTE[Route or model]
    ROUTE --> CACHE{Cache hit?}
    CACHE -->|yes| HIT[Cached response]
    CACHE -->|no| LIMIT{Within rate and spend limits?}
    LIMIT -->|no| E429[429 to caller]
    LIMIT -->|yes| CALL[Call selected provider]
    CALL --> PA[(Provider A)]
    CALL -->|"error before output"| PB[(Provider B fallback)]
    PA -->|"first token"| OUT[Stream to caller]
    PB --> OUT
    HIT --> LOG[(Log entry)]
    E429 --> LOG
    OUT --> LOG
    LOG --> OBS[Analytics, Logpush, logId]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class AUTH primary;
    class APP,ROUTE,LIMIT,E429,CALL,OUT,OBS secondary;
    class CACHE,HIT ok;

The value is not the extra hop. It is that the hop is the only place where a model swap is configuration rather than a deploy. Figure 2 makes the boundaries explicit, because most gateway incidents are boundary mistakes.

Where the gateway sits between an application and model providers Three zones: your application, which holds no provider keys; AI Gateway, split into a control plane of routes, keys and limits and a data plane of auth, cache, limits, provider call and logging; and provider APIs. Dashed lines mark the credential boundary and the data boundary, and a log entry is written below the gateway. Your application Worker or server knows a gateway URL and a gateway token holds no provider key AI Gateway Control plane routes, provider keys, limits, cache defaults, log settings Data plane, per request auth, route resolution, cache, rate and spend checks, provider call, retry or fallback, stream back, log write Provider APIs Provider A Provider B and other catalog models produces tokens request call tokens Log entry: prompt, tokens, cost, duration, logId credential boundary data boundary

Your application crosses a credential boundary when it stops holding provider keys. The gateway crosses a data boundary when it forwards prompt text to whichever provider the route chose. What it never does is validate your JSON schema, know whether this caller may see this ticket, or make a vague prompt precise.

Routing and Retries Can Change Cost and Semantics

A retry looks like a reliability feature. It is also a cost and semantics decision: it multiplies how many times you may be billed, how long a caller waits, and — when a fallback swaps models — which model actually answered. The failure mode is not that retries do nothing. It is that they succeed quietly, at a different price and with a different answer than the code expects.

Take one feature: summarize a support ticket in a sentence. With maxAttempts: 2 and an 8-second first-byte timeout, one logical call can consume 16 seconds before the caller sees anything. Add two fallback models with the same policy and the worst case is 48 seconds. Those numbers are not a benchmark; they are the policy you wrote. Spend stacks the same way: a response the provider generated but your client never received is still billable.

The table separates the layers, because "we have retries" usually means three different things in one codebase.

MechanismWhere it executesFailure it absorbsWhat it changes without telling you
SDK or client retryYour Worker or serverNetwork blips, connection resets, some 5xxAttempt count and latency; can duplicate non-idempotent side effects such as a tool call
Gateway retry (cf-aig-max-attempts)AI Gateway, before the response reaches youProvider 5xx, 429, and first-byte timeoutUp to five upstream attempts with constant, linear, or exponential backoff; every completed attempt is billable
Model fallback (fallback in agents/models/ai-sdk)Your Worker, across modelsVendor rejection, or a stream failing before its first output partModel identity, output style, JSON adherence, prompt-cache behavior, and per-token price
Dynamic route fallbackAI Gateway, inside a published routeA condition or budget node routing away from the primaryWhich model the route picked, visible as the step metadata field
Provider-internal retryThe providerIts own transient faultsNothing visible; it appears as latency, not as a retry

One retry owner per hop

If the gateway retries twice and the SDK retries twice, one user action becomes four upstream attempts, and your error-budget math is wrong by a factor of four. Choose the layer that sees the failure you care about and disable retries elsewhere.

Two features share the name fallback but not the implementation. The boundary decides which request shapes work and where the evidence appears.

BoundaryGateway dynamic routeWorker fallback option
Runs inAI Gateway, inside a published routeYour Worker, through ai() in agents/models/ai-sdk
Request shapesOpenAI chat-completions only; Anthropic Messages returns 400, and /ai/run returns 400 with code 7003Provider-native endpoints, across models
ScopeOne gateway; a REST call without cf-aig-gateway-id resolves against the default gateway or returns 404The model objects the Worker builds
TriggerA condition or budget node routes away from the primaryVendor rejection, or a stream failing before its first output part
EvidenceThe step metadata fieldproviderMetadata plus your own logs
After the first tokenNo replayNo replay

The fallback option on ai() is a Worker feature, not a gateway feature.

Fallback stops at the first token

Once a model has produced output, its answer is final, errors included. A stream that dies after the first chunk returns as a broken stream, not replayed elsewhere. Stitching two models' tokens would be incoherent, but your client still needs a visible error path.

Figure 3 shows both branches.

Routing and Retries Can Change Cost and Semantics
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    participant C as Client
    participant G as Gateway
    participant A as Provider A
    participant B as Provider B
    C->>G: chat completion request
    G->>G: authenticate, cache MISS, limits OK
    G->>A: attempt 1
    A-->>G: 503 before first token
    G->>A: attempt 2 after backoff
    A-->>G: first-byte timeout
    G->>B: fallback call
    B-->>G: 200 and stream
    G-->>C: stream, cf-aig-step 1
    Note over C,B: Post-output failure is different.
    B-->>G: partial stream
    G-->>C: partial stream
    B--xG: stream error after first token
    G-->>C: error, no fallback

Gateway tokens are account-scoped

A gateway centralizes keys, and that centralization has a sharp edge: the AI Gateway Run permission cannot be restricted to one gateway. Any token with that permission can call every gateway in the account, including gateways holding stored provider keys, and therefore spend those credentials. For tenant or environment isolation, use separate Cloudflare accounts or a Worker-side binding — a narrower token is not an option.

Storage is otherwise sensible. BYOK keys live in Secrets Store, are named {gateway_id}_{provider_slug}_{alias}, and default to the alias named default, with cf-aig-byok-alias selecting another. The gateway substitutes a stored key only when the provider authorization header is absent; an invalid value there produces a provider authentication error rather than a silent override.

Availability claims should stay narrow. Analytics, caching, and rate limiting are documented as free on all plans; DLP is free; Guardrails is billed as Workers AI inference; Unified Billing adds a 5% fee on purchased credits. Log retention depends on when the account created its first gateway. Those are the state of the documentation on 2026-11-05, not timeless facts.

The code below sets a two-attempt retry, a first-byte timeout, a three-model fallback chain, a ticket-scoped cache key, and tenant metadata, then reads the gateway's evidence back out of the result.

import { CloudflareAIError, createAI } from "agents/models/ai-sdk";
import { generateText } from "ai";

interface Env {
  AI: Ai;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const ticketId = url.searchParams.get("ticket") ?? "unknown";
    const tenant = url.searchParams.get("tenant") ?? "unknown";

    // Gateway defaults: one gateway, one cache TTL, one metadata tag.
    const ai = createAI({
      binding: env.AI,
      id: "support-prod",
      cacheTtl: 300,
      metadata: { app: "support-bot" },
    });

    // Per-model policy: bounded retries, a first-byte timeout, ordered fallbacks.
    const model = ai("anthropic/claude-opus-4.7", {
      fallback: ["openai/gpt-5.5", "@cf/zai-org/glm-4.7-flash"],
      requestTimeoutMs: 8_000,
      retries: { maxAttempts: 2, retryDelayMs: 500, backoff: "exponential" },
    });

    try {
      const result = await generateText({
        model,
        prompt: `Summarize ticket ${ticketId} in one sentence.`,
        providerOptions: {
          cloudflare: {
            // Scope the key to this ticket and prompt version, never to the feature.
            cacheKey: `ticket-summary:v3:${ticketId}`,
            metadata: { tenant, ticket: ticketId },
            eventId: `ticket-${ticketId}`,
          },
        },
      });

      const gw = result.providerMetadata?.cloudflare;
      console.log(
        JSON.stringify({
          model: gw?.model,
          cache: gw?.cacheStatus,
          step: gw?.step,
          logId: gw?.logId,
          eventId: gw?.eventId,
        }),
      );

      return Response.json({ summary: result.text, model: gw?.model });
    } catch (error) {
      if (error instanceof CloudflareAIError) {
        console.error(
          JSON.stringify({
            code: error.code,
            status: error.status,
            logId: error.logId,
            failedAttempts: error.attempts?.length ?? 0,
          }),
        );
      }
      return Response.json({ error: "all_models_failed" }, { status: 502 });
    }
  },
};
 # Send one request with an explicit retry, timeout, and cache policy.
curl -sS -D headers.txt -o body.json \
  -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "cf-aig-cache-key: ticket-summary:v3:1042" \
  -H "cf-aig-cache-ttl: 300" \
  -H "cf-aig-max-attempts: 2" \
  -H "cf-aig-retry-delay: 500" \
  -H "cf-aig-backoff: exponential" \
  -H "cf-aig-request-timeout: 8000" \
  -H 'cf-aig-metadata: {"tenant":"acme","ticket":"1042"}' \
  --data '{"model":"anthropic/claude-opus-4.7","messages":[{"role":"user","content":"Summarize ticket 1042 in one sentence."}]}'

 # Read back the gateway's own evidence for that single call.
grep -iE 'cf-aig-(step|cache-status|log-id|request-id)' headers.txt

 # Repeat the exact request; a warm cache should now report HIT.
curl -sS -D headers-again.txt -o /dev/null \
  -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "cf-aig-cache-key: ticket-summary:v3:1042" \
  -H "cf-aig-cache-ttl: 300" \
  --data '{"model":"anthropic/claude-opus-4.7","messages":[{"role":"user","content":"Summarize ticket 1042 in one sentence."}]}'

grep -i 'cf-aig-cache-status' headers-again.txt

Cache Keys and Prompt Data Need Explicit Policy

Caching is where gateway configuration becomes a data-sharing decision. By default the cache key is a SHA-256 hash of provider, endpoint, model, the provider authentication header, and the full request body — exact match. Change one character of the system prompt, add a tool definition, bump temperature, or reorder two messages, and you get a different entry. That is safe, and it is why the hit rate is low for anything dynamic.

The cf-aig-cache-key header replaces that hash entirely. Requests sharing a custom key share the stored response, whatever their bodies say. It is the most dangerous knob in the product, and the documentation says so: choose a key that groups only requests with equivalent responses. A key like support-answer-v2 groups every tenant's question into one bucket, and the first caller's answer is served to everyone else for the TTL. No attacker is required; a well-meaning optimization produces cross-tenant leakage.

That is the realistic form of "cache poisoning" here. It is rarely injected content; it is an operator collapsing the key space, or a cached response outliving the context that made it correct. Three variants:

  • Key collapse. One key for a whole feature, so different users, documents, and locales share one answer.
  • Stale context. The key omits a variable that changes the right answer, such as plan tier or document version. The TTL, not the data, decides when it becomes true again.
  • Policy drift. A DLP or Guardrails policy changes while responses are cached. Cache hits skip DLP scanning, so old content is served until expiry; the fix is cf-aig-skip-cache.

The cache is volatile. Two identical requests arriving together can both miss, because the first response is not stored yet. A cache is a cost optimization, not a lock.

Limits are bounded. TTL runs from 60 seconds to one month, with a 25 MB cap on cacheable request size, and a custom key with no TTL and no gateway default lives five minutes. The cf-aig-cache-status response header is the ground truth for any cache claim in a design review, returning HIT or MISS.

Logging is on by default. Three questions decide what is stored.

QuestionControlBehavior
Is an entry written?cf-aig-collect-logfalse drops the entry; true keeps it. Logging is on by default.
Are raw bodies stored?cf-aig-collect-log-payloadKeeps metadata and drops prompt and response bodies. Ignored when the entry is off.
What does an entry hold?—Prompt, response, provider, model, timestamp, status, token usage, estimated cost, duration, and client user agent.

Three consequences belong in a design document, not an audit:

  1. Prompts are data. Customer text, retrieved documents, and tool arguments land in log storage unless payloads are suppressed. Metadata is data too: user_id and tenant are personal information in most jurisdictions.
  2. Per-request headers do not govern Logpush. They control what AI Gateway stores; exports follow their own configuration, so an excluded request can still leave through an export job.
  3. Retention is cohort-dependent. Accounts whose first gateway was created on or after 24 September 2026 use Workers Logs pricing and retention; earlier accounts use Legacy Logs. Quoting a number without the cohort spreads stale documentation.

Guardrails are not validation. The word invites a category error. Guardrails intercept prompts and responses and classify them for harmful content — violence, hate, sexual content — then flag or block. The evaluation runs on a Workers AI model, so it is probabilistic, adds latency, and is billed as inference. DLP is another layer: profile-based detection of sensitive data such as financial identifiers.

Neither validates your contract. A guardrail pass says nothing about whether the JSON matches your schema, whether priority is one of three allowed values, whether the cited ticket belongs to this user, or whether the summary's total matches the database. Those checks are deterministic and unit-testable, and they belong in application code after the model returns. Guardrails reduce harmful content crossing the boundary, DLP reduces sensitive content crossing it, and application validation decides whether the output is usable.

Response scanning has a latency cost: for a streamed request, the gateway buffers the entire response before scanning, so time-to-first-token becomes time-to-last-token. Request-only scanning does not buffer. Because DLP policy is per gateway, mixed latency needs call for separate gateways.

Observability, Limits, and Evaluation Feedback

A log is only useful if you can join it to the request that caused it. Five identifiers cover different scopes: one entry, one logical event, one HTTP request, one distributed trace, and one resumable run. The AI SDK surfaces them under provider metadata.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Gateway evidence record",
  "type": "object",
  "required": ["logId", "verdict"],
  "properties": {
    "logId": { "type": "string" },
    "eventId": { "type": "string" },
    "requestId": { "type": "string" },
    "traceId": { "type": "string" },
    "runId": { "type": "string" },
    "model": { "type": "string" },
    "cacheStatus": { "enum": ["HIT", "MISS"] },
    "step": { "type": "integer" },
    "verdict": { "enum": ["thumbs-up", "thumbs-down", "corrected"] }
  },
  "additionalProperties": false
}
type GatewayEvidence = {
  logId?: string;
  eventId?: string;
  requestId?: string;
  traceId?: string;
  runId?: string;
  model?: string;
  cacheStatus?: "HIT" | "MISS";
  step?: number;
};

// The AI SDK exposes these under providerMetadata.cloudflare.
export function gatewayEvidence(providerMetadata: unknown): GatewayEvidence {
  const gw = (providerMetadata as { cloudflare?: GatewayEvidence } | undefined)
    ?.cloudflare;
  return {
    logId: gw?.logId,
    eventId: gw?.eventId,
    requestId: gw?.requestId,
    traceId: gw?.traceId,
    runId: gw?.runId,
    model: gw?.model,
    cacheStatus: gw?.cacheStatus,
    step: gw?.step,
  };
}

// Keep the gateway record beside the product outcome that judged the answer.
export function recordVerdict(
  providerMetadata: unknown,
  verdict: "thumbs-up" | "thumbs-down" | "corrected",
) {
  console.log(JSON.stringify({ ...gatewayEvidence(providerMetadata), verdict }));
}
 # log-id: one entry; event-id: one logical event; request-id: the HTTP request;
 # trace-id: the distributed trace; run-id: a resumable streamed run.
 grep -iE 'cf-aig-(log-id|event-id|request-id|trace-id|run-id)' headers.txt

 # Store the log id with the outcome that judged the answer.
 LOG_ID=$(awk 'tolower($1)=="cf-aig-log-id:" {print $2}' headers.txt | tr -d '\r')
 printf '{"logId":"%s","verdict":"thumbs-down"}\n' "$LOG_ID"

The pattern is simple and usually skipped: capture the log id in your own structured logs at call time, and record it with any downstream outcome — a thumbs-down, a correction, an escalation. Later it is the only reliable way to retrieve the exact prompt and response behind a bad answer.

Figure 4 contrasts the two states. On the left, a global rate limit and no attribution: one noisy tenant trips it, everyone gets 429, and a retry storm makes it worse. On the right, the same incident with tenant metadata, a per-tenant budget, and a captured log id.

Budget incident without and with gateway attribution Top panel: one global rate limit, no tenant attribution, a 429 for every caller, and a client retry loop that amplifies load. Bottom panel: tenant metadata, a spend limit split by tenant, a 429 scoped to the noisy tenant, a cheaper fallback model, and a log entry whose logId joins to an evaluation sample. Before: one global limit, no attribution All tenants one request stream Gateway 100 req/min, shared 429 to everyone no tenant named Client retry loop amplifies the spike cost rises, cause stays unknown After: tenant metadata, split budget, one log id Request tenant = acme Gateway budget split by tenant logId captured 429 for acme only other tenants served Route to cheaper fallback model Log entry to eval sample, same logId

Three limit types get conflated and behave differently under load.

Rate limiting caps request counts per interval, fixed or sliding. The documentation's example is the clearest explanation: with ten requests per ten minutes, ten calls at 12:09 and ten at 12:11 both succeed under a fixed window because they land in different buckets; a sliding window rejects the second batch because the last ten minutes already hold ten. Use sliding for customer-facing traffic; the boundary is approximate either way.

Spend limits cap dollars, not requests. They scope by model, provider, or metadata key, split by value or filtered by value, up to twenty rules per gateway. When any applicable rule is over budget, the gateway returns 429 before calling the provider.

A budget is a guardrail, not a ledger

Cost is a best-effort estimate from token counts and published pricing, and enforcement is eventually consistent — the current request is recorded after completion, so a concurrent burst can briefly overshoot. Treat a budget as a runaway-spend guardrail, not an accounting record.

Platform quotas are the limits you do not control: ten gateways on free and twenty on paid, five metadata entries per request, a 25 MB cacheable body, four Logpush jobs, and a Unified Billing rate of 200 requests per 60 seconds per gateway, which returns 429 with code 2018 and does not apply to BYOK.

Evaluation is the loop that turns logs into configuration changes, and the tooling status matters: AI Gateway's built-in Evaluations product is documented as deprecated and unsupported for new accounts. The durable pattern is external — sample entries by id, score them against your rubric or a stronger model, store the verdict keyed by logId and prompt version, then change one route variable and re-measure. The gateway records what happened; it cannot judge whether the answer was right.

Design a Gateway Policy for Two Model Providers

This exercise is design-only — it has not been executed. No request was sent to Cloudflare or any provider while writing this article, and no latency, cost, or hit-rate figure below is measured.

Prerequisites. A Cloudflare account, Wrangler authenticated, Node 20 or later, and a Worker with an AI binding. One path is Workers AI; the second can be a paid catalog model through Unified Billing or a stored BYOK key. If neither is available, run the fixture variant and label it a fixture, not hosted validation.

Decide first: a primary model and one cheaper fallback reachable from the same gateway; a per-tenant daily budget and its metadata key; a cache TTL and exactly which variables belong in the key; and a retention choice.

Actions.

  1. Create a gateway named support-prod. Confirm authentication is on; new gateways require it and it cannot be disabled afterward.
  2. Store the provider credential. Via the API, pre-create the secret as support-prod_<provider>_default; runtime lookup depends on the name, not the returned id.
  3. Create a dynamic route named support with a conditional on metadata.tenant, a budget-limit node on the same key, a primary model node, and a fallback node. Publish a version.
  4. Deploy a Worker that calls dynamic/support with tenant and ticket metadata.
  5. Send one request per tenant. Record cf-aig-step, cf-aig-cache-status, and cf-aig-log-id.
  6. Repeat the identical request twice. Expect MISS, then HIT on the third call.
  7. Break the primary deliberately — an invalid BYOK alias, or an unreachable model id — and send again.

Expected observations. Two steps carry the evidence.

  1. Step 6: a cache transition with no provider call on the hit. If not, the bodies differ, the key differs, or the TTL is too short for your cadence.
  2. Step 7: a non-zero step and a successful fallback answer. A 400 or 404 points at request shape or route scope, not the fallback chain.

Failure checks. A request without cf-aig-authorization must fail. A second tenant must not receive the first tenant's cached text — the key-collapse test, and the one most likely to fail with a feature-level key. The budget 429 must be scoped to the noisy tenant. Confirm Logpush is disabled or intentional, because logging headers will not stop an export.

Cost dimensions. Four independent drivers: tokens per attempt (retries and fallbacks multiply attempts), Guardrails tokens if enabled, log storage or Workers Logs ingestion, and the 5% Unified Billing fee. Cache hits remove provider token cost but not log cost.

Cleanup. Delete the route, gateway, Secrets Store entry, Worker and its binding, and any Logpush job. Deleting a stored key immediately breaks every request that depends on it, so check for other references first.

Guided exercise

Design a Gateway Policy for Two Model Providers

Status: design-only. No request is sent to Cloudflare or any provider. Inputs are one authenticated gateway, two model paths, a tenant metadata key, a daily per-tenant budget, a 300-second TTL, and a cache key of tenant plus ticket plus prompt version.

Prerequisites.

  • A Cloudflare account and an authenticated Wrangler session.
  • Node 20 or later, and a Worker with an AI binding.
  • One Workers AI model plus either a paid catalog model or a stored BYOK key.

Run the design.

  1. Publish a support route with a tenant condition, a budget node, a primary model, and a fallback.
  2. Call it with tenant and ticket metadata, using the scoped cache key.
  3. Send the same request three times. The third call should report a HIT.
  4. Break the primary and send a fourth request.

Pass criteria.

  • The third call hits cache with no provider call.
  • The fourth records a non-zero step and a fallback answer.
  • No tenant receives another tenant's text.
  • Every call yields a retrievable log id.

Failure cases. A missing token, a feature-level cache key, a global budget, or Logpush still exporting each fail a different check.

Cleanup. Delete the route, gateway, secret, Worker, and Logpush job.

Test Provider Failure and Inspect Redacted Usage Evidence

The planning baseline is 2026-11-02 and the documentation was re-checked on 2026-11-05. No hosted test was run. What matters is the documented API surface, not an SDK pin: the AI SDK provider, the cf-aig-* header set, and the REST endpoints under the account's AI path.

Pass/fail evidence. Each check has a falsifier, so a failure names the broken assumption.

  • Pass: a request without cf-aig-authorization is rejected. Fail: it succeeds — authentication is off on a legacy gateway, and unauthenticated traffic can inflate log volume.
  • Pass: the second identical request returns HIT with an identical body. Fail: MISS again — bodies differ, the key differs, or the TTL elapsed.
  • Pass: a tenant budget returns 429 for one tenant while another succeeds. Fail: every caller gets 429 — the limit is global.
  • Pass: breaking the primary yields a non-zero step and a fallback answer. Fail: 400 or 404 — request shape, route scope, or a missing cf-aig-gateway-id.
  • Pass: the returned log id resolves to model, provider, tokens, duration, and cache status. Fail: no id, usually because logging was disabled for that request.
  • Pass: a policy change appears immediately after cf-aig-skip-cache: true. Fail: the old answer persists, as expected until TTL expiry.

Self-check.

  1. maxAttempts: 2 at the gateway and fallback: [B, C] in the SDK — worst-case upstream calls? Six: each of the three models can be attempted twice. If the SDK also retries the chain, multiply again. Count attempts across layers, not within one.
  2. An answer is cached for an hour and a DLP policy tightens at minute ten. When does it apply? Not until expiry, because cache hits skip DLP scanning. Invalidate with cf-aig-skip-cache, or shorten the TTL before the rollout.
  3. A model passes Guardrails and returns valid JSON. Is it safe to show? No. Guardrails classify harmful content; JSON validity proves syntax. Authorization, schema conformance, numeric bounds, and grounding remain unchecked.

Unresolved limitations. Dynamic-route budget behavior under concurrency, the interaction between gateway retries and stream resume, and whether every catalog provider honors identical fallback triggers are documentation-derived and were not confirmed against a hosted account. Log retention differs by cohort. Pricing and plan gating change. No latency or cost measurement appears here, because none was taken.

References.

  • AI Gateway overview — https://developers.cloudflare.com/ai-gateway/
  • Caching and the default key recipe — https://developers.cloudflare.com/ai-gateway/features/caching/
  • Dynamic routes — https://developers.cloudflare.com/ai-gateway/features/dynamic-routing/
  • Rate limiting — https://developers.cloudflare.com/ai-gateway/features/rate-limiting/
  • Spend limits — https://developers.cloudflare.com/ai-gateway/features/spend-limits/
  • Request handling: timeouts and retries — https://developers.cloudflare.com/ai-gateway/configuration/request-handling/
  • Fallbacks and cf-aig-step — https://developers.cloudflare.com/ai-gateway/configuration/fallbacks/
  • BYOK and key aliases — https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/
  • Authentication and token scope — https://developers.cloudflare.com/ai-gateway/configuration/authentication/
  • Logging and payload suppression — https://developers.cloudflare.com/ai-gateway/observability/logging/
  • Custom metadata — https://developers.cloudflare.com/ai-gateway/observability/custom-metadata/
  • Analytics and GraphQL — https://developers.cloudflare.com/ai-gateway/observability/analytics/
  • DLP and cache-hit behavior — https://developers.cloudflare.com/ai-gateway/features/dlp/
  • Guardrails — https://developers.cloudflare.com/ai-gateway/features/guardrails/
  • Limits — https://developers.cloudflare.com/ai-gateway/reference/limits/
  • Pricing — https://developers.cloudflare.com/ai-gateway/reference/pricing/
  • AI SDK provider — https://developers.cloudflare.com/agents/models/ai-sdk/
  • Evaluations deprecation — https://developers.cloudflare.com/ai-gateway/evaluations/

Next in the Series

In Build Grounded Retrieval With Vectorize and AI Search, we'll explore Compare a custom retrieval pipeline with managed search.