Dev.to AI ๐Ÿค– Ai ๐Ÿ‘ 0 ๐Ÿ“– 17 min read

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

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:

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:

Guard The problem it handles
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/[email protected]

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:

  1. 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.
  2. 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 {
    [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() };
  }

The per-day keys carry a 48-hour TTL, so old counters disappear without a cleanup job.

Step 4: Cap concurrent streams with slots that expire

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;

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.

Step 5: Add the global spend breaker

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

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

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.

Step 6: Make settle run exactly once

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

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

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.

Step 7: Wire the guards into streamText

Replace the route from the start of the tutorial with this:

import { after } from "next/server";
import { convertToModelMessages, streamText, type UIMessage } from "ai";
import { admitChat, networkKey, refusalResponse } from "@/lib/guard";
import { estimateInputTokens, trimHistory } from "@/lib/estimate";
import { currentUser } from "@/lib/identity";
import { modelFor } from "@/lib/model";

// Keep in step with SLOT_TTL_MS in lib/config.ts.
export const maxDuration = 120;

const SYSTEM = "You are a concise assistant. Answer in at most three short paragraphs.";

export async function POST(req: Request) {
  const { userId, plan } = await currentUser();
  const body = (await req.json().catch(() => null)) as { messages?: UIMessage[] } | null;
  if (!Array.isArray(body?.messages) || body.messages.length === 0) {
    return Response.json({ error: "bad_request", message: "messages must be a non-empty array" }, { status: 400 });
  }
  const messages = trimHistory(body.messages);

  const admission = await admitChat({
    userId,
    plan,
    estimatedInputTokens: estimateInputTokens(messages, SYSTEM),
    network: networkKey(req.headers),
  });
  if (!admission.ok) return refusalResponse(admission);
  const { lease, headers } = admission;

  // settle() runs from stream callbacks, after the response has started.
  // after() keeps the function alive until the Redis write lands.
  after(() => lease.done);

  const result = streamText({
    model: modelFor(lease.tier),
    system: SYSTEM,
    messages: await convertToModelMessages(messages),
    maxOutputTokens: lease.maxOutputTokens,
    abortSignal: req.signal,
    onEnd: ({ totalUsage }) => lease.settle({ kind: "finished", usage: totalUsage }),
    onAbort: () => lease.settle({ kind: "aborted" }),
    onError: () => lease.settle({ kind: "failed" }),
  });

  return result.toUIMessageStreamResponse({ headers });
}

currentUser() should return your session's user id and plan (the demo uses an anonymous cookie). lib/estimate.ts in the repo gives you estimateInputTokens(), about four characters per token plus eight per message, and trimHistory(), which keeps the last 12 messages. Passing maxOutputTokens is not optional: the reservation is only a true worst case if the model can't exceed it.

I tested what AI SDK 7 calls for each way a stream can end:

  • Normal finish: onEnd fires once with totalUsage. The lease charges the real tokens and returns the unused part of the reservation.
  • User presses Stop or closes the tab: onAbort fires and onEnd does not. The whole reservation stays charged, since no usage exists for the partial step.
  • Provider fails mid-stream: onError fires, and then onEnd fires as well. The lease refunds on the first call and ignores the second. Without the ??= guard, this request would be settled twice.
  • The function crashes: nothing fires. The slot ages out after 120 seconds and the reservation stays charged.

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 }
  }
}

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

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

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

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.

What to watch for

  • Every limit() call that protects money needs a reason check and a catch.
  • Test how your algorithm handles refused units before you pass rate.
  • The four-characters-per-token estimate runs low for code and non-Latin text. Many of my users write Arabic; if yours do too, size the reservation with a real tokenizer. Settlement corrects the final number either way.
  • Attach budgets to accounts. Offices share an IP and attackers rotate theirs. The network limit is for slowing abuse, not for billing.
  • Stop can cost a user up to maxOutputTokens of budget. Say so somewhere they'll see it.
  • Count round trips. Each Upstash call is an HTTPS request, which is why the same code runs on Node, Vercel Functions and Cloudflare Workers with no connection pool, and why three checks belong in one script. The only hot key is the global spend counter (one INCRBY per finished request); if it ever bottlenecks, split it into N keys and sum them on read.

Wrap-up

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

๐Ÿ“ฐ Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.