DEV Community

Cover image for Rate Limiting and Queuing Long AI Jobs in Next.js with Upstash Redis and QStash
Dumebi Okolo
Dumebi Okolo

Posted on

Rate Limiting and Queuing Long AI Jobs in Next.js with Upstash Redis and QStash

While building Ozigi, an AI content tool, we ran into two problems along the way.

Its main generation endpoint is a single LLM call, and every call cost us money, so we needed a limit in front of it.

That became an Upstash Redis rate limiter: a sliding window of 30 requests per hour. Later we moved Ozigi's background work (scraping, sending, reply checks) onto QStash schedules, and hit the second problem: over 15 days, the scrape job was the only one of ours to time out with a 504.

This post covers what we learned about both: protecting an expensive endpoint and surviving long jobs.

AI features break the assumptions most web handlers are built on. A request that calls an LLM can take tens of seconds, costs real money every time it runs. This is exactly what an abusive client wants to call in a loop. On a serverless platform like Vercel, that creates two separate problems:

  1. Protecting the endpoint. You need to count requests across many short-lived function instances that share no memory.
  2. Surviving the work. The request that starts a long AI job can't also be the thing that finishes it, because functions have a maximum duration and can be retried, cancelled or cold-started at any moment.

Upstash gives you a clean answer to each, and they compose well:

  • Upstash Redis is a shared, low-latency counter store you reach over HTTP. It does the rate limiting, and it can also enforce a concurrency cap.
  • QStash is an HTTP message queue. It accepts a message, then calls your endpoint with retries, delays and signed requests, so you never run a worker process.

In this post we'll build the whole flow in a Next.js (App Router) app deployed on Vercel. Here is how the pieces fit together:

Browser ──POST /api/jobs──▶ [1] rate limit (Redis)
                            [2] concurrency slot (Redis)
                            [3] insert job row (Postgres)
                            [4] publish message (QStash)
        ◀─── 202 {jobId} ───┘

QStash ──POST /api/jobs/worker (signed)──▶ verify signature
                                           claim job atomically
                                           call the model
                                           write result, free slot

Browser ──GET /api/jobs/:id (polling)──▶ status + result
QStash ──POST /api/jobs/failed (after final retry)──▶ mark job failed, free slot
Enter fullscreen mode Exit fullscreen mode

The browser only ever talks to the enqueue and status routes. QStash calls the worker, and calls the failure route once the last retry fails.

All code is TypeScript. The job-queue pattern here comes from the async generation worker we built and tested in Ozigi (an AI content tool), which ran AI jobs through QStash with a separate worker.

Setup

npm install @upstash/redis @upstash/ratelimit @upstash/qstash @supabase/supabase-js
Enter fullscreen mode Exit fullscreen mode

We use Postgres via Supabase for job state because the job record is the source of truth, and it is the only thing that survives a deploy. Any database works.

# .env.local
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=

QSTASH_TOKEN=
QSTASH_CURRENT_SIGNING_KEY=
QSTASH_NEXT_SIGNING_KEY=

APP_URL=https://your-app.vercel.app        # public URL QStash will call
ANTHROPIC_API_KEY=                          # or any model provider

NEXT_PUBLIC_SUPABASE_URL=
SUPABASE_SERVICE_ROLE_KEY=
Enter fullscreen mode Exit fullscreen mode

Create the job table:

create table jobs (
  id               uuid primary key default gen_random_uuid(),
  user_id          uuid not null,
  status           text not null default 'pending'
                   check (status in ('pending','processing','done','error')),
  payload          jsonb not null,
  result           jsonb,
  error            text,
  attempts         int  not null default 0,
  idempotency_key  text,
  created_at       timestamptz not null default now(),
  updated_at       timestamptz not null default now()
);
create index on jobs (user_id, created_at desc);

-- one job per (user, key); rows without a key are not constrained
create unique index jobs_idempotency
  on jobs (user_id, idempotency_key)
  where idempotency_key is not null;
