Upstash (Redis + QStash) Integration Guide

Technology: upstash · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/upstash

Insight:

Upstash is HTTP-based Redis + QStash (+ Workflow, Vector, Search), so it runs on Vercel Edge where TCP clients like ioredis can't. Use Redis for caching and rate-limiting, QStash/Workflow for background jobs — always behind verifySignatureAppRouter. QStash defaults to the EU region, so US-first apps should set QSTASH_URL to the US endpoint. Redis now has built-in full-text search, and a hosted OAuth MCP server lets agents manage the whole account.

██╗   ██╗██████╗ ███████╗████████╗ █████╗ ███████╗██╗  ██╗
██║   ██║██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔════╝██║  ██║
██║   ██║██████╔╝███████╗   ██║   ███████║███████╗███████║
██║   ██║██╔═══╝ ╚════██║   ██║   ██╔══██║╚════██║██╔══██║
╚██████╔╝██║     ███████║   ██║   ██║  ██║███████║██║  ██║
 ╚═════╝ ╚═╝     ╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝

Upstash (Redis + QStash) Integration Guide

Focus: Serverless Redis and the QStash message queue (plus Workflow, which is built on QStash), all reached over HTTP/REST. That means they run on Vercel Edge / serverless functions, where persistent TCP connections (e.g. ioredis) aren't allowed. Pay-per-request pricing and scale-to-zero suit codeAmani's low-volume SME workloads.

Overview

Upstash's product line (per the docs index, 2026-10-20): Redis, Vector, QStash, Workflow, Search, Box, and Blob. codeAmani uses these:

Product Package Use it for
Redis @upstash/redis Cache, sessions, feature flags, counters. Since 2026 it also has Redis Search (full-text), Vector commands, and Array commands built in
Ratelimit @upstash/ratelimit Rate limiting on top of Redis (no extra infrastructure)
QStash @upstash/qstash HTTP message queue and scheduler: guaranteed delivery, retries, cron, DLQ, flow control
Workflow @upstash/workflow Durable multi-step functions on top of QStash (context.run / sleep / call / waitForEvent)
Vector @upstash/vector Serverless ANN index for RAG
Search @upstash/search Standalone AI search (full-text + semantic + reranking). Not the same thing as Redis Search

New products we don't use yet: Box (sandboxed cloud containers for running agents), Blob (object storage), and Realtime (React useRealtime, built on Redis Streams + Pub/Sub). Upstash Kafka was shut down on 2025-03-11, so use QStash / Workflow instead.

Context7 is also an Upstash product. It's the live-docs MCP that our Documentation Policy relies on, and it has its own guide in context7/. Upstash's marketing site even advertises a Context7 "ask" endpoint for its docs.

The big picture: every primitive is reached over HTTP/REST from the same edge function.

flowchart LR
  APP["Vercel Edge<br/>Next.js function"] -->|"REST + token"| REDIS["Upstash Redis<br/>cache · rate-limit · search"]
  APP -->|"REST + token"| QSTASH["QStash<br/>queue + scheduler"]
  QSTASH -->|"signed POST + retry"| WORKER["Receiver route<br/>verifySignatureAppRouter"]
  QSTASH -->|"step-by-step"| WF["Workflow endpoint<br/>serve()"]

Official Documentation

Resource URL
Docs home (product index) https://upstash.com/docs/introduction
Redis TS SDK https://upstash.com/docs/redis/sdks/ts/getstarted
Redis Search https://upstash.com/docs/redis/search/introduction
Rate limiting https://upstash.com/docs/redis/sdks/ratelimit-ts/overview
QStash Next.js quickstart https://upstash.com/docs/qstash/quickstarts/vercel-nextjs
QStash signature verification https://upstash.com/docs/qstash/howto/signature
QStash regions (EU / US) https://upstash.com/docs/qstash/howto/multi-region
Workflow Next.js quickstart https://upstash.com/docs/workflow/quickstarts/vercel-nextjs
MCP server https://upstash.com/docs/agent-resources/mcp
Vercel integration https://upstash.com/docs/redis/howto/vercelintegration
Pricing (machine-readable) https://upstash.com/pricing/redis.md, /pricing/qstash.md, /pricing/workflow.md, /pricing/vector.md
Console https://console.upstash.com

1. Get credentials

Create a Redis database and pick a QStash region at console.upstash.com, or install Upstash from the Vercel Marketplace. The Marketplace lists Upstash for Redis, Vector, QStash/Workflow, and Search. It also replaced Vercel KV, which Vercel moved to Upstash Redis in December 2024.

Secrets (server-side only, so they go in .env.local / Vercel env / the vault):

