Upstash Redis SDK - Complete Skills Guide
This directory contains comprehensive guides for using the @upstash/redis SDK. These skill files are designed to help developers and AI assistants understand and use the SDK effectively.
Installation
npm install @upstash/redis
Quick Start
Basic Initialization
import { Redis } from "@upstash/redis";
// Initialize with explicit credentials
const redis = new Redis({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
});
// Or initialize from environment variables
const redis = Redis.fromEnv();
Environment Variables
Set these in your .env file:
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here
No credentials yet? If you're an agent that needs scratch Redis and the user hasn't provided a database, you can mint a temporary one with a single POST to https://upstash.com/start-redis (3-day TTL, no signup).
Skill Files Overview
Data Structures (data-structures/)
Redis data types with auto-serialization examples:
- strings.md - GET, SET, INCR, DECR, APPEND with automatic type handling
- hashes.md - HSET, HGET, HMGET with object serialization
- lists.md - LPUSH, RPUSH, LRANGE with array handling
- sets.md - SADD, SMEMBERS, set operations
- sorted-sets.md - ZADD, ZRANGE, ZRANK, leaderboard patterns
- json.md - JSON.SET, JSON.GET, JSONPath queries for nested objects
- streams.md - XADD, XREAD, XGROUP, consumer groups
Advanced Features (advanced-features/)
Complex operations and optimizations:
- auto-pipeline.md - Automatic request batching, performance optimization
- pipeline-and-transactions.md - Manual pipelines, MULTI/EXEC for atomic operations
- scripting.md - Lua scripts, EVAL, EVALSHA for server-side logic
Patterns (patterns/)
Common use cases and architectural patterns:
- caching.md - Cache-aside, write-through, TTL strategies
- rate-limiting.md - Integration with @upstash/ratelimit package
- session-management.md - Session storage and user state management
- distributed-locks.md - Lock implementations, deadlock prevention
- leaderboard.md - Sorted set leaderboards, real-time rankings
Performance (performance/)
Optimization techniques and best practices:
- batching-operations.md - MGET, MSET, batch operations
- pipeline-optimization.md - When to use pipelines, performance tips
- ttl-expiration.md - Key expiration strategies, memory management
- data-serialization.md - Deep dive into auto serialization, custom serializers, edge cases
- error-handling.md - Error types, retry strategies, timeout handling, debugging tips
- redis-replicas.md - Global database setup, read replicas, read-your-writes consistency
Search (search/)
Full-text search, filtering, and aggregation extension for Redis:
- overview.md - Schema definition, field types, pitfalls, package overview
- commands/querying.md - Query and count with filters, pagination, sorting, highlighting
- commands/aggregating.md - Metric aggregations ($avg, $sum, $stats), bucket aggregations ($terms, $range, $histogram, $facet)
- commands/index-management.md - Create, describe, drop indexes, waitIndexing
- commands/aliases.md - Index aliases for zero-downtime reindexing
- adapters.md - Using search with node-redis and ioredis via @upstash/search-redis and @upstash/search-ioredis
Migrations (migrations/)
Migration guides from other libraries:
- from-ioredis.md - Migration from ioredis, key differences, serialization changes
- from-redis-node.md - Migration from node-redis, API differences
Common Mistakes (Especially for LLMs)
❌ Mistake 1: Treating Everything as Strings
// ❌ WRONG - Don't do this with @upstash/redis
await redis.set("count", "42"); // Stored as string "42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // Manual parsing needed
// ✅ CORRECT - Let the SDK handle it
await redis.set("count", 42); // Stored as number
const count = await redis.get("count");
const incremented = count + 1; // Just use it
❌ Mistake 2: Manual JSON Serialization
// ❌ WRONG - Unnecessary with @upstash/redis
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));
// ✅ CORRECT - Automatic handling
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");
Quick Command Reference
// Strings
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");
// Hashes
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");
// Lists
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);
// Sets
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");
// Sorted Sets
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);
// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");
// Expiration
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");
Best Practices
- Use environment variables for credentials, never hardcode
- Leverage auto-serialization - pass native JavaScript types
- Use TypeScript types for better type safety
- Set appropriate TTLs to manage memory
- Use pipelines for multiple operations
- Namespace your keys (e.g.,
user:123, session:abc)
Resources
Getting Help
For detailed information on specific topics, refer to the individual skill files in the skills/ directory. Each file contains comprehensive examples, use cases, and best practices for its topic.
1---2name: upstash-redis-js3description: Work with the @upstash/redis TypeScript/JavaScript SDK, a serverless HTTP-based Redis client for Next.js, Vercel, Cloudflare Workers, edge runtimes, and Node.js. Use when adding a cache (cache-aside, write-through, TTL and expiration strategies), session storage and user sessions, a key-value store, leaderboards and rankings with sorted sets, counters, distributed locks, queues with lists, streams and consumer groups, JSON documents, pipelines and MULTI/EXEC transactions, Lua scripting, read replicas, or full-text search, typo-tolerant search, facets, and aggregations with Upstash Redis Search (different from regular FT.SEARCH; also available for TCP clients via @upstash/search-redis and @upstash/search-ioredis). Also use when migrating from ioredis or node-redis, when a Redis connection is needed from a serverless function without connection pooling, when integrating @upstash/ratelimit, or when the user says Redis cache, KV store, session store, serverless Redis, or Upstash Redis. Supports automatic serializ4license: MIT5---6
7# Upstash Redis SDK - Complete Skills Guide
8
9This directory contains comprehensive guides for using the `@upstash/redis` SDK. These skill files are designed to help developers and AI assistants understand and use the SDK effectively.
10
11## Installation
12
13```bash
14npm install @upstash/redis
15```
16
17## Quick Start
18
19### Basic Initialization
20
21```typescript
22import { Redis } from "@upstash/redis";
23
24// Initialize with explicit credentials
25const redis = new Redis({
26 url: "UPSTASH_REDIS_REST_URL",
27 token: "UPSTASH_REDIS_REST_TOKEN",
28});
29
30// Or initialize from environment variables
31const redis = Redis.fromEnv();
32```
33
34### Environment Variables
35
36Set these in your `.env` file:
37
38```bash
39UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
40UPSTASH_REDIS_REST_TOKEN=your-token-here
41```
42
43> **No credentials yet?** If you're an agent that needs scratch Redis and the user hasn't provided a database, you can mint a temporary one with a single POST to `https://upstash.com/start-redis` (3-day TTL, no signup).
44
45## Skill Files Overview
46
47### Data Structures (data-structures/)
48
49Redis data types with auto-serialization examples:
50
51- **strings.md** - GET, SET, INCR, DECR, APPEND with automatic type handling
52- **hashes.md** - HSET, HGET, HMGET with object serialization
53- **lists.md** - LPUSH, RPUSH, LRANGE with array handling
54- **sets.md** - SADD, SMEMBERS, set operations
55- **sorted-sets.md** - ZADD, ZRANGE, ZRANK, leaderboard patterns
56- **json.md** - JSON.SET, JSON.GET, JSONPath queries for nested objects
57- **streams.md** - XADD, XREAD, XGROUP, consumer groups
58
59### Advanced Features (advanced-features/)
60
61Complex operations and optimizations:
62
63- **auto-pipeline.md** - Automatic request batching, performance optimization
64- **pipeline-and-transactions.md** - Manual pipelines, MULTI/EXEC for atomic operations
65- **scripting.md** - Lua scripts, EVAL, EVALSHA for server-side logic
66
67### Patterns (patterns/)
68
69Common use cases and architectural patterns:
70
71- **caching.md** - Cache-aside, write-through, TTL strategies
72- **rate-limiting.md** - Integration with @upstash/ratelimit package
73- **session-management.md** - Session storage and user state management
74- **distributed-locks.md** - Lock implementations, deadlock prevention
75- **leaderboard.md** - Sorted set leaderboards, real-time rankings
76
77### Performance (performance/)
78
79Optimization techniques and best practices:
80
81- **batching-operations.md** - MGET, MSET, batch operations
82- **pipeline-optimization.md** - When to use pipelines, performance tips
83- **ttl-expiration.md** - Key expiration strategies, memory management
84- **data-serialization.md** - Deep dive into auto serialization, custom serializers, edge cases
85- **error-handling.md** - Error types, retry strategies, timeout handling, debugging tips
86- **redis-replicas.md** - Global database setup, read replicas, read-your-writes consistency
87
88### Search (search/)
89
90Full-text search, filtering, and aggregation extension for Redis:
91
92- **overview.md** - Schema definition, field types, pitfalls, package overview
93- **commands/querying.md** - Query and count with filters, pagination, sorting, highlighting
94- **commands/aggregating.md** - Metric aggregations ($avg, $sum, $stats), bucket aggregations ($terms, $range, $histogram, $facet)
95- **commands/index-management.md** - Create, describe, drop indexes, waitIndexing
96- **commands/aliases.md** - Index aliases for zero-downtime reindexing
97- **adapters.md** - Using search with node-redis and ioredis via @upstash/search-redis and @upstash/search-ioredis
98
99### Migrations (migrations/)
100
101Migration guides from other libraries:
102
103- **from-ioredis.md** - Migration from ioredis, key differences, serialization changes
104- **from-redis-node.md** - Migration from node-redis, API differences
105
106## Common Mistakes (Especially for LLMs)
107
108### ❌ Mistake 1: Treating Everything as Strings
109
110```typescript
111// ❌ WRONG - Don't do this with @upstash/redis
112await redis.set("count", "42"); // Stored as string "42"
113const count = await redis.get("count");
114const incremented = parseInt(count) + 1; // Manual parsing needed
115
116// ✅ CORRECT - Let the SDK handle it
117await redis.set("count", 42); // Stored as number
118const count = await redis.get("count");
119const incremented = count + 1; // Just use it
120```
121
122### ❌ Mistake 2: Manual JSON Serialization
123
124```typescript
125// ❌ WRONG - Unnecessary with @upstash/redis
126await redis.set("user", JSON.stringify({ name: "Alice" }));
127const user = JSON.parse(await redis.get("user"));
128
129// ✅ CORRECT - Automatic handling
130await redis.set("user", { name: "Alice" });
131const user = await redis.get("user");
132```
133
134## Quick Command Reference
135
136```typescript
137// Strings
138await redis.set("key", "value");
139await redis.get("key");
140await redis.incr("counter");
141await redis.decr("counter");
142
143// Hashes
144await redis.hset("user:1", { name: "Alice", age: 30 });
145await redis.hget("user:1", "name");
146await redis.hgetall("user:1");
147
148// Lists
149await redis.lpush("tasks", "task1", "task2");
150await redis.rpush("tasks", "task3");
151await redis.lrange("tasks", 0, -1);
152
153// Sets
154await redis.sadd("tags", "javascript", "redis");
155await redis.smembers("tags");
156
157// Sorted Sets
158await redis.zadd("leaderboard", { score: 100, member: "player1" });
159await redis.zrange("leaderboard", 0, -1);
160
161// JSON
162await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
163await redis.json.get("user:1");
164
165// Expiration
166await redis.setex("session", 3600, { userId: "123" });
167await redis.expire("key", 60);
168await redis.ttl("key");
169```
170
171## Best Practices
172
1731. **Use environment variables** for credentials, never hardcode
1742. **Leverage auto-serialization** - pass native JavaScript types
1753. **Use TypeScript types** for better type safety
1764. **Set appropriate TTLs** to manage memory
1775. **Use pipelines** for multiple operations
1786. **Namespace your keys** (e.g., `user:123`, `session:abc`)
179
180## Resources
181
182- [Official Documentation](https://upstash.com/docs/redis)
183- [GitHub Repository](https://github.com/upstash/redis-js)
184- [API Reference](https://upstash.com/docs/redis/sdks/ts/overview)
185- [Examples](https://github.com/upstash/redis-js/tree/main/examples)
186
187## Getting Help
188
189For detailed information on specific topics, refer to the individual skill files in the `skills/` directory. Each file contains comprehensive examples, use cases, and best practices for its topic.