engineering-redis-game-patterns

Use when implementing Redis patterns for games — caching, leaderboards, pub/sub messaging, session storage, rate limiting, or ephemeral game state. Triggers: Redis, cache, leaderboard, pub/sub, rate limit, session.

6 stars

Best use case

engineering-redis-game-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when implementing Redis patterns for games — caching, leaderboards, pub/sub messaging, session storage, rate limiting, or ephemeral game state. Triggers: Redis, cache, leaderboard, pub/sub, rate limit, session.

Teams using engineering-redis-game-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/redis-game-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/fcsouza/agent-skills/main/plugins/game-dev/engineering/redis-game-patterns/SKILL.md"

Manual Installation

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

How engineering-redis-game-patterns Compares

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

Frequently Asked Questions

What does this skill do?

Use when implementing Redis patterns for games — caching, leaderboards, pub/sub messaging, session storage, rate limiting, or ephemeral game state. Triggers: Redis, cache, leaderboard, pub/sub, rate limit, session.

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

# Redis Game Patterns

## Purpose

Redis usage patterns for games — leaderboards, session caching, pub/sub messaging, rate limiting, ephemeral state, and sorted sets for real-time game data.

## When to Use

Trigger: Redis, pub/sub, leaderboard, session cache, rate limiting, sorted sets, game cache, ephemeral state, TTL, player presence, cross-server messaging

## Prerequisites

None — this is a foundational infrastructure skill.

## Core Principles

> Will Wright: "Simulation state must be fast, ephemeral, and disposable — persistence is for outcomes, not for process."

1. **Redis is for hot data, PostgreSQL is for cold data** — cache what's accessed frequently, persist what matters long-term
2. **Every cached value needs a TTL** — stale data is worse than no data; always set expiration
3. **Use the right data structure** — sorted sets for leaderboards, hashes for sessions, pub/sub for events, strings for simple counters
4. **Cache-aside pattern by default** — check cache, miss, load from DB, populate cache; never assume cache is populated
5. **Atomic operations prevent race conditions** — use pipelines and Lua scripts for multi-step operations, never read-then-write
6. **Separate Redis connections for pub/sub** — subscriber connections are blocked; use dedicated connections for subscriptions
7. **Namespace all keys** — prefix keys by domain (`lb:`, `session:`, `rl:`, `presence:`) to avoid collisions and enable selective flushing

## Step-by-Step Instructions

### 1. Install Dependencies

```bash
bun add ioredis
```

### 2. Configure Redis Connection

Use `boilerplate/redis-client.ts` for the base connection with reconnection logic and error handling. All other modules import from this file.

### 3. Set Up Leaderboards

Use `boilerplate/leaderboard.ts` for sorted-set-based leaderboards. Supports adding scores, fetching top N, getting player rank, and fetching nearby ranks. Includes periodic snapshot to PostgreSQL for historical data.

### 4. Implement Session Caching

Use `boilerplate/session-cache.ts` for player session caching with TTL. Follows cache-aside pattern: check cache → miss → load from DB → populate cache.

### 5. Configure Pub/Sub

Use `boilerplate/pub-sub.ts` for cross-server messaging. Requires separate Redis connections for publishing and subscribing. Typed event handlers ensure type safety.

### 6. Add Rate Limiting

Use `templates/rate-limiter.ts` for per-player per-action sliding window rate limiting using sorted sets. Configurable window size and max requests.

### 7. Manage Ephemeral State

Use `templates/ephemeral-state.ts` for short-lived game state: match state with TTL, player presence via heartbeat, and temporary buffs/effects.

## Code Examples

### Adding a player score to a leaderboard

```typescript
import { leaderboard } from './leaderboard';

await leaderboard.addScore('weekly', 'player_123', 4500);
const top10 = await leaderboard.getTopN('weekly', 10);
const rank = await leaderboard.getPlayerRank('weekly', 'player_123');
```

### Caching a player session

```typescript
import { sessionCache } from './session-cache';

const session = await sessionCache.get('player_123');
if (!session) {
  const fromDb = await db.query.players.findFirst({ where: eq(players.id, 'player_123') });
  await sessionCache.set('player_123', fromDb, 3600);
}
```

### Publishing a game event across servers

```typescript
import { publisher, subscriber } from './pub-sub';

await publisher.publish('match-events', {
  type: 'match-started',
  matchId: 'match_456',
  players: ['player_123', 'player_789'],
});

subscriber.on('match-events', (event) => {
  console.log('Match event:', event.type);
});
```

### Rate limiting a player action

```typescript
import { checkRateLimit } from './rate-limiter';

const result = await checkRateLimit('player_123', 'attack', {
  maxRequests: 1,
  windowSeconds: 5,
});

if (!result.allowed) {
  throw new Error(`Rate limited. Retry after ${result.retryAfter}s`);
}
```

See `boilerplate/` for full implementations and `templates/` for rate limiting and ephemeral state patterns.

