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