Enter fullscreen mode Exit fullscreen mode

The attempts column matters: it is the only place you will ever see how many times QStash had to retry a job, because the queue doesn't write back to your database.

Shared clients, in one place:

// lib/clients.ts
import { Redis } from "@upstash/redis";
import { Client, Receiver } from "@upstash/qstash";
import { createClient } from "@supabase/supabase-js";

export const redis = Redis.fromEnv();

export const qstash = new Client({ token: process.env.QSTASH_TOKEN! });

export const receiver = new Receiver({
  currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
  nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
});

export const db = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!,
  { auth: { persistSession: false } },
);
Enter fullscreen mode Exit fullscreen mode

Why this stack works on serverless: Upstash Redis is accessed over REST, so each call is a stateless HTTP request rather than a pooled TCP connection that has to be re-established on every cold start. QStash goes the other way, calling your HTTPS endpoint, so there's nothing to keep alive.

Part 1: Rate limiting with Upstash Redis

Two limiters, two jobs

A single limit is not enough for AI endpoints. You want to stop bursts and also bound daily spend, and these need different algorithms:

// lib/limits.ts
import { Ratelimit } from "@upstash/ratelimit";
import { redis } from "./clients";

// Burst control: smooth, fair, no boundary spikes.
export const burstLimiter = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(10, "1 m"),
  prefix: "rl:burst",
  analytics: true,
  timeout: 1500, // fail open if Redis is slow; see below
});

// Spend control: a daily budget of AI jobs per user.
export const dailyLimiter = new Ratelimit({
  redis,
  limiter: Ratelimit.fixedWindow(50, "24 h"),
  prefix: "rl:daily",
  analytics: true,
  timeout: 1500,
});
Enter fullscreen mode Exit fullscreen mode

What each option gives:

  • slidingWindow weights the previous window into the current one, so a client can't send a full quota at the end of one window and another at the start of the next. That is the right choice for burst control.
  • fixedWindow is cheaper and easy to explain to users ("50 per day"). Boundary spikes don't matter much at daily scale.
  • prefix namespaces the keys. Give each limiter its own, or usage on one will count against another.
  • analytics: true records every decision so you can inspect them later. Turn it on for every limiter from the start. We only enabled it on one of ours and can't report on the others.
  • timeout (default 5000 ms) is a deliberate decision about failure mode. If Redis doesn't answer within the timeout, the limiter allows the request. For a product whose revenue depends on availability, failing open is usually right. If a runaway bill is the bigger risk, handle the timeout yourself and fail closed.

@upstash/ratelimit also offers tokenBucket (steady refill with a burst allowance), getRemaining() to read usage without consuming it, blockUntilReady() to wait instead of reject, an ephemeralCache that skips Redis for identifiers that are already blocked on a warm instance, and MultiRegionRatelimit for several databases.

Pick the identifier carefully

The identifier is what you're counting. Use the authenticated user ID whenever you have one. IP addresses are shared by offices and mobile carriers, and are trivial to rotate. Fall back to IP only for anonymous endpoints:

// lib/identify.ts
export function clientIp(req: Request): string {
  const forwarded = req.headers.get("x-forwarded-for");
  return forwarded?.split(",")[0].trim() ?? "anonymous";
}
Enter fullscreen mode Exit fullscreen mode

A helper that turns a result into a proper 429

// lib/limits.ts (continued)
import { NextResponse } from "next/server";

export function tooManyRequests(r: { limit: number; remaining: number; reset: number }) {
  const retryAfter = Math.max(1, Math.ceil((r.reset - Date.now()) / 1000));
  return NextResponse.json(
    { error: "Too many requests", retryAfterSeconds: retryAfter },
    {
      status: 429,
      headers: {
        "Retry-After": String(retryAfter),
        "X-RateLimit-Limit": String(r.limit),
        "X-RateLimit-Remaining": String(r.remaining),
        "X-RateLimit-Reset": String(Math.ceil(r.reset / 1000)),
      },
    },
  );
}
Enter fullscreen mode Exit fullscreen mode

