redis-patterns

Upstash Redis patterns for caching and rate limiting.

242 stars

Best use case

redis-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Upstash Redis patterns for caching and rate limiting.

Upstash Redis patterns for caching and rate limiting.

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "redis-patterns" skill to help with this workflow task. Context: Upstash Redis patterns for caching and rate limiting.

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/redis-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/aiskillstore/marketplace/main/skills/barnhardt-enterprises-inc/redis-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/redis-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How redis-patterns Compares

Feature / Agentredis-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Upstash Redis patterns for caching and rate limiting.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 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, remaining } = await ratelimit.limit(ip);

  if (!success) {
    return new Response('Too Many Requests', {
      status: 429,
      headers: {
        'X-RateLimit-Limit': limit.toString(),
        'X-RateLimit-Remaining': remaining.toString(),
        'X-RateLimit-Reset': reset.toString(),
      },
    });
  }

  // Process request...
}
```

## Session Storage

```typescript
interface Session {
  userId: string;
  expiresAt: number;
}

async function createSession(userId: string): Promise<string> {
  const sessionId = crypto.randomUUID();
  const session: Session = {
    userId,
    expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days
  };

  await redis.setex(`session:${sessionId}`, 7 * 24 * 60 * 60, session);
  return sessionId;
}

async function getSession(sessionId: string): Promise<Session | null> {
  return await redis.get<Session>(`session:${sessionId}`);
}

async function deleteSession(sessionId: string): Promise<void> {
  await redis.del(`session:${sessionId}`);
}
```

## Pub/Sub for Real-time

```typescript
// Publisher
async function publishEvent(channel: string, data: unknown): Promise<void> {
  await redis.publish(channel, JSON.stringify(data));
}

// Usage
await publishEvent('user:updates', { userId: '123', action: 'updated' });
```

## Leaderboard

```typescript
// Add score
await redis.zadd('leaderboard', { score: 100, member: 'user:123' });

// Get top 10
const topUsers = await redis.zrevrange('leaderboard', 0, 9, { withScores: true });

// Get user rank
const rank = await redis.zrevrank('leaderboard', 'user:123');
```

## Cache Patterns

```typescript
// Cache-aside pattern
async function getData<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = 300
): Promise<T> {
  const cached = await redis.get<T>(key);
  if (cached) return cached;

  const data = await fetcher();
  await redis.setex(key, ttl, data);
  return data;
}

// Usage
const user = await getData(
  `user:${id}`,
  () => db.query.users.findFirst({ where: eq(users.id, id) }),
  300
);
```

Related Skills

python-design-patterns

242
from aiskillstore/marketplace

Python design patterns including KISS, Separation of Concerns, Single Responsibility, and composition over inheritance. Use when making architecture decisions, refactoring code structure, or evaluating when abstractions are appropriate.

design-system-patterns

242
from aiskillstore/marketplace

Build scalable design systems with design tokens, theming infrastructure, and component architecture patterns. Use when creating design tokens, implementing theme switching, building component libraries, or establishing design system foundations.

vercel-composition-patterns

242
from aiskillstore/marketplace

React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture.

ui-component-patterns

242
from aiskillstore/marketplace

Build reusable, maintainable UI components following modern design patterns. Use when creating component libraries, implementing design systems, or building scalable frontend architectures. Handles React patterns, composition, prop design, TypeScript, and component best practices.

zapier-make-patterns

242
from aiskillstore/marketplace

No-code automation democratizes workflow building. Zapier and Make (formerly Integromat) let non-developers automate business processes without writing code. But no-code doesn't mean no-complexity - these platforms have their own patterns, pitfalls, and breaking points. This skill covers when to use which platform, how to build reliable automations, and when to graduate to code-based solutions. Key insight: Zapier optimizes for simplicity and integrations (7000+ apps), Make optimizes for power

workflow-patterns

242
from aiskillstore/marketplace

Use this skill when implementing tasks according to Conductor's TDD workflow, handling phase checkpoints, managing git commits for tasks, or understanding the verification protocol.

workflow-orchestration-patterns

242
from aiskillstore/marketplace

Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.

wcag-audit-patterns

242
from aiskillstore/marketplace

Conduct WCAG 2.2 accessibility audits with automated testing, manual verification, and remediation guidance. Use when auditing websites for accessibility, fixing WCAG violations, or implementing accessible design patterns.

unity-ecs-patterns

242
from aiskillstore/marketplace

Master Unity ECS (Entity Component System) with DOTS, Jobs, and Burst for high-performance game development. Use when building data-oriented games, optimizing performance, or working with large entity counts.

stride-analysis-patterns

242
from aiskillstore/marketplace

Apply STRIDE methodology to systematically identify threats. Use when analyzing system security, conducting threat modeling sessions, or creating security documentation.

sql-optimization-patterns

242
from aiskillstore/marketplace

Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.

rust-async-patterns

242
from aiskillstore/marketplace

Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.