redis-patternslisted
Install: claude install-skill aiskillstore/marketplace
# Upstash Redis Patterns
## Setup
```typescript
// lib/redis.ts
import { Redis } from '@upstash/redis';
export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
```
## Basic Caching
```typescript
// Cache with TTL
async function getCachedUser(id: string): Promise<User | null> {
const cacheKey = `user:${id}`;
// Try cache first
const cached = await redis.get<User>(cacheKey);
if (cached) return cached;
// Fetch from DB
const user = await db.query.users.findFirst({
where: eq(users.id, id),
});
if (user) {
// Cache for 5 minutes
await redis.setex(cacheKey, 300, user);
}
return user;
}
```
## Cache Invalidation
```typescript
// Invalidate on update
async function updateUser(id: string, data: UpdateUserInput): Promise<User> {
const user = await db.update(users)
.set(data)
.where(eq(users.id, id))
.returning();
// Invalidate cache
await redis.del(`user:${id}`);
// Also invalidate list caches
await redis.del('users:list');
return user[0];
}
```
## Rate Limiting
```typescript
import { Ratelimit } from '@upstash/ratelimit';
const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
analytics: true,
});
// In API route or middleware
export async function POST(request: Request) {
const ip = request.headers.get('x-forwarded-for') ?? 'anonymous';
const { success, limit, reset, re