Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Upstash
https://github.com/upstash/docs
Admin
Upstash documentation
Tokens:
688,955
Snippets:
3,048
Trust Score:
8.5
Update:
1 week ago
Context
Skills
Chat
Benchmark
90.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Upstash Documentation Upstash is a serverless data platform providing managed Redis, Vector, QStash (messaging/scheduling), Workflow (durable functions), Search, and Realtime services. All services are HTTP/REST-based, designed for serverless environments like AWS Lambda, Cloudflare Workers, Vercel, and edge computing platforms. The platform offers pay-per-request pricing with automatic scaling and zero infrastructure management. The core services include: **Redis** for caching and data storage with full Redis compatibility via REST API; **Vector** for AI/LLM vector similarity search; **QStash** for serverless messaging, scheduling, and background jobs; **Workflow** for building durable, fault-tolerant serverless functions with automatic retries; **Search** for full-text search capabilities; and **Realtime** for adding real-time features to applications using Redis Streams. ## Upstash Redis - TypeScript SDK The `@upstash/redis` SDK provides HTTP-based Redis access, eliminating connection management issues in serverless environments. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", }) // String operations await redis.set('key', 'value'); await redis.set('key2', 'value2', { ex: 100 }); // with expiration const data = await redis.get('key'); // Hash operations await redis.hset('user:1', { name: 'John', email: 'john@example.com' }); const name = await redis.hget('user:1', 'name'); // Sorted set operations await redis.zadd('leaderboard', { score: 100, member: 'player1' }); const topPlayers = await redis.zrange('leaderboard', 0, 10); // List operations await redis.lpush('queue', 'task1', 'task2'); const tasks = await redis.lrange('queue', 0, -1); // Set operations await redis.sadd('tags', 'javascript', 'typescript'); const members = await redis.smembers('tags'); ``` ## Upstash Redis - Python SDK The Python SDK provides both synchronous and asynchronous clients for Redis operations. ```python # Synchronous client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") # Or auto-load from environment redis = Redis.from_env() redis.set("key", "value") print(redis.get("key")) # Asynchronous client from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("key", "value") result = await redis.get("key") print(result) ``` ## Upstash Redis - REST API Direct REST API access for Redis commands without any SDK dependencies. ```bash # Basic SET/GET commands curl https://us1-merry-cat-32748.upstash.io/set/foo/bar \ -H "Authorization: Bearer YOUR_TOKEN" # Response: {"result":"OK"} curl https://us1-merry-cat-32748.upstash.io/get/foo \ -H "Authorization: Bearer YOUR_TOKEN" # Response: {"result":"bar"} # POST with JSON body for complex values curl -X POST -d '{"name":"John","age":30}' \ https://us1-merry-cat-32748.upstash.io/set/user:1 \ -H "Authorization: Bearer YOUR_TOKEN" # Pipeline multiple commands curl -X POST https://us1-merry-cat-32748.upstash.io/pipeline \ -H "Authorization: Bearer YOUR_TOKEN" \ -d '[ ["SET", "key1", "value1"], ["SET", "key2", "value2"], ["MGET", "key1", "key2"] ]' # Response: [{"result":"OK"},{"result":"OK"},{"result":["value1","value2"]}] # Atomic transactions curl -X POST https://us1-merry-cat-32748.upstash.io/multi-exec \ -H "Authorization: Bearer YOUR_TOKEN" \ -d '[ ["INCR", "counter"], ["INCR", "counter"], ["GET", "counter"] ]' ``` ## Upstash Vector - TypeScript SDK Vector database for AI/LLM applications supporting similarity search with metadata filtering. ```typescript import { Index } from "@upstash/vector"; const index = new Index({ url: "UPSTASH_VECTOR_REST_URL", token: "UPSTASH_VECTOR_REST_TOKEN", }); // Upsert single vector with metadata await index.upsert({ id: "movie-1", vector: [0.1, 0.2, 0.3, 0.4, 0.5], metadata: { title: "Lord of The Rings", genre: "fantasy", year: 2001 }, }); // Upsert multiple vectors await index.upsert([ { id: "movie-2", vector: [0.6, 0.7, 0.8, 0.9, 0.9], metadata: { title: "Star Wars" } }, { id: "movie-3", vector: [0.2, 0.3, 0.4, 0.5, 0.6], metadata: { title: "Harry Potter" } }, ]); // Upsert with automatic embedding (requires embedding model configured) await index.upsert({ id: "movie-4", data: "A sci-fi epic about space exploration and human survival", metadata: { title: "Interstellar" }, }); // Query for similar vectors const results = await index.query({ vector: [0.1, 0.2, 0.3, 0.4, 0.5], topK: 5, includeMetadata: true, filter: "genre = 'fantasy'" }); // Use namespaces for multi-tenancy await index.upsert([{ id: "1", vector: [0.1, 0.2] }], { namespace: "user-123" }); ``` ## Upstash Vector - Python SDK Python SDK for vector similarity search with sync and async support. ```python from upstash_vector import Index index = Index(url="UPSTASH_VECTOR_REST_URL", token="UPSTASH_VECTOR_REST_TOKEN") # Upsert vectors with metadata index.upsert( vectors=[ ("movie-1", [0.6, 0.8], {"title": "Star Wars", "genre": "sci-fi"}), ("movie-2", [0.3, 0.5], {"title": "The Matrix", "genre": "sci-fi"}), ] ) # Query similar vectors results = index.query( vector=[0.6, 0.8], top_k=3, include_metadata=True, ) for result in results: print(f"ID: {result.id}, Score: {result.score}, Metadata: {result.metadata}") ``` ## QStash - Message Publishing (TypeScript) QStash provides serverless messaging with automatic retries, scheduling, and delivery guarantees. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "<QSTASH_TOKEN>" }); // Publish message with delay and headers const res = await client.publishJSON({ url: "https://my-api.example.com/webhook", body: { orderId: "12345", action: "process" }, headers: { "x-custom-header": "value" }, delay: "30s", // delay delivery by 30 seconds retries: 3, }); console.log("Message ID:", res.messageId); // Publish to a URL group (fan-out to multiple endpoints) await client.publishJSON({ urlGroup: "order-processors", body: { orderId: "12345" }, }); // Publish with callback for async response handling await client.publishJSON({ url: "https://api.example.com/long-running-task", body: { taskId: "abc" }, callback: "https://my-api.com/callback", failureCallback: "https://my-api.com/failure", timeout: "300s", }); ``` ## QStash - Schedules (TypeScript) Create and manage scheduled jobs using cron expressions. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "<QSTASH_TOKEN>" }); // Create schedule running every 5 minutes await client.schedules.create({ destination: "https://my-api.com/cleanup", cron: "*/5 * * * *", }); // Create hourly schedule with callback await client.schedules.create({ destination: "https://my-api.com/reports", cron: "0 * * * *", callback: "https://my-api.com/report-done", body: JSON.stringify({ type: "hourly" }), }); // List all schedules const schedules = await client.schedules.list(); // Pause/resume a schedule await client.schedules.pause({ schedule: "schedule-id" }); await client.schedules.resume({ schedule: "schedule-id" }); // Delete a schedule await client.schedules.delete("schedule-id"); ``` ## QStash - Queues (TypeScript) FIFO queues for ordered message delivery with controlled parallelism. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: "<QSTASH_TOKEN>" }); // Create/configure queue with parallelism const queue = client.queue({ queueName: "order-queue" }); await queue.upsert({ parallelism: 5 }); // Enqueue message (FIFO order guaranteed) await queue.enqueueJSON({ url: "https://my-api.com/process-order", body: { orderId: "12345", items: ["item1", "item2"] }, }); // Get queue info const queueInfo = await queue.get(); console.log("Parallelism:", queueInfo.parallelism); ``` ## QStash - Python SDK Python SDK for QStash messaging with sync and async clients. ```python from qstash import QStash client = QStash("<QSTASH_TOKEN>") # Publish message client.message.publish_json( url="https://my-api.com/webhook", body={"event": "user_signup", "userId": "123"}, ) # Enqueue to queue (FIFO) client.message.enqueue_json( queue="notifications", url="https://my-api.com/notify", body={"message": "Hello World"}, ) # Create schedule client.schedule.create( destination="https://my-api.com/daily-report", cron="0 9 * * *", # Every day at 9 AM ) # Async client from qstash import AsyncQStash import asyncio async def main(): client = AsyncQStash("<QSTASH_TOKEN>") await client.message.publish_json( url="https://my-api.com/webhook", body={"async": True}, ) asyncio.run(main()) ``` ## Upstash Workflow - Basic Setup (TypeScript) Workflow SDK for building durable, fault-tolerant serverless functions with automatic retries. ```typescript // app/api/workflow/route.ts (Next.js) import { serve } from "@upstash/workflow/nextjs"; export const { POST } = serve<{ userId: string; email: string }>( async (context) => { const { userId, email } = context.requestPayload; // Step 1: Validate user const user = await context.run("validate-user", async () => { const response = await fetch(`https://api.example.com/users/${userId}`); return response.json(); }); // Step 2: Send welcome email await context.run("send-email", async () => { await sendEmail(email, "Welcome!", `Hello ${user.name}!`); }); // Step 3: Wait 1 day before follow-up await context.sleep("wait-for-followup", "1d"); // Step 4: Send follow-up await context.run("send-followup", async () => { await sendEmail(email, "How's it going?", "Let us know if you need help!"); }); } ); ``` ## Upstash Workflow - HTTP Calls (context.call) Make HTTP requests that can run for up to 12 hours without consuming compute resources. ```typescript import { serve } from "@upstash/workflow/nextjs"; export const { POST } = serve<{ topic: string }>(async (context) => { const { topic } = context.requestPayload; // Long-running API call (executed by Upstash, not your serverless function) const { status, body } = await context.call("generate-content", { url: "https://api.openai.com/v1/chat/completions", method: "POST", headers: { "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "gpt-4", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: `Write an essay about ${topic}` } ], }), timeout: 300, // 5 minute timeout retries: 2, }); // Process the response await context.run("save-content", async () => { await saveToDatabase(body.choices[0].message.content); }); }); ``` ## Upstash Workflow - Parallel Steps Execute multiple independent steps concurrently for improved performance. ```typescript import { serve } from "@upstash/workflow/nextjs"; export const { POST } = serve<{ imageUrl: string }>(async (context) => { const { imageUrl } = context.requestPayload; // Run image processing tasks in parallel const [thumbnail, watermarked, metadata] = await Promise.all([ context.run("create-thumbnail", async () => { return await createThumbnail(imageUrl, { width: 200 }); }), context.run("add-watermark", async () => { return await addWatermark(imageUrl, "Copyright 2024"); }), context.run("extract-metadata", async () => { return await extractExifData(imageUrl); }), ]); // Continue with results await context.run("save-processed", async () => { await saveToStorage({ thumbnail, watermarked, metadata }); }); }); ``` ## Upstash Workflow - Client API Programmatically trigger and manage workflow runs from external services. ```typescript import { Client } from "@upstash/workflow"; const client = new Client({ token: process.env.QSTASH_TOKEN! }); // Trigger a single workflow const { workflowRunId } = await client.trigger({ url: "https://myapp.com/api/onboarding", body: { userId: "user-123", plan: "premium" }, headers: { "x-source": "signup-flow" }, workflowRunId: "onboard-user-123", // custom ID retries: 3, delay: "10s", flowControl: { key: "onboarding", rate: 10, parallelism: 5, }, }); // Trigger multiple workflows in batch const results = await client.trigger([ { url: "https://myapp.com/api/workflow-a", body: { id: 1 } }, { url: "https://myapp.com/api/workflow-b", body: { id: 2 } }, ]); // Cancel a workflow await client.cancel({ workflowRunId: "wfr_onboard-user-123" }); // Get workflow logs const logs = await client.logs({ workflowRunId: "wfr_onboard-user-123" }); ``` ## Upstash Workflow - Python SDK Python SDK for creating durable workflows with FastAPI integration. ```python from fastapi import FastAPI from upstash_workflow.fastapi import Serve from upstash_workflow import AsyncWorkflowContext from dataclasses import dataclass app = FastAPI() serve = Serve(app) @dataclass class OrderRequest: order_id: str customer_email: str @serve.post("/api/process-order") async def process_order(context: AsyncWorkflowContext[OrderRequest]) -> None: request = context.request_payload # Step 1: Validate order async def _validate(): return await validate_order(request.order_id) order = await context.run("validate-order", _validate) # Step 2: Process payment async def _payment(): return await charge_customer(order.total) payment = await context.run("process-payment", _payment) # Step 3: Wait before shipping notification await context.sleep("wait-for-shipping", "2h") # Step 4: Send notification async def _notify(): await send_email(request.customer_email, "Your order has shipped!") await context.run("send-notification", _notify) ``` ## Upstash Search - TypeScript SDK Full-text search with semantic understanding and metadata filtering. ```typescript import { Search } from "@upstash/search"; const client = new Search({ url: "<UPSTASH_SEARCH_REST_URL>", token: "<UPSTASH_SEARCH_REST_TOKEN>", }); const index = client.index("products"); // Upsert documents await index.upsert([ { id: "product-1", content: { title: "Wireless Bluetooth Headphones", description: "Premium noise-canceling headphones with 30-hour battery", category: "electronics", price: 299, }, metadata: { inStock: true, rating: 4.5 }, }, { id: "product-2", content: { title: "Mechanical Keyboard", description: "RGB backlit mechanical keyboard with Cherry MX switches", category: "electronics", price: 149, }, metadata: { inStock: true, rating: 4.8 }, }, ]); // Search with reranking const results = await index.search({ query: "wireless audio devices", limit: 10, reranking: true, filter: "inStock = true AND rating >= 4.0", }); results.forEach((doc) => { console.log(`${doc.id}: ${doc.content.title} (Score: ${doc.score})`); }); ``` ## Upstash Realtime - Next.js Integration Add real-time features to Next.js applications using Redis Streams and SSE. ```typescript // lib/realtime.ts - Server-side setup import { Realtime, InferRealtimeEvents } from "@upstash/realtime"; import { Redis } from "@upstash/redis"; import z from "zod"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, }); const schema = { chat: { message: z.object({ userId: z.string(), text: z.string(), timestamp: z.number(), }), }, notifications: { alert: z.string(), }, }; export const realtime = new Realtime({ schema, redis }); export type RealtimeEvents = InferRealtimeEvents<typeof realtime>; // app/api/realtime/route.ts - Route handler import { handle } from "@upstash/realtime"; import { realtime } from "@/lib/realtime"; export const GET = handle({ realtime }); // Server action - Emit events import { realtime } from "@/lib/realtime"; export async function sendChatMessage(userId: string, text: string) { await realtime.emit("chat.message", { userId, text, timestamp: Date.now(), }); } // Client component - Subscribe to events "use client"; import { createRealtime } from "@upstash/realtime/client"; import type { RealtimeEvents } from "@/lib/realtime"; const { useRealtime } = createRealtime<RealtimeEvents>(); export function ChatRoom() { const [messages, setMessages] = useState<Message[]>([]); useRealtime({ events: ["chat.message"], onData({ event, data }) { setMessages((prev) => [...prev, data]); }, }); return ( <div> {messages.map((msg, i) => ( <div key={i}>{msg.userId}: {msg.text}</div> ))} </div> ); } ``` ## Summary Upstash provides a comprehensive serverless data platform ideal for modern cloud-native applications. The primary use cases include: **caching and session management** with Redis; **AI/ML applications** with Vector for similarity search and RAG; **background job processing** with QStash for reliable message delivery; **complex business workflows** with Workflow for durable function execution; **search functionality** with Search for full-text queries; and **real-time features** with Realtime for live updates. Integration patterns typically involve initializing clients with REST URLs and tokens from the Upstash Console, then using the provided SDKs (TypeScript/Python) or direct REST API calls. All services are stateless and HTTP-based, making them perfect for serverless environments where connection management is problematic. The platform supports automatic retries, dead letter queues for failed messages, flow control for rate limiting, and comprehensive observability through the console dashboard.
Upstash (upstash/docs) | Context7