Add Four Cost Guards to a Streaming Next.js AI Route with Upstash Redis (Step by Step)
This tutorial is sponsored by Upstash . What to write about, how to approach it and what to think of it were all my calls. Each behaviour described below is covered by a test that ran against a real Upstash database. You have a chat route that calls streamText and streams the answer to the browser.

This tutorial is sponsored by Upstash. What to write about, how to approach it and what to think of it were all my calls. Each behaviour described below is covered by a test that ran against a real Upstash database.
You have a chat route that calls streamText and streams the answer to the browser. It works, and it has no idea what any single response costs. This tutorial bolts that awareness on in eight steps, without rewriting the route.
If you read my notes on streaming AI responses in Next.js, your route already stops the model when someone closes the tab. The open question is how much it may spend while the tab stays open.
All the code comes from a small open-source app, so you can check your work against something that runs:
One function, admitChat(), runs before the model call. It either refuses the request with a 429 or 503 and a Retry-After header, or it returns a lease. The lease holds a worst-case token reservation and a stream slot. When the stream ends, lease.settle() replaces the reservation with the real usage, frees the slot and adds the request's cost to a daily spend counter.
Four guards, because model providers charge per token and a per-minute request cap can't see tokens:
The last three run inside a single Lua script on Upstash Redis, so admission is one round trip and all-or-nothing.
Here's the kind of route this tutorial starts from:
// app/api/chat/route.ts (before) import { convertToModelMessages, streamText, type UIMessage } from "ai"; export async function POST ( req: Request ) { const { messages } = ( await req. json ( ) ) as { messages: UIMessage [ ] }; const result = streamText ( { model: "anthropic/claude-sonnet-5.5", messages: await convertToModelMessages ( messages ), abortSignal: req. signal, } ); return result. toUIMessageStreamResponse ( ); } Enter fullscreen mode Exit fullscreen mode Step 1: Create the database and a client that fails fast Create a Redis database in the Upstash console. Put it in the same region as your functions; that choice matters more for latency than anything in the code below. Copy the REST URL and token into.env.local:
UPSTASH_REDIS_REST_URL = UPSTASH_REDIS_REST_TOKEN = # Optional: lets one database host several apps or test runs GUARD_PREFIX = aiguard Enter fullscreen mode Exit fullscreen mode Install the two SDKs. Pin the rate limiter to the version the tests in this post ran against:
pnpm add @upstash/redis @upstash/ratelimit@2.2.3 Enter fullscreen mode Exit fullscreen mode Side note for anyone working with coding agents: Upstash can give an agent a temporary database from a single POST request, no sign-up needed. It lasts three days unless you claim it in the console. This project's first test runs used one.
import { Redis } from "@upstash/redis"; export const redis = new Redis ( { url: process. env. UPSTASH_REDIS_REST_URL!, token: process. env. UPSTASH_REDIS_REST_TOKEN!, retry: { retries: 1, backoff: ( ) => 50 }, signal: ( ) => AbortSignal. timeout ( 2_000 ), } ); Enter fullscreen mode Exit fullscreen mode Out of the box, @upstash/redis retries a failing call five times with exponential backoff, roughly four seconds in all. A background worker can afford that wait. A user staring at a chat box can't, so give it one quick retry and cut every call off at two seconds.
Next, put every number that decides cost in lib/config.ts:
export type Plan = "free" | "pro"; type PlanLimits = { requestsPerMinute: number; dailyTokens: number; // input + output, per UTC day maxConcurrentStreams: number; maxOutputTokens: number; // also the reservation size }; export const PLANS: Record < Plan, PlanLimits > = { free: { requestsPerMinute: 10, dailyTokens: 50_000, maxConcurrentStreams: 1, maxOutputTokens: 1_024 }, pro: { requestsPerMinute: 60, dailyTokens: 1_000_000, maxConcurrentStreams: 3, maxOutputTokens: 4_096 }, }; export type ModelTier = "primary" | "fallback"; // USD per 1M tokens. Example values: replace them with your provider's prices. export const MODELS: Record < ModelTier, { id: string; inputPerM: number; outputPerM: number } > = { primary: { id: process. env. PRIMARY_MODEL??
"anthropic/claude-sonnet-5.5", inputPerM: 3, outputPerM: 15 }, fallback: { id: process. env. FALLBACK_MODEL?? "anthropic/claude-haiku-5.5", inputPerM: 1, outputPerM: 5 }, }; // Global daily spend in micro-dollars (1 USD = 1_000_000). export const SPEND = { softCapMicros: Number ( process. env.
SPEND_SOFT_CAP_USD?? 20 ) * 1_000_000, hardCapMicros: Number ( process. env. SPEND_HARD_CAP_USD??
50 ) * 1_000_000, }; // Match the route's maxDuration (step 4). export const SLOT_TTL_MS = 120_000; export const PREFIX = process. env. GUARD_PREFIX?? "aiguard"; Enter fullscreen mode Exit fullscreen mode Step 2: Add a request limit that fails closed Create lib/guard/index.ts.
Build the limiters at module scope: @upstash/ratelimit keeps an in-memory ephemeralCache of blocked identifiers, and on a warm instance it refuses those repeat offenders without touching Redis at all.
import { Ratelimit } from "@upstash/ratelimit"; import type { LanguageModelUsage } from "ai"; import { MODELS, PLANS, PREFIX, SLOT_TTL_MS, SPEND, type ModelTier, type Plan } from "@/lib/config"; import { redis } from "@/lib/redis"; import { admitScript, settleScript } from "./scripts"; const DAY_TTL_S = 60 * 60 * 48; const perPlan = ( plan: Plan ) => new Ratelimit ( { redis, prefix: `${PREFIX}:rl:${plan}`, limiter: Ratelimit. slidingWindow ( PLANS [ plan ]. requestsPerMinute, "1 m" ), timeout: 1_500, } ); const requestLimiters: Record < Plan, Ratelimit > = { free: perPlan ( "free" ), pro: perPlan ( "pro" ) }; // Coarse per-network limit, checked first. const networkLimiter = new Ratelimit ( { redis, prefix: `${PREFIX}:rl:net`, limiter: Ratelimit. slidingWindow ( 30, "1 m" ), timeout: 1_500, } ); /** Client network key from trusted platform headers; IPv6 keyed on its /64. */ export function networkKey ( headers: Headers ): string { const ip = headers. get ( "cf-connecting-ip" )?? headers. get ( "x-real-ip" )?? headers. get ( "x-forwarded-for" )?. split ( "," ) [ 0 ]?. trim ( )?? "unknown"; return ip. includes ( ":" )? `ip6:${ip.split(":").slice(0, 4).join(":")}`: `ip4:${ip}`; } export type Refusal = { ok: false; status: 429 | 503; reason: "rate_limited" | "too_many_streams" | "token_budget" | "spend_cap" | "guard_unavailable"; message: string; retryAfterSeconds: number; }; const unavailable: Refusal = { ok: false, status: 503, reason: "guard_unavailable", message: "Usage limits are unavailable right now. Try again shortly.", retryAfterSeconds: 5, }; const secondsUntil = ( ms: number ) => Math. max ( 1, Math. ceil ( ( ms - Date. now ( ) ) / 1000 ) ); const secondsUntilUtcMidnight = ( ) => { const d = new Date ( ); return secondsUntil ( Date.
UTC ( d. getUTCFullYear ( ), d. getUTCMonth ( ), d. getUTCDate ( ) + 1 ) ); }; export function refusalResponse ( r: Refusal ) { return Response. json ( { error: r. reason, message: r. message }, { status: r. status, headers: { "Retry-After": String ( r. retryAfterSeconds ) } }, ); } Enter fullscreen mode Exit fullscreen mode Now start admitChat() with the request check:
export async function admitChat ( opts: { userId: string; plan: Plan; estimatedInputTokens: number; network?: string; } ): Promise < { ok: true; lease: Lease; headers: Record < string, string > } | Refusal > { const plan = PLANS [ opts. plan ]; let rl; try { if ( opts. network ) { const net = await networkLimiter. limit ( opts. network ); if ( net. reason === "timeout" ) throw new Error ( "ratelimit timeout" ); if (! net. success ) { return { ok: false, status: 429, reason: "rate_limited", message: "Too many requests from your network.", retryAfterSeconds: secondsUntil ( net. reset ) }; } } rl = await requestLimiters [ opts. plan ]. limit ( opts. userId ); } catch { rl = null; // a refused connection throws } if (! rl || rl. reason === "timeout" ) return unavailable; // success is true on timeout if (! rl. success ) { return { ok: false, status: 429, reason: "rate_limited", message: "Too many requests. Slow down a little.", retryAfterSeconds: secondsUntil ( rl. reset ) }; } //...step 3 continues here } Enter fullscreen mode Exit fullscreen mode Both the catch and the reason check are there because of two behaviours I pinned in tests, run with @upstash/ratelimit 2.2.3, the latest release at the time of writing:
Failing open is a reasonable default for most endpoints, since a flaky dependency shouldn't take your API down with it. An endpoint that spends money on every call deserves the reverse, so this code turns both cases into a 503.
You may be tempted to reuse the rate limiter for tokens: limit(userId, { rate: estimatedTokens }) subtracts n units instead of one. The behaviour tests (same 2.2.3 release) show why that's a poor fit for a budget. Give a limiter 1,000 units, spend 900, then ask for 500. The request is refused, as expected. But with fixedWindow or slidingWindow the refused 500 units are still counted, so the window now shows 0 remaining and a 50-unit request fails too. tokenBucket refuses the 500 without consuming them, leaving 100. Counting refused units makes sense for punishing a hammering client. For a budget it means one oversized request can lock a user out.
There's a second problem: you only learn the real token count when the stream finishes. So the budget works in two moves. At admission, reserve estimated input + maxOutputTokens. At settlement, add actual - reserved, which is almost always negative.
Create lib/guard/scripts.ts. The admit script checks the spend cap, then stream slots, then the budget, and only writes once every check has passed:
import { redis } from "@/lib/redis"; // KEYS: slots zset, token counter, global spend counter // Returns { code, tokensLeft, spendMicros, degraded } // code 0 = admitted, 1 = too many streams, 2 = over budget, 3 = spend cap const ADMIT = ` local now = tonumber(ARGV) local slotTtl = tonumber(ARGV) local maxSlots = tonumber(ARGV) local leaseId = ARGV local reserve = tonumber(ARGV) local limit = tonumber(ARGV) local budgetTtl = tonumber(ARGV) local softCap = tonumber(ARGV) local hardCap = tonumber(ARGV) local spend = tonumber(redis.call('GET', KEYS) or '0') local used = tonumber(redis.call('GET', KEYS) or '0') if spend >= hardCap then return {3, limit - used, spend, 0} end redis.call('ZREMRANGEBYSCORE', KEYS, '-inf', now - slotTtl) if redis.call('ZCARD', KEYS) >= maxSlots then return {1, limit - used, spend, 0} end if used + reserve > limit then return {2, limit - used, spend, 0} end local total = redis.call('INCRBY', KEYS, reserve) if total == reserve then redis.call('EXPIRE', KEYS, budgetTtl) end redis.call('ZADD', KEYS, now, leaseId) redis.call('PEXPIRE', KEYS, slotTtl) local degraded = 0 if spend >= softCap then degraded = 1 end return {0, limit - total, spend, degraded} `; // ARGV: lease id, token delta (may be negative), cost micros, spend key TTL s const SETTLE = ` redis.call('ZREM', KEYS, ARGV) local delta = tonumber(ARGV) local used = tonumber(redis.call('GET', KEYS) or '0') if delta ~= 0 then used = redis.call('INCRBY', KEYS, delta) if used < 0 then redis.call('SET', KEYS, 0, 'KEEPTTL') used = 0 end end local cost = tonumber(ARGV) local spend = tonumber(redis.call('GET', KEYS) or '0') if cost > 0 then spend = redis.call('INCRBY', KEYS, cost) if spend == cost then redis.call('EXPIRE', KEYS, tonumber(ARGV)) end end return {used, spend} `; export const admitScript = redis. createScript < [ number, number, number, number ] > ( ADMIT ); export const settleScript = redis. createScript < [ number, number ] > ( SETTLE ); Enter fullscreen mode Exit fullscreen mode createScript tries EVALSHA first and only sends the full body with EVAL when the server hasn't cached it yet. A refusal returns before anything is reserved, so there's nothing to roll back.
Back in lib/guard/index.ts, add the key helpers:
export const utcDay = ( now = Date. now ( ) ) => new Date ( now ). toISOString ( ). slice ( 0, 10 ); export function keysFor ( userId: string, day = utcDay ( ) ) { return { slots: `${PREFIX}:slots:${userId}`, tokens: `${PREFIX}:tokens:${userId}:${day}`, spend: `${PREFIX}:spend:${day}`, }; } Enter fullscreen mode Exit fullscreen mode Then continue admitChat() where step 2 stopped:
const leaseId = crypto. randomUUID ( ); const reserve = opts. estimatedInputTokens + plan. maxOutputTokens; const keys = keysFor ( opts. userId ); let code: number, tokensLeft: number, spend: number, degraded: number; try { [ code, tokensLeft, spend, degraded ] = await admitScript. exec ( [ keys. slots, keys. tokens, keys. spend ], [ Date. now ( ), SLOT_TTL_MS, plan. maxConcurrentStreams, leaseId, reserve, plan. dailyTokens, DAY_TTL_S, SPEND. softCapMicros, SPEND. hardCapMicros ]. map ( String ), ); } catch { return unavailable; } if ( code === 1 ) { return { ok: false, status: 429, reason: "too_many_streams", message: "Wait for your other response to finish.", retryAfterSeconds: 5 }; } if ( code === 2 ) { return { ok: false, status: 429, reason: "token_budget", message: "Daily token budget reached.", retryAfterSeconds: secondsUntilUtcMidnight ( ) }; } if ( code === 3 ) { return { ok: false, status: 503, reason: "spend_cap", message: "Today's spending limit is reached.", retryAfterSeconds: secondsUntilUtcMidnight ( ) }; } Enter fullscreen mode Exit fullscreen mode The per-day keys carry a 48-hour TTL, so old counters disappear without a cleanup job.
The slot logic is already in the admit script. Each user has a sorted set whose members are lease ids, scored by the time each stream started. Before counting, ZREMRANGEBYSCORE drops any member older than the slot TTL.
That pruning line is what keeps a crash from locking people out. A function that dies mid-stream never reaches its cleanup code, so without an expiry its slot would stay taken until someone deleted the key by hand. Tie the TTL to the longest a healthy stream can live, which is the route's maxDuration. Add this to the route now:
// Keep in step with SLOT_TTL_MS in lib/config.ts. export const maxDuration = 120; Enter fullscreen mode Exit fullscreen mode Free users get one slot and pro users get three. When the set is full the script returns code 1, and the route answers 429 too_many_streams with Retry-After: 5. You can see it in the demo by sending from two tabs, or with its Fire 3 requests at once button.
Per-user limits bound each user. Nothing so far bounds the total. The breaker is a single counter per UTC day, spend:{YYYY-MM-DD}, that every settlement adds to. The admit script reads it first: past the hard cap it returns code 3 and the route sends a 503 until the day rolls over; past the soft cap it sets degraded, which moves new requests onto the fallback model.
Store the counter in integer micro-dollars. A price quoted in USD per million tokens is numerically equal to micro-dollars per token ($3 per million is 3 micro-dollars per token), so the cost never needs a float. Add this to lib/guard/index.ts:
/** Cost in micro-dollars. USD per 1M tokens equals micro-dollars per token. */ export function costMicros ( tier: ModelTier, inputTokens: number, outputTokens: number ) { const m = MODELS [ tier ]; return Math. ceil ( inputTokens * m. inputPerM + outputTokens * m. outputPerM ); } Enter fullscreen mode Exit fullscreen mode Then map the tier to a model in lib/model.ts. The repo's version swaps in a built-in mock model when no AI Gateway credentials are set; the core is one line:
import type { LanguageModel } from "ai"; import { MODELS, type ModelTier } from "@/lib/config"; export function modelFor ( tier: ModelTier ): LanguageModel { return MODELS [ tier ]. id; } Enter fullscreen mode Exit fullscreen mode Know the gap before you rely on it. The breaker compares against spend that has already been committed, so streams in flight can push past the hard cap by up to open streams × one request's maximum cost. Reserving spend at admission, as the budget does with tokens, would close it. I left the bound in place for a breaker.
Finish admitChat() by building the lease. Add these types near the top of the file:
export type Outcome = | { kind: "finished"; usage: LanguageModelUsage } | { kind: "aborted" } | { kind: "failed" }; export type Lease = { id: string; tier: ModelTier; maxOutputTokens: number; reservedTokens: number; tokensLeft: number; settle ( outcome: Outcome ): Promise < void >; done: Promise < void >; }; Enter fullscreen mode Exit fullscreen mode Then the end of admitChat():
const tier: ModelTier = degraded? "fallback": "primary"; let settling: Promise < void > | undefined; let resolveDone!: ( ) => void; const done = new Promise < void > ( ( r ) => ( resolveDone = r ) ); const fullCost = ( ) => costMicros ( tier, opts. estimatedInputTokens, plan. maxOutputTokens ); const lease: Lease = { id: leaseId, tier, maxOutputTokens: plan. maxOutputTokens, reservedTokens: reserve, tokensLeft, done, settle ( outcome ) { settling??= ( async ( ) => { let delta = 0; let cost = 0; if ( outcome. kind === "finished" ) { const { inputTokens: input, outputTokens: output } = outcome. usage; if ( input!== undefined && output!== undefined ) { delta = input + output - reserve; cost = costMicros ( tier, input, output ); } else { cost = fullCost ( ); // no usage reported: keep and charge the reservation } } else if ( outcome. kind === "aborted" ) { cost = fullCost ( ); // partial usage is unknown } else { delta = - reserve; // provider error: refund } try { await settleScript. exec ( [ keys. slots, keys. tokens, keys. spend ], [ leaseId, delta, cost, DAY_TTL_S ]. map ( String ) ); } catch ( err ) { console. error ( "[guard] settle failed", err ); // slot expires on its own } finally { resolveDone ( ); } } ) ( ); return settling; }, }; const headers = { "X-RateLimit-Limit": String ( rl. limit ), "X-RateLimit-Remaining": String ( rl. remaining ), "X-RateLimit-Reset": String ( Math. ceil ( rl. reset / 1000 ) ), "X-Token-Budget-Remaining": String ( Math. max ( 0, tokensLeft ) ), "X-Model-Tier": tier, }; return { ok: true, lease, headers }; Enter fullscreen mode Exit fullscreen mode The??= is the important part. The first call to settle() starts the write, and every later call gets that same promise back. done resolves once the write has landed or failed, which step 7 relies on.
Replace the route from the start of the tutorial with this:
I tested what AI SDK 7 calls for each way a stream can end:
Aborts, missing usage and crashes all lean towards charging too much. Provider errors are the exception: most happen before any text is generated, and billing a user for your provider's outage is worse than under-counting a little.
Two more settings keep this honest in production. after() stops a serverless runtime from freezing before settle reaches Redis. And req.signal only fires on disconnect if the platform forwards it: on Vercel add this vercel.json, and on Cloudflare Workers add enable_request_signal to compatibility_flags in wrangler.jsonc.
{ "functions": { "app/api/chat/route.ts": { "supportsCancellation": true } } } Enter fullscreen mode Exit fullscreen mode Step 8: Test locally with SRH and the smoke script You don't need a cloud database to test. SRH is a container that speaks the Upstash REST API in front of a plain Redis, and the repo's docker-compose.yml runs both:
services: redis: image: redis:7 ports: - "6379:6379" serverless-redis-http: image: hiett/serverless-redis-http:latest ports: - "8079:80" environment: SRH_MODE: env SRH_TOKEN: local_token SRH_CONNECTION_STRING: "redis://redis:6379" depends_on: - redis Enter fullscreen mode Exit fullscreen mode Start it and run the suite against it:
docker compose up -d UPSTASH_REDIS_REST_URL = http://localhost:8079 UPSTASH_REDIS_REST_TOKEN = local_token pnpm test Enter fullscreen mode Exit fullscreen mode The repo has 22 tests. Each run writes under its own key prefix and deletes its keys afterwards. Two files are worth copying into your own project as they are: test/ratelimit-behaviour.test.ts pins the timeout-versus-throw split and how each algorithm treats refused units, and test/stream-callbacks.test.ts pins the callback order above. If a library upgrade changes either, your CI goes red before your billing changes.
Then start the app with the same two variables and run the end-to-end smoke script from another terminal:
UPSTASH_REDIS_REST_URL = http://localhost:8079 UPSTASH_REDIS_REST_TOKEN = local_token pnpm dev BASE_URL = http://localhost:3000 pnpm smoke Enter fullscreen mode Exit fullscreen mode It checks that a finished stream settles to a real count below the 1,024-token reservation and frees its slot, that a second concurrent stream gets 429 too_many_streams, that an aborted stream frees its slot while keeping its reservation, and that an empty body is a plain 400. It reads state from the demo's /api/usage route, so copy that route too if you point it at your own app. The live demo runs on Cloudflare Workers, and the same script runs against it.
You now have a route that refuses bursts, reserves the worst case before it calls the model, caps how many answers one user can stream at once, and shuts itself off when the day's spend runs out, with admission costing a single Redis round trip. I run the identical code locally with next start and in production on Cloudflare Workers.
Compare your version against the repo, and try to break the demo from two tabs. If you wire this into your own route and hit a case the tests don't cover, tell me in the comments.
Upstash docs used for this tutorial: Getting started with Redis · Ratelimit features · Ratelimit algorithms · Scripts and EVAL · Local development with SRH