limit() returns { success, limit, remaining, reset }, where reset is a Unix timestamp in milliseconds. That's everything you need for well-behaved clients.

Limiting concurrency, not just rate

Rate limits don't stop one user from starting 10 long jobs at once. The queue will happily run them all in parallel, and with AI work that means a burst of expensive concurrent model calls. Redis makes a concurrency cap easy with an atomic counter:

// lib/concurrency.ts
import { redis } from "./clients";

const MAX_IN_FLIGHT = 3;
const SAFETY_TTL_SECONDS = 15 * 60; // so a crashed job can't hold a slot forever

const key = (userId: string) => `inflight:${userId}`;

export async function acquireSlot(userId: string): Promise<boolean> {
  const n = await redis.incr(key(userId));
  if (n === 1) await redis.expire(key(userId), SAFETY_TTL_SECONDS);
  if (n > MAX_IN_FLIGHT) {
    await redis.decr(key(userId));
    return false;
  }
  return true;
}

export async function releaseSlot(userId: string): Promise<void> {
  const n = await redis.decr(key(userId));
  if (n < 0) await redis.del(key(userId)); // never go negative
}
Enter fullscreen mode Exit fullscreen mode

INCR is atomic, so two simultaneous requests can't both think they took the last slot. The TTL is the safety net: if a worker dies without releasing, the counter eventually clears itself.

What the numbers look like

For a sense of scale: Ozigi's main generation endpoint runs a slidingWindow(30, "1 h") limiter with analytics on. Reading its stored events back (sorted sets named @upstash/ratelimit:events:<hour>) for 13 March to 26 November 2026, excluding local development traffic:

  • 436 requests from 218 unique IP addresses
  • 431 allowed, 5 blocked with a 429 (about 1.1%)

That's a small, low-abuse product, and the low block rate is exactly what a healthy limiter looks like: nearly everyone passes straight through, and the occasional script is capped. You can compute the same figures yourself. Each analytics key is a sorted set whose members are {"identifier":…,"success":bool} and whose scores are counts:

// scripts/ratelimit-stats.ts
import { redis } from "../lib/clients";

let cursor = 0;
let allowed = 0, blocked = 0;
const ids = new Set<string>();

do {
  const [next, keys] = await redis.scan(cursor, {
    match: "@upstash/ratelimit:events:*",
    count: 1000,
  });
  cursor = Number(next);

  for (const key of keys) {
    const rows = (await redis.zrange(key, 0, -1, { withScores: true })) as (string | number)[];
    for (let i = 0; i < rows.length; i += 2) {
      const member = typeof rows[i] === "string" ? JSON.parse(rows[i] as string) : rows[i];
      const count = Number(rows[i + 1]);
      if (/(::1|127\.0\.0\.1)$/.test(member.identifier)) continue; // skip local dev traffic
      member.success ? (allowed += count) : (blocked += count);
      ids.add(member.identifier);
    }
  }
} while (cursor !== 0);

console.log({ total: allowed + blocked, allowed, blocked, uniqueIdentifiers: ids.size });
Enter fullscreen mode Exit fullscreen mode

These keys don't expire by themselves, so add a TTL or cleanup job if you leave analytics on for a long time. And if your identifiers are IPs, "unique identifiers" means unique IPs, not unique people.

Part 2: Queuing the AI job with QStash

The enqueue endpoint

This route does four things quickly and returns. It never calls the model. A request has to pass the burst limit, the daily budget and the concurrency cap before a job is saved and published.