UPSTASH_REDIS_REST_TOKEN=your_redis_rest_token
QSTASH_TOKEN=your_qstash_token
QSTASH_CURRENT_SIGNING_KEY=sig_current_placeholder
QSTASH_NEXT_SIGNING_KEY=sig_next_placeholder

Non-secret settings:

Variable Value Notes
UPSTASH_REDIS_REST_URL https://<name>.upstash.io Read by Redis.fromEnv() together with the token
QSTASH_URL https://qstash-us-east-1.upstash.io Set this for US-first apps. If it's unset, the SDK uses the EU region (https://qstash.upstash.io). Each region has its own token and signing keys
QSTASH_DEV true (local only) @upstash/qstash / @upstash/workflow download and start a local QStash dev server, so you don't need a tunnel. This does nothing when NODE_ENV=production
UPSTASH_VECTOR_REST_URL / UPSTASH_SEARCH_REST_URL per index Each comes with a matching *_REST_TOKEN secret

The Vercel integration injects the variables for you, but redeploy before they take effect. Never put any Upstash token in a NEXT_PUBLIC_* variable.

2. Install

npm install @upstash/redis @upstash/qstash @upstash/ratelimit   # core
npm install @upstash/workflow                                    # durable multi-step jobs
# optional: npm install @upstash/vector @upstash/search
pip install upstash-redis qstash                                 # Python services

Current versions (verified 2026-10-20 via npm view / PyPI JSON): @upstash/redis 1.39.0, @upstash/qstash 2.12.1, @upstash/ratelimit 2.2.0, @upstash/workflow 1.4.0, @upstash/vector 1.2.3, @upstash/search 0.1.7, @upstash/mcp-server 0.3.0, @upstash/redis-mcp 0.1.1. Python: upstash-redis 1.8.0, qstash 3.4.0, upstash-workflow 2.0.0, upstash-vector 0.8.0, upstash-ratelimit 1.2.0. The core API surface (Redis.fromEnv, Ratelimit.slidingWindow, Client.publishJSON, verifySignatureAppRouter) hasn't changed. New since the last review: Client.fromEnv() (qstash 2.12.1), messages.runNow(), redis.search.*, redis.vector.*, and Redis array commands (1.39.0).

3. Redis client

import { Redis } from "@upstash/redis";

// Reads UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN from the env
export const redis = Redis.fromEnv();

await redis.set("foo", "bar", { ex: 60 });
const bar = await redis.get<string>("foo");

4. Caching pattern (cache-aside)

Cache-aside works like this: try the cache, and on a miss compute the value, write it back with a TTL, then return it. The TTL caps staleness and storage cost.

flowchart TD
  START["request needs data"] --> GET["redis.get key"]
  GET --> HIT{"cache hit"}
  HIT -->|"yes"| RET["return cached value"]
  HIT -->|"no · miss"| COMPUTE["compute value<br/>db query · API call"]
  COMPUTE --> SET["redis.set key value<br/>ex = TTL seconds"]
  SET --> RET
import { redis } from "@/lib/redis";

export async function cached<T>(
  key: string,
  ttlSeconds: number,
  compute: () => Promise<T>,
): Promise<T> {
  const hit = await redis.get<T>(key);
  if (hit !== null && hit !== undefined) return hit; // cache hit

  const value = await compute(); // miss: do the slow work once
  await redis.set(key, value, { ex: ttlSeconds }); // store with TTL (seconds)
  return value;
}

Gotcha: cache stampede. When a hot key expires, many concurrent requests miss at once and hit the origin together. Fix it with a lock (set(lockKey, "1", { nx: true, ex })), a stale-while-revalidate window, or jittered TTLs. See examples/redis.ts.

5. Rate limiting (protect API routes)

import { Ratelimit } from "@upstash/ratelimit";
import { redis } from "@/lib/redis";
import { after } from "next/server";

const ratelimit = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(10, "10 s"),
  analytics: true,
  prefix: "rl:api",
});

const { success, limit, reset, pending } = await ratelimit.limit(userId);
after(() => pending); // let analytics / multi-region sync finish after the response
if (!success) return new Response("Too many requests", { status: 429 });

6. QStash: publish a background job

sequenceDiagram
  participant App as "Edge function"
  participant Q as "QStash"
  participant Route as "Receiver route"
  App->>Q: "publishJSON - url + body"
  Q-->>App: "messageId"
  Q->>Route: "POST + Upstash-Signature JWT"
  Route->>Route: "verify signature"
  Route->>Route: "do the slow work (idempotently)"
  Route-->>Q: "2xx"
  Note over Q,Route: "non-2xx: retried (3 by default), then DLQ"
"use server";
import { Client } from "@upstash/qstash";

const qstash = Client.fromEnv(); // QSTASH_TOKEN + QSTASH_URL (or: new Client({ token }))

export async function startBackgroundJob(orderId: string) {
  const { messageId } = await qstash.publishJSON({
    url: "https://<your-app>.vercel.app/api/long-task", // public HTTPS URL
    body: { orderId },
    retries: 3,
    deduplicationId: `order:${orderId}`, // idempotent enqueue
  });
  return messageId;
}

7. QStash: receive and verify the message

Every QStash request carries a JWT in the Upstash-Signature header, signed with your signing key. Always verify it before you act on the payload:

// app/api/long-task/route.ts
import { verifySignatureAppRouter } from "@upstash/qstash/nextjs";

export const POST = verifySignatureAppRouter(async (req: Request) => {
  const body = await req.json();
  // ... do the slow work here (idempotently)
  return new Response("ok");
});

8. Workflow: durable multi-step jobs

Use Workflow when a job has several steps, long waits, or external calls that could outlive a function timeout:

// app/api/workflow/route.ts
import { serve } from "@upstash/workflow/nextjs";

export const { POST } = serve<{ userId: string }>(async (context) => {
  await context.run("create-profile", async () => { /* idempotent write */ });
  await context.sleep("wait-a-day", "1d");
  await context.run("send-email", async () => { /* Resend */ });
});

Trigger it from server code with new Client({ token }).trigger({ url, body, retries }) (from @upstash/workflow). It returns a workflowRunId that starts with wfr_. serve() verifies QStash signatures itself. Billing: run / sleep / sleepUntil / waitForEvent count as 1 step, call / invoke count as 2, and retries plus parallel steps add more. See examples/workflow.ts.

9. Redis Search (built-in, since 2026-03)

Upstash Redis has its own full-text search extension, built on Tantivy and different from RediSearch's FT.* API. It indexes JSON / Hash / String / Stream keys by prefix and stays in sync with normal writes:

import { Redis, s } from "@upstash/redis";
const redis = Redis.fromEnv();

// once, at deploy time (throws if it already exists)
await redis.search.createIndex({
  name: "products", dataType: "json", prefix: "product:",
  schema: s.object({ name: s.string(), category: s.string().noTokenize(), price: s.number("F64") }),
});

const results = await redis.search.index({ name: "products" }).query({ filter: { name: "headphones" } });

If you want hosted semantic + full-text search over documents without managing the data in Redis, use the separate Upstash Search product (@upstash/search, Search.fromEnv().index("docs")).

10. Upstash MCP server (for coding agents)

Upstash ships an MCP server that can manage the whole account across Redis, QStash, Workflow, Vector, Search, Box, and Blob. It has 59 tools, each annotated as read / write / destructive.

Option Setup Auth Coverage
Remote (recommended) claude mcp add --scope user --transport http upstash https://mcp.upstash.com/mcp, then /mcp → Authenticate OAuth (choose account/team scope + read-only) or a Bearer email:API_KEY header All products, plus a console "MCP App"
Local stdio npx -y @upstash/mcp-server@latest --email <email> --api-key <key> Developer API key Redis, QStash, Workflow, Box
Single Redis DB npx -y @upstash/redis-mcp with that DB's REST URL/token in env DB token 2 tools: redis_run_commands, redis_search_docs
One-shot setup npx upstash (or npx -y upstash setup --yes --claude) OAuth Installs the Upstash plugin + skills + remote MCP

Pricing snapshot (2026-10-20)

Product Free Pay as you go Fixed
Redis 250 MB, 500K commands/month, 10 GB bandwidth $0.20 / 100K commands, $0.25/GB storage (first 1 GB free), bandwidth free to 200 GB then $0.03/GB, max 100 GB From $10/mo (250 MB, no per-command billing) up to $1,500/mo (500 GB), plus a per-read-region charge
QStash 1,000 messages/day, 1 MB messages $1 / 100K messages, 10 MB messages, 2-hour max response duration Fixed 1M $180/mo · Fixed 10M $420/mo
Workflow 1,000 steps/day $1 / 100K steps Fixed 1M $180/mo · Fixed 10M $420/mo
Vector 10K queries/day, 1 GB $0.40 / 100K requests $60/mo

The Prod Pack add-on ($200/month per database on Redis) adds an uptime SLA, multi-zone HA, encryption at rest, SOC 2, Prometheus/Datadog, and Insights. The pay-as-you-go plan supports a budget cap. The old Pro 2K / Pro 10K plans are deprecated. Full details are in reference/limits-and-pricing.md.

codeAmani notes

Official docs: