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