## Cross-References

- `game-backend-architecture` for integrating Redis into the game server
- `bullmq-game-queues` for job queues built on Redis
- `postgres-game-schema` for persisting leaderboard snapshots and session fallback data

## Pitfalls & Anti-Patterns

- **Don't use Redis as a primary database** — Redis is a cache and message broker; always have a persistence layer backing it
- **Don't forget TTLs** — keys without expiration accumulate forever and eventually exhaust memory
- **Don't use `KEYS *` in production** — it blocks Redis; use `SCAN` for key enumeration
- **Don't share a single connection for pub/sub and commands** — subscriber connections are blocked and cannot execute other commands
- **Don't store large objects in Redis** — keep values small (< 1MB); store IDs and fetch details from the database
- **Don't assume cache is populated** — always implement cache-aside; never trust that a key exists

## Designer Philosophy

**Will Wright** (SimCity, The Sims): Simulation state management is about speed and disposability. In SimCity, the game constantly recalculates traffic, power, and zoning — none of that intermediate state needs to survive a restart. Redis serves this exact role in multiplayer games: it holds the hot, fast-changing state that drives the simulation, while the database records outcomes that matter. The moment you treat cache as truth, you've confused process with product.

## Sources

- [Redis Official Documentation](https://redis.io/docs/)
- [Redis Data Types and Abstractions](https://redis.io/docs/data-types/)
- [ioredis GitHub Repository](https://github.com/redis/ioredis)
- [Redis Sorted Sets for Leaderboards](https://redis.io/docs/data-types/sorted-sets/)
- [Redis Pub/Sub Documentation](https://redis.io/docs/interact/pubsub/)
- [Redis Best Practices](https://redis.io/docs/management/optimization/)

Related Skills

game-lore

6
from fcsouza/agent-skills

Adds or updates a single world lore entry (faction, location, NPC, or event) — validates against existing lore for consistency, applies the right template, and updates docs/world-lore.md. Extract the entry type (faction/location/npc/event) and name from the user's message.

game-expand

6
from fcsouza/agent-skills

Adds a new feature to an existing MVP plan — scoped architect interview, scope validation against original plan, and integration into the build sequence. Extract the feature name or description from the user's message. Requires docs/mvp-first-draft.md — run game-architect first.

game-build

6
from fcsouza/agent-skills

Builds a game component from the MVP plan — production TypeScript + Vitest tests + mock dependencies + build registry tracking. Extract the component name from the user's message (or "status" to check progress). Requires docs/mvp-first-draft.md — run game-architect first.

game-balance

6
from fcsouza/agent-skills

Analyzes a game system against design principles — economy health metrics, difficulty curve, reward schedules, and progression cost curves. Flags imbalances with severity levels. Use after creating an MVP plan with game-architect. Extract the analysis scope (economy/difficulty/progression/rewards/all) from the user's message.

game-architect

6
from fcsouza/agent-skills

Comprehensive game MVP interviewer and planner. Interviews you in progressive groups, researches genre conventions and reference games, then produces an actionable MVP First Draft with starter project files. Use when starting a new game project from scratch.

narrative-story-structure-game

6
from fcsouza/agent-skills

Use when designing interactive narratives, branching storylines, player agency systems, non-linear story structures, or act frameworks for games. Triggers: branching narrative, player agency, story arc, interactive story, dialogue.

infrastructure-monitoring-game-ops

6
from fcsouza/agent-skills

Use when implementing game monitoring, structured logging, player telemetry, alerting rules, or performance budgets. Triggers: monitoring, logging, telemetry, alerts, observability, metrics.

infrastructure-claude-code-game-workflow

6
from fcsouza/agent-skills

Use when starting a game project, choosing which skill to read, or navigating the game-dev skill ecosystem. Entry point for AI agents working on game development. Triggers: workflow, which skill, how to start, game project setup.

infrastructure-ci-cd-game

6
from fcsouza/agent-skills

Use when setting up CI/CD pipelines, GitHub Actions workflows, deployment automation, migration safety, or staging environments for game projects. Triggers: CI/CD, GitHub Actions, deployment, pipeline, staging.

engineering-stripe-game-payments

6
from fcsouza/agent-skills

Use when implementing game payments, in-app purchases, subscriptions, Stripe webhooks, or monetization flows. Triggers: payments, IAP, subscription, Stripe, checkout, webhooks, monetization.

engineering-postgres-game-schema

6
from fcsouza/agent-skills

Use when designing game database schemas, player data models, inventory systems, or working with Drizzle ORM and PostgreSQL for games. Triggers: database, schema, Drizzle, players, inventory, leaderboards, game data.

engineering-matchmaking-system

6
from fcsouza/agent-skills

Use when implementing player matchmaking, skill-based match selection, lobby systems, queue management, or rank-based grouping. Triggers: matchmaking, lobby, queue, ELO, skill-based, rank, match players, pairing, bracket.