AI Gateway · Exercise 04

Route and fall back

Move model selection out of your Worker and into a versioned gateway route that branches on metadata, falls back on failure, and updates without redeploying your app.

Route and fall back

Routing requests by team metadata and swapping models in AI Gateway without redeploying the app. Direct video link

When a model name is hardcoded in your application, every model upgrade, tier change, or provider outage requires a code change and a deployment across every service that calls it. Moving model choice into a versioned route in AI Gateway lets the gateway pick the model from request metadata, fall back automatically if a primary model fails, and swap or roll back models without touching your application code.

What you’ll build

A gateway route named dynamic/support that sends interns to a fast economical model and escalations to a larger model with an automatic fallback. Then you’ll deploy a second version of the route and watch the model change with zero Worker redeploy.

Prerequisites

Moving model choice into a route

Instead of naming a specific model in code, your Worker calls "dynamic/support" and passes who’s asking in metadata:

src/index.tsconst result = await env.AI.run(
  "dynamic/support",
  { messages: [{ role: "user", content: prompt }] },
  {
    gateway: {
      id: "dev-school-gateway",
      metadata: { user, team },
    },
  },
);

Inside AI Gateway, the support route replaces the single model provider at the end of the pipeline from Exercise 3 with a versioned decision graph: it checks metadata.team, routes each team to the right model, falls back to a backup model if the primary model fails or times out, and lets you publish a new version of the route without redeploying your Worker:

prompt + metadatatruefalseon error / timeoutYour Workerenv.AI.run('dynamic/support')1. Logs · 2. Cache · 3. Limits4. Route: supportmetadata.team == interns?Gemma 4 26B(swap to Granite in v2)Llama 3.3 70BGPT-OSS 120B (fallback)