// app/api/jobs/route.ts
import { NextResponse } from "next/server";
import { db, qstash } from "@/lib/clients";
import { burstLimiter, dailyLimiter, tooManyRequests } from "@/lib/limits";
import { acquireSlot, releaseSlot } from "@/lib/concurrency";
import { getUserId } from "@/lib/auth"; // your auth: cookie, bearer token, etc.

export async function POST(req: Request) {
  const userId = await getUserId(req);
  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  // 0. Idempotency: the same key from the same user is the same job.
  //    A replay returns the original job and costs nothing: no rate limit, slot or publish.
  const idempotencyKey = req.headers.get("idempotency-key");
  if (idempotencyKey !== null && (idempotencyKey.length < 8 || idempotencyKey.length > 128)) {
    return NextResponse.json({ error: "Idempotency-Key must be 8 to 128 characters" }, { status: 400 });
  }
  if (idempotencyKey) {
    const { data: existing } = await db
      .from("jobs")
      .select("id")
      .eq("user_id", userId)
      .eq("idempotency_key", idempotencyKey)
      .maybeSingle();
    if (existing) return NextResponse.json({ jobId: existing.id, replayed: true });
  }

  // 1. Rate limits (burst, then daily budget)
  const burst = await burstLimiter.limit(userId);
  if (!burst.success) return tooManyRequests(burst);

  const daily = await dailyLimiter.limit(userId);
  if (!daily.success) return tooManyRequests(daily);

  // 2. Concurrency cap
  if (!(await acquireSlot(userId))) {
    return NextResponse.json(
      { error: "You already have the maximum number of jobs running." },
      { status: 429, headers: { "Retry-After": "30" } },
    );
  }

  // 3. Validate, then persist the job *before* queueing it
  const payload = await req.json();
  if (typeof payload?.prompt !== "string" || payload.prompt.length > 8000) {
    await releaseSlot(userId);
    return NextResponse.json({ error: "Invalid prompt" }, { status: 400 });
  }

  const { data: job, error } = await db
    .from("jobs")
    .insert({ user_id: userId, payload, idempotency_key: idempotencyKey })
    .select("id")
    .single();

  if (error?.code === "23505" && idempotencyKey) {
    // Two identical requests raced past the check above. The unique index let one
    // insert win; this one hands back the winner's job instead of creating a second.
    await releaseSlot(userId);
    const { data: winner } = await db
      .from("jobs")
      .select("id")
      .eq("user_id", userId)
      .eq("idempotency_key", idempotencyKey)
      .maybeSingle();
    if (winner) return NextResponse.json({ jobId: winner.id, replayed: true });
  }

  if (error || !job) {
    await releaseSlot(userId);
    return NextResponse.json({ error: "Could not create job" }, { status: 500 });
  }

  // 4. Hand it to QStash
  try {
    await qstash.publishJSON({
      url: `${process.env.APP_URL}/api/jobs/worker`,
      body: { jobId: job.id },
      retries: 3,
      retryDelay: "5000 * (1 + retried)", // 5s, 10s, 15s
      deduplicationId: job.id,
      failureCallback: `${process.env.APP_URL}/api/jobs/failed?jobId=${job.id}`,
    });
  } catch (e) {
    await db.from("jobs").update({ status: "error", error: "enqueue_failed" }).eq("id", job.id);
    await releaseSlot(userId);
    return NextResponse.json({ error: "Could not queue job" }, { status: 502 });
  }

  return NextResponse.json({ jobId: job.id }, { status: 202 });
}
Enter fullscreen mode Exit fullscreen mode

