Add Four Cost Guards to a Streaming Next.js AI Route with Upstash Redis (Step by Step)
DEV Community

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. 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:

Finished demo: ai-cost-guard.devya.dev. Open it in two tabs and send a message from both. The second tab is refused with 429 too_many_streams. A mock model sits behind it, so experimenting costs nothing, but every guard is live.

Repo: github.com/eng-AhmedMahmoud/nextjs-ai-cost-guard

What you'll build

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:

  • Request limit - Scripts and bursts hitting the route
  • Daily token budget - A few large requests that each use the full output allowance
  • Stream slots - One person streaming long answers in several tabs at once
  • Spend breaker - Lots of accounts, each within its own limits, adding up to more than you budgeted

The last three run inside a single Lua script on Upstash Redis, so admission is one round trip and all-or-nothing.

Prerequisites

A Next.js App Router project with a streaming route on AI SDK 7. The demo runs Next.js 16.

Node 20.9 or newer. I use pnpm; any package manager works.

An Upstash account (the console gives you a free database).

Docker, only if you want to run the tests offline in step 8.

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 ( ) ;
}

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

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

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.

Create lib/redis.ts:

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 ) , } ) ;

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" ;

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 ) } } , ) ;
}

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
}

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:

  • Slow Redis: once timeout elapses (5 seconds by default, 1.5 seconds here), limit() resolves with success: true and reason: "timeout". The request is let through.
  • Refused connection: limit() throws. The timeout option doesn't cover errors.

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.

The network limit runs before the user limit because a user id is only as trustworthy as whatever issues it, and anonymous cookies are easy to churn. For identity strategies and algorithm choice, see my earlier post on rate limiting in the Next.js App Router.

Step 3: Reserve the token budget in one Lua round trip

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[1]) local slotTtl= tonumber(ARGV[2]) local maxSlots = tonumber(ARGV[3]) local leaseId= ARGV[4] local reserve= tonumber(ARGV[5]) local limit= tonumber(ARGV[6]) local budgetTtl = tonumber(ARGV[7]) local softCap= tonumber(ARGV[8]) local hardCap= tonumber(ARGV[9]) local spend = tonumber(redis.call('GET', KEYS[3]) or '0') local used= tonumber(redis.call('GET', KEYS[2]) or '0') if spend >= hardCap then return {3, limit - used, spend, 0} end redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - slotTtl) if redis.call('ZCARD', KEYS[1]) >= 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[2], reserve) if total == reserve then redis.call('EXPIRE', KEYS[2], budgetTtl) end redis.call('ZADD', KEYS[1], now, leaseId) redis.call('PEXPIRE', KEYS[1], 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[1], ARGV[1]) local delta = tonumber(ARGV[2]) local used = tonumber(redis.call('GET', KEYS[2]) or '0') if delta ~= 0 then used = redis.call('INCRBY', KEYS[2], delta) if used < 0 then redis.call('SET', KEYS[2], 0, 'KEEPTTL') used = 0 end end local cost = tonumber(ARGV[3]) local spend = tonumber(redis.call('GET', KEYS[3]) or '0') if cost > 0 then spend = redis.call('INCRBY', KEYS[3], cost) if spend == cost then redis.call('EXPIRE', KEYS[3], tonumber(ARGV[4])) end end return {used, spend} ` ;
export const admitScript = redis . createScript < [ number , number , number , number ] > ( ADMIT ) ;
export const settleScript = redis . createScript < [ number , number ] > ( SETTLE ) ;

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}` , } ;
}

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 { [ c
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.