1
---
2
name: upstash-redis
3
description: >
4
Use Redis over HTTP from serverless and edge runtimes with @upstash/redis, and
5
add rate limiting with @upstash/ratelimit. Use when the user mentions Upstash
6
Redis, needs Redis from a Next.js route handler or middleware, Vercel,
7
Cloudflare Workers, Deno, or Bun without TCP connection pooling, or wants
8
cache-aside with TTLs, a session store, counters, or a 429 rate limiter using
9
fixed window, sliding window, or token bucket. DO NOT use for self-hosted or
10
TCP Redis clients (ioredis, node-redis), Redis Cluster administration, or
11
vector similarity search.
12
license: MIT
13
compatibility: "@upstash/redis 1.x, @upstash/ratelimit 2.x, Node.js 18+ or any runtime with global fetch"
14
metadata:
15
author: Upstash
16
---
17
18
# Upstash Redis Skill
19
20
This skill covers the three things serverless apps most often need Redis for:
21
caching, sessions, and rate limiting. The client talks to Redis over HTTP, so
22
it works where a long-lived TCP connection does not (edge middleware, short
23
lived functions). Follow the steps in order; each ends with a checkpoint.
24
25
## Requirements and limitations
26
27
- An Upstash Redis database (hosted service; usage-based pricing with a free
28
tier). Credentials are a REST URL and token from the database page.
29
- Environment variables `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
30
- Every command is an HTTP request. Batch with `pipeline()` or `MGET`/`MSET`
31
when you issue many commands per request; avoid `KEYS *` in production.
32
- Values are serialized automatically (objects, arrays, numbers round-trip).
33
Do not `JSON.stringify` before `set` or `parseInt` after `get`.
34
35
## Step 1 — Install and create one client per module
36
37
```bash
38
npm install @upstash/redis @upstash/ratelimit
39
```
40
41
```ts
42
// lib/redis.ts
43
import { Redis } from "@upstash/redis";
44
45
// Reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN
46
export const redis = Redis.fromEnv();
47
```
48
49
Create the client at module scope, not inside the request handler, so
50
ephemeral caches and pipelines can be reused across invocations.
51
52
> **Checkpoint**: `await redis.ping()` returns `"PONG"`.
53
54
## Step 2 — Cache-aside with TTL
55
56
```ts
57
import { redis } from "@/lib/redis";
58
59
type User = { id: string; name: string; plan: "free" | "pro" };
60
61
export async function getUser(userId: string): Promise<User | null> {
62
const key = `user:${userId}`;
63
const cached = await redis.get<User>(key);
64
if (cached) return cached;
65
66
const user = await db.users.findById(userId); // your data source
67
if (user) await redis.set(key, user, { ex: 3600 }); // 1 hour TTL
68
return user;
69
}
70
71
export async function updateUser(userId: string, patch: Partial<User>) {
72
const user = await db.users.update(userId, patch);
73
await redis.set(`user:${userId}`, user, { ex: 3600 }); // write-through
74
return user;
75
}
76
77
export async function deleteUser(userId: string) {
78
await db.users.delete(userId);
79
await redis.del(`user:${userId}`); // invalidate
80
}
81
```
82
83
Always set a TTL on cache entries; namespace keys (`user:123`, `session:abc`).
84
85
> **Checkpoint**: second call to `getUser` returns without hitting the database
86
> and `await redis.ttl("user:123")` is positive.
87
88
## Step 3 — Sessions with sliding expiration
89
90
```ts
91
import { redis } from "@/lib/redis";
92
93
const SESSION_TTL = 60 * 60 * 24; // 24 hours
94
95
export async function createSession(userId: string, data: Record<string, unknown>) {
96
const sessionId = crypto.randomUUID();
97
await redis.set(`session:${sessionId}`, { userId, ...data, createdAt: Date.now() }, { ex: SESSION_TTL });
98
return sessionId;
99
}
100
101
export async function getSession<T = Record<string, unknown>>(sessionId: string) {
102
const session = await redis.get<T>(`session:${sessionId}`);
103
if (session) await redis.expire(`session:${sessionId}`, SESSION_TTL); // slide
104
return session;
105
}
106
107
export async function destroySession(sessionId: string) {
108
await redis.del(`session:${sessionId}`);
109
}
110
```
111
112
Store the session id in an `HttpOnly; Secure; SameSite` cookie; never put the
113
Redis token in client code.
114
115
> **Checkpoint**: `getSession` after `createSession` returns the object with
116
> `userId`; after `destroySession` it returns `null`.
117
118
## Step 4 — Rate limiting a route handler
119
120
```ts
121
// app/api/search/route.ts (Next.js App Router; same pattern for any fetch handler)
122
import { Ratelimit } from "@upstash/ratelimit";
123
import { Redis } from "@upstash/redis";
124
125
const ratelimit = new Ratelimit({
126
redis: Redis.fromEnv(),
127
limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10 seconds
128
prefix: "ratelimit:search", // isolate keys per limiter
129
});
130
131
export async function POST(request: Request) {
132
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "anonymous";
133
const { success, limit, remaining, reset } = await ratelimit.limit(ip);
134
135
if (!success) {
136
return new Response("Too Many Requests", {
137
status: 429,
138
headers: {
139
"X-RateLimit-Limit": String(limit),
140
"X-RateLimit-Remaining": String(remaining),
141
"Retry-After": String(Math.max(0, Math.ceil((reset - Date.now()) / 1000))),
142
},
143
});
144
}
145
146
// handle the request
147
return Response.json({ ok: true });
148
}
149
```
150
151
- Identifier: use the user id or API key when authenticated; fall back to IP.
152
- Algorithms: `Ratelimit.fixedWindow(n, "1 m")` (cheapest), `slidingWindow`
153
(smooth boundaries, default choice), `tokenBucket(refill, "10 s", max)`
154
(allows bursts). Windows accept `ms`, `s`, `m`, `h`, `d`.
155
- Tiers: create one `Ratelimit` per tier with different `prefix` values.
156
- Edge middleware / Cloudflare Workers with `analytics: true`: the result has a
157
`pending` promise; pass it to `context.waitUntil(pending)` so background work
158
finishes before the runtime exits.
159
- `reset` is a Unix timestamp in milliseconds.
160
161
> **Checkpoint**: the 11th request within 10 seconds returns 429 with a
162
> `Retry-After` header; after the window it succeeds again.
163
164
## Common pitfalls
165
166
- **Creating clients inside handlers**: the limiter's in-memory
167
`ephemeralCache` only helps when the instance outlives the request.
168
- **Manual JSON**: `redis.set("k", JSON.stringify(v))` then `redis.get` returns
169
an already-parsed object; double parsing throws.
170
- **No TTL on cache keys**: memory grows until eviction; always pass `{ ex }`.
171
- **Trusting `x-forwarded-for` blindly**: take the first hop, or use the
172
platform's IP helper, when behind a proxy.
173
- **Forgetting `pending`** on edge runtimes with analytics or multi-region
174
limiters.
175
176
## When NOT to use this skill
177
178
- Long-running servers with a TCP Redis connection already in place: keep
179
ioredis/node-redis.
180
- Vector search or RAG: use a vector database skill instead.
181
- Sub-millisecond, in-process caching: use an in-memory LRU.
182
183
## References
184
185
- https://upstash.com/docs/redis/sdks/ts/overview
186
- https://upstash.com/docs/redis/sdks/ratelimit-ts/overview
187
- https://github.com/upstash/redis-js
188
- https://github.com/upstash/ratelimit-js
189