Upstash (Redis + QStash) Integration Guide
What is Upstash?
@upstash/redis 1.39 (HTTP), QStash 2.12 (signed HTTPS queue), Workflow 1.4, Vector, plus a hosted MCP server.
@upstash/redis is a thin HTTP wrapper — call it from Vercel Edge / Cloudflare Workers / any runtime without TCP. Global replication keeps p99 reads under ~30ms anywhere. QStash sends a signed POST to your HTTPS endpoint at a scheduled time or after a delay — perfect for cron-style jobs, delayed-callback retries, and offloading slow work from a webhook. The Vector product is a serverless Pinecone-ish ANN with similar pricing dynamics. Receivers wrap handlers in verifySignatureAppRouter so only QStash can call them. QStash defaults to the EU region — set QSTASH_URL to the US endpoint for US-first apps. For codeAmani, Upstash is the offload layer: Stripe webhooks (and M-Pesa callbacks on Kenya-targeted projects) ACK fast, then enqueue the slow part to QStash.
Six Upstash primitives
Same HTTPS contract everywhere. Pay per call, scale to zero.
██╗ ██╗██████╗ ███████╗████████╗ █████╗ ███████╗██╗ ██╗
██║ ██║██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔════╝██║ ██║
██║ ██║██████╔╝███████╗ ██║ ███████║███████╗███████║
██║ ██║██╔═══╝ ╚════██║ ██║ ██╔══██║╚════██║██╔══██║
╚██████╔╝██║ ███████║ ██║ ██║ ██║███████║██║ ██║
╚═════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝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.
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_placeholderNon-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 servicesCurrent versions (verified 2026-10-20 via
npm view/ PyPI JSON):@upstash/redis1.39.0,@upstash/qstash2.12.1,@upstash/ratelimit2.2.0,@upstash/workflow1.4.0,@upstash/vector1.2.3,@upstash/search0.1.7,@upstash/mcp-server0.3.0,@upstash/redis-mcp0.1.1. Python:upstash-redis1.8.0,qstash3.4.0,upstash-workflow2.0.0,upstash-vector0.8.0,upstash-ratelimit1.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");- On
set, the SDK auto-JSON.stringifys non-string values, andget<T>()parses them back. Don't double-serialize. - On Cloudflare Workers, import from
@upstash/redis/cloudflare. On Fastly, import from@upstash/redis/fastly. redis.pipeline()batches commands into one HTTP round-trip (each command is still billed).redis.multi()makes the batch atomic.- Agents can get a disposable database with no signup:
POST https://upstash.com/start-redisreturns credentials, and the database expires after about 3 days unless it's claimed. Use this for experiments only, never for customer data.
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.
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. Seeexamples/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 });- Algorithms:
slidingWindow(tokens, window),fixedWindow(tokens, window),tokenBucket(refillRate, interval, maxTokens). Watch the argument order on tokenBucket. Since 2.2.0, durations accept decimals and a week unit ("1.5 h","1 w"). timeout(default 5 s) makes the limiter fail open and returnsreason: "timeout". Lower it on hot paths.ephemeralCache(on by default) blocks repeat offenders in memory.dynamicLimits: truelets you change limits at runtime.- Every
limit()call is billed as normal Redis commands.
6. QStash: publish a background job
"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;
}- Recurring jobs use
qstash.schedules.create({ destination, cron, scheduleId }). Cron runs in UTC with a minimum resolution of 1 minute. - Other options:
delay/notBefore,callback/failureCallback,label(filters logs and the DLQ),flowControl({ key, parallelism, rate, period }), andretryDelay(an expression). - QStash delivers at least once. Make every receiver idempotent.
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");
});- The wrapper reads
QSTASH_CURRENT_SIGNING_KEYandQSTASH_NEXT_SIGNING_KEYand throws if either is missing. The "next" key is what makes key rotation possible with zero downtime. - The optional second argument is
{ url, clockTolerance, devMode, currentSigningKey, nextSigningKey }. If you omiturl, it's derived fromVERCEL_URL. Passurlexplicitly when you're behind a custom domain. - Outside Next.js, use
new Receiver({ currentSigningKey, nextSigningKey }).verify({ signature, body, url }). Pass the raw body string, because re-stringifying parsed JSON breaks the body hash. PassupstashRegion(from theupstash-regionheader) if you use the multi-region migration mode. - The JWT claims are checked like this:
iss=Upstash,sub= the URL you published to,exp/nbf, andbody= the SHA-256 hash of the raw body.
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 |
- Scope the tools with
?features=redis,qstash_workflow(the groups areredis,qstash_workflow,vector_search,box,blob,console). - On the remote server, tokens never reach the agent. Describe-tools return
credentials only when called with
include_credentials: true. - codeAmani rule: connect agents read-only by default, and grant write access
per task.
redis_run_command,redis_delete_database, andindex_resetare destructive. Keep the Developer API key in the Hazina vault, never in a committed.mcp.json.
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
- Edge-safe default: use Upstash (HTTP), not
ioredis(TCP), anywhere on Vercel Edge or serverless. Upstash is our default cache, rate-limit store, and job queue on Vercel. - US-first region choice: create Redis in a US region (for example
us-east-1) and setQSTASH_URL=https://qstash-us-east-1.upstash.io(as a non-secret setting) with the US token and signing keys. If you skip this, QStash runs in the EU region. - Stripe default: offload Stripe webhook side-effects (receipts, provisioning,
CRM sync) to QStash/Workflow. Verify the Stripe signature in the webhook route,
enqueue, and return 200 fast. Use
deduplicationId: event.idso a Stripe retry doesn't double-enqueue. - M-Pesa (Kenya-targeted projects only): the same pattern applies to the Daraja
callback. Store
CheckoutRequestID, dedupe, enqueue reconciliation/notification to QStash, and return immediately. For a Kenyan audience, the EU QStash region is the closer one. - Rate limiting: put
@upstash/ratelimitin front of auth, checkout / STK-Push, and public AI routes (Claude/OpenAI calls are the expensive ones). - AI routing: Upstash isn't an LLM provider. For LLM calls that may outrun a
function timeout, use QStash's LLM integration or a Workflow
context.call(up to 2 h on pay-as-you-go). - Security: all tokens and signing keys stay server-side, in the vault,
.env.local, or Vercel env. Always verify QStash signatures. Connect MCP agents read-only by default. - Cost: pay-as-you-go plus scale-to-zero fits spiky SME traffic. Set a budget cap on every pay-as-you-go Redis database, and move to a Fixed plan once usage is steady and high. Remember that retries are billed (see NOTES.md).