Design choices in this model:

  • The database row comes first. If the QStash publish fails, you have a row you can mark as errored. If you published first and the insert failed, a worker would run with nothing to load.
  • Only the job ID travels in the message. The prompt can be large or sensitive, and the database is the right home for it. The message stays tiny.
  • deduplicationId tells QStash to drop a second publish with the same ID within a 10-minute window (deduplication docs). Because the ID here is the new job's own ID, it only protects against publishing the same job twice, for example if your code retries the publish call. It does not catch a client that sends the same request twice, because each request would create a new row with a new ID. The idempotency key described below handles that case.
  • retries: 3 is the number of additional attempts if your worker returns a non-2xx response, so a job gets up to 4 deliveries. Your plan may cap the maximum number of retries (the @upstash/qstash type documentation says so, so check your plan's limits; see also the retry docs).
  • retryDelay is worth setting explicitly. When we ran this against QStash's local server with no retryDelay, a consistently failing job was retried after about 11 seconds, then about 156 seconds, then about 1,800 seconds. With retries: 3 that is roughly 33 minutes before the job finally fails, and the user sees a spinner the whole time. The value is an expression in milliseconds, and "5000 * (1 + retried)" gave retries at 5, 10 and 15 seconds, with the whole sequence finishing in about 30 seconds. Pick delays that suit your model provider's rate limits. The @upstash/qstash type documentation also says a Retry-After header on a failed response overrides retryDelay. We did not test that, and the web retry docs don't mention it, so treat it as unconfirmed.
  • failureCallback is called once all retries are exhausted. The job ID is in the URL so you don't depend on parsing the callback payload.
  • Every early exit releases the slot. Leaking a slot locks the user out until the TTL expires, so treat acquire and release like a pair.

Making double-submits harmless

A user who double-clicks, or a client that retries after a timeout, sends the same request twice. Without help, that creates two jobs and spends twice. The fix is an idempotency key: the client generates one random value per user action and sends it as an Idempotency-Key header, reusing it on every retry of that action.

// client: one key per user action, reused on every retry of that action
const key = crypto.randomUUID();

const res = await fetch("/api/jobs", {
  method: "POST",
  headers: { "content-type": "application/json", "idempotency-key": key },
  body: JSON.stringify({ prompt }),
});
Enter fullscreen mode Exit fullscreen mode

The route above does three things with it:

  • Replays are free. If a job already exists for this user and key, the route returns that job's ID with replayed: true before it touches the rate limiter, the concurrency counter or QStash.
  • Races are settled by the database. Two identical requests can both pass the check at the same moment. The unique index lets exactly one insert succeed. The other gets a 23505 error, frees its slot, and returns the winner's job.
  • It has no time limit. QStash's own deduplication only covers a 10-minute window, and the key here is a client value, not the job ID. The unique index remembers the key for as long as the row exists.

We tested this against QStash's local server with an in-memory stand-in for the database. Sending the same key twice in a row returned the same job ID with one model call. Five simultaneous requests with one key produced a single job and a single model call. 25 replays all returned 200, so they used none of the rate-limit budget. The same key from a different user created a separate job.

Verifying that a request really came from QStash

The worker URL is public. Anyone who finds it could post to it, so every request must be verified against the QStash signature. Read the raw body first. The signature is computed over the exact bytes, and parsing then re-serialising changes them.

// lib/verify.ts
import { receiver } from "./clients";

export async function verifyQStash(req: Request, rawBody: string): Promise<boolean> {
  const signature = req.headers.get("upstash-signature");
  if (!signature) return false;
  try {
    return await receiver.verify({ signature, body: rawBody });
  } catch {
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

The receiver takes two signing keys so you can rotate keys without downtime, since it accepts either.

The worker

The worker is where QStash's at-least-once delivery bites. A message can arrive twice (a retry after a timeout whose response you never sent, for example), so the handler must be idempotent. The most reliable way is an atomic claim: a single UPDATE … WHERE status = 'pending' that only one invocation can win.

// app/api/jobs/worker/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/clients";
import { verifyQStash } from "@/lib/verify";
import { releaseSlot } from "@/lib/concurrency";
import { runAiTask } from "@/lib/ai";

// Set this as high as your plan allows. The queue exists so you are not
// betting a user's request on this number, but each attempt still has to fit.
export const maxDuration = 60;

export async function POST(req: Request) {
  const rawBody = await req.text();
  if (!(await verifyQStash(req, rawBody))) {
    return new Response("Unauthorized", { status: 401 });
  }

  const { jobId } = JSON.parse(rawBody) as { jobId?: string };
  if (!jobId) return new Response("Bad request", { status: 400 });

  // Atomic claim: only one invocation can move pending -> processing.
  const { data: job } = await db
    .from("jobs")
    .update({ status: "processing", updated_at: new Date().toISOString() })
    .eq("id", jobId)
    .eq("status", "pending")
    .select("id, user_id, payload, attempts")
    .maybeSingle();

  if (!job) {
    // Already claimed, finished, or failed. Acknowledge so QStash stops retrying.
    return NextResponse.json({ skipped: true });
  }

  await db.from("jobs").update({ attempts: job.attempts + 1 }).eq("id", job.id);

  try {
    const output = await runAiTask(job.payload.prompt);

    await db
      .from("jobs")
      .update({ status: "done", result: { output }, updated_at: new Date().toISOString() })
      .eq("id", job.id);

    await releaseSlot(job.user_id);
    return NextResponse.json({ ok: true });
  } catch (err) {
    const message = err instanceof Error ? err.message : "unknown error";

    if (isPermanent(err)) {
      // Retrying won't help (bad input, content refused). Mark failed and ACK.
      await db
        .from("jobs")
        .update({ status: "error", error: message, updated_at: new Date().toISOString() })
        .eq("id", job.id);
      await releaseSlot(job.user_id);
      return NextResponse.json({ ok: false, permanent: true });
    }

    // Transient failure (timeout, 429, 5xx). Put the job back so the retry
    // can claim it, then return 500 so QStash retries with backoff.
    await db
      .from("jobs")
      .update({ status: "pending", error: message, updated_at: new Date().toISOString() })
      .eq("id", job.id);
    return new Response("retry", { status: 500 });
  }
}

function isPermanent(err: unknown): boolean {
  const status = (err as { status?: number })?.status;
  return status === 400 || status === 401 || status === 403 || status === 422;
}
Enter fullscreen mode Exit fullscreen mode

The key idea is the explicit state machine. On a transient failure you reset the row to pending before returning 500. Without that reset, the retry would find a row stuck in processing and be skipped by the claim, and the job would silently never finish. Returning 200 for a permanent failure is just as deliberate: it tells QStash that the message was handled, so it doesn't burn the remaining retries on something that can't succeed.

A job only moves forward (pending, processing, then done or error), except for the one loop back to pending that lets a retry claim it.

The model call itself is plain fetch, with a timeout so a hung upstream can't consume your whole invocation:

// lib/ai.ts
export async function runAiTask(prompt: string): Promise<string> {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.ANTHROPIC_API_KEY!,
      "anthropic-version": "2023-06-01",
    },
    body: JSON.stringify({
      model: "claude-sonnet-5-5",
      max_tokens: 2048,
      messages: [{ role: "user", content: prompt }],
    }),
    signal: AbortSignal.timeout(50_000),
  });

  if (!res.ok) {
    const err = new Error(`model error ${res.status}`) as Error & { status?: number };
    err.status = res.status;
    throw err;
  }

  const data = await res.json();
  return data.content?.[0]?.text ?? "";
}
Enter fullscreen mode Exit fullscreen mode

The failure callback

When the last retry fails, QStash calls your failureCallback. Use it to close out the job and free the slot, so a user is never left watching a spinner on a job that is never going to finish:

// app/api/jobs/failed/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/clients";
import { verifyQStash } from "@/lib/verify";
import { releaseSlot } from "@/lib/concurrency";

export async function POST(req: Request) {
  const rawBody = await req.text();
  if (!(await verifyQStash(req, rawBody))) {
    return new Response("Unauthorized", { status: 401 });
  }

  const jobId = new URL(req.url).searchParams.get("jobId");
  if (!jobId) return new Response("Bad request", { status: 400 });

  const { data: job } = await db
    .from("jobs")
    .update({ status: "error", error: "Failed after all retries", updated_at: new Date().toISOString() })
    .eq("id", jobId)
    .in("status", ["pending", "processing"])
    .select("user_id")
    .maybeSingle();

  if (job) await releaseSlot(job.user_id);
  return NextResponse.json({ ok: true });
}
Enter fullscreen mode Exit fullscreen mode

Messages that exhaust their retries also land in QStash's dead-letter queue, where you can inspect the payload and republish. The callback is for your app's state, the DLQ is for you.

Status endpoint and client polling

// app/api/jobs/[id]/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/clients";
import { getUserId } from "@/lib/auth";

export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const userId = await getUserId(req);
  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { data: job } = await db
    .from("jobs")
    .select("id, status, result, error")
    .eq("id", id)
    .eq("user_id", userId) // never let one user read another's job
    .maybeSingle();

  if (!job) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json(job);
}
Enter fullscreen mode Exit fullscreen mode
// hooks/useJob.ts
"use client";
import { useEffect, useState } from "react";

type Job = { id: string; status: "pending" | "processing" | "done" | "error"; result?: any; error?: string };

export function useJob(jobId: string | null) {
  const [job, setJob] = useState<Job | null>(null);

  useEffect(() => {
    if (!jobId) return;
    let cancelled = false;
    let delay = 1000;

    async function tick() {
      const res = await fetch(`/api/jobs/${jobId}`);
      if (res.ok) {
        const data: Job = await res.json();
        if (cancelled) return;
        setJob(data);
        if (data.status === "done" || data.status === "error") return;
      }
      delay = Math.min(delay * 1.5, 8000); // back off gently
      setTimeout(tick, delay);
    }

    tick();
    return () => { cancelled = true; };
  }, [jobId]);

  return job;
}
Enter fullscreen mode Exit fullscreen mode

Polling is the simplest thing that works on serverless. If you want push instead, QStash's callback option can notify your app when a job succeeds, or you can write status changes to a realtime channel. Polling with a backoff is fine for jobs measured in seconds.

Running it locally

QStash can't deliver to localhost, which is the most common way a first attempt fails. You have two good options:

  1. The local QStash server. Run npx @upstash/qstash-cli dev. It prints a local URL and credentials. Set QSTASH_URL, QSTASH_TOKEN and the signing keys from its output, and QStash calls your dev server directly.
  2. A tunnel (any HTTPS tunnel) with APP_URL set to the tunnel address, using your real QStash project.

On Vercel, remember that preview deployments with deployment protection enabled will return 401 to QStash unless you configure a bypass. If messages are being delivered but your worker never runs, check this first.

Scheduling recurring work

The same primitives handle cron. QStash signs scheduled calls exactly like one-off messages, so the verification code is identical:

await qstash.schedules.create({
  destination: `${process.env.APP_URL}/api/cron/daily-digest`,
  cron: "0 9 * * *",
  retries: 2,
});
Enter fullscreen mode Exit fullscreen mode

Ozigi runs 10 schedules this way (scraping, sending, reply checking, a promotional broadcast), each with its own retry count. Over the 15 days of delivery history QStash retains:

  • 226 distinct messages, 225 delivered
  • 10 retry events and 11 delivery errors, all HTTP 504 timeouts on a single endpoint, the scrape job
  • The other three jobs (91 reply checks, 60 sends, 15 broadcasts) ran with no errors
  • 1 message ended as FAILED

The lesson generalises: the job that struggled was the one whose handler did the most work inside a single invocation. Retries repair flaky networks, not handlers that are too big for their time limit. When a job keeps timing out, split it into stages instead. Each stage does a bounded slice of the work and publishes a message for the next one, so every invocation stays small and a failure only reruns one stage.

You can pull the same figures from the QStash API: GET /v2/events for the delivery log (count messages by messageId, since each message logs CREATED, ACTIVE and DELIVERED separately), GET /v2/dlq for dead letters, and GET /v2/schedules for schedules.

Failure modes to take into account

Failure What happens Defence
Client double-submits Two jobs, double spend Idempotency-Key header plus a unique index; a replay returns the original job
QStash delivers twice Job runs twice Atomic pending → processing claim
Worker times out mid-run Row stuck in processing, slot held Reset to pending on caught errors; slot TTL; consider a reaper for rows stuck in processing past a deadline
Model returns 429/5xx Transient Reset to pending, return 500, let QStash back off
Model rejects input Permanent Mark error, return 200, free the slot
All retries exhausted Message goes to DLQ failureCallback closes the job and frees the slot
Redis is slow or down Limiter can't decide timeout makes the limiter fail open; choose deliberately
Someone calls the worker URL directly Unauthorised execution Signature verification on the raw body

Checklist

  • Rate limit by user ID when you can, IP only when you can't.
  • Combine a burst limiter, a daily budget and a concurrency cap.
  • Separate prefix per limiter, and analytics: true on all of them from day one.
  • Persist the job before you publish; put only the job ID in the message. Accept an Idempotency-Key header and enforce it with a unique index, so a double-submit returns the original job.
  • Set a retryDelay that matches how long a user will wait.
  • Verify upstash-signature against the raw body, before anything else.
  • Make the worker idempotent with an atomic claim.
  • Distinguish transient errors (reset and 500) from permanent ones (mark failed and 200).
  • Always set a failureCallback, and always release the concurrency slot on every exit path.
  • Use a public URL for QStash, never localhost (use the local QStash server in development).
  • Keep each invocation within your platform's time limit, and split work that doesn't fit.

Top comments (6)

Collapse
 
userxnom profile image
Abdullah Naseer •

The number that stuck with me is the retryDelay one — the default backoff meant a failing job took about 33 minutes to finally fail while the user watched a spinner, and "5000 * (1 + retried)" cut that to about 30 seconds. That's the kind of measured tradeoff that makes the whole post land. The piece I'd push on is the failure table's "consider a reaper" line: if a worker dies hard — the platform kills the invocation, no 500, no failureCallback — the row stays in processing and the slot stays held until the 15-minute TTL expires. Did you end up building that reaper, or does the TTL alone cover it in practice?

Collapse
 
gautamtalksdev profile image
Gautam K •

Sliding window limiter in front of the paid call plus a queue for the long jobs is a clean split. Did you put the limit per user or per IP? The per user one usually holds up better once people share networks.

Collapse
 
paullovelace profile image
Paul Lovelace •

The fail-open Redis call is the part I'd lose sleep over — a Redis outage turning into an unlimited-spend window on the one endpoint that costs real money per call. Did you ever consider failing closed just for the generation route, or is the uptime hit not worth it when the endpoint's already behind auth?

Collapse
 
sara_builds profile image
Sara •

The failure table covers a worker dying mid-run, but the expensive part for me has been when the model already returned and the process dies before the result is written. The atomic claim stops an overlapping retry, but once the row goes back to pending the next attempt calls the model again and you get billed twice. When the provider accepts an idempotency key, I send the job id on the model request and only then feel okay resetting to pending after a timeout. The other thing I'd tweak: acquiring the Redis slot at enqueue time means a delayed QStash delivery can outlive the 15-minute TTL, and a second job can start, so you can still go past MAX_IN_FLIGHT. Did you consider taking the slot in the worker, right before the model call?

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

the job row in postgres being the only thing that survives a deploy is the part that holds it together. the queue and the counter are just plumbing around it.

Collapse
 
ric0c0derlab profile image
Ric0 C0der Lab •

I'd be interested in how interrupted jobs are resumed without duplicating actions that already succeeded.