redis-game-patterns
Four Redis patterns for game servers: sorted-set leaderboards, heartbeat presence with short-lived match state and timed buffs, a per-player per-action…
от fcsouza★ 29 звёзд на GitHub
Установить redis-game-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Redis Game Patterns
Redis holds hot, disposable game state. The database holds outcomes. If Redis restarts empty, players should lose nothing that matters: match results, rewards and currency are written to the database first.
Client choice
The code here uses ioredis 6, because BullMQ 6 creates its Redis connections
with ioredis by default and most game servers in this bundle already run
BullMQ (bullmq-game-queues). The ioredis README says that for new projects
node-redis is the recommended client; if the project has no BullMQ and no
ioredis yet, consider node-redis and port the commands. BullMQ 6 marks ioredis
as an optional peer, so install it explicitly: bun add ioredis.
Every file takes the client as a parameter typed Redis from ioredis.
Create the client once in the server and pass it in. Keep the default
replyMapping: "legacy": the parsers expect WITHSCORES replies as flat
[member, score, ...] string arrays. The code needs Redis 6.2 or newer
(ZRANGE ... REV).
Pattern 1: leaderboard
Copy boilerplate/leaderboard.ts when the game ranks players by score.
- One sorted set per board and period:
lb:weekly:2026-W46,lb:season:3. A new period is a new key; snapshot the old one, then delete it. ZADDoverwrites the score. For "best score counts", decide on purpose:ZADD ... GTkeeps the higher value;ZINCRBYadds points.- Ties: equal scores sort by member ID bytes (reverse order under
REV), not by who reached the score first. If first-to-score must win, encode the tie break into the score, and keep the whole score inside the exact integer range of a double (2^53). - Rank from
ZREVRANKis zero-based; the boilerplate returns rank 1 for the top player. - At season end, call
snapshot()with a function that writes the rows to Postgres (postgres-game-schema), then reset the board.
Pattern 2: presence and ephemeral state
Copy templates/ephemeral-state.ts when the game shows who is online, keeps
live match state outside the database, or applies timed buffs.
- Presence: the client heartbeats every few seconds; the server writes
presence:<playerId>withEX. A missing key means offline, so a crashed client goes offline without cleanup code. Set the TTL to a few heartbeat intervals so one lost packet does not flash the player offline. - Match state: one JSON key per match with a TTL longer than the longest
match.
update()reads the JSON, applies your pure function and writes the result with a compare-and-set Lua script: the write lands only if the key still holds what was read, else it reads again and retries. Calls for one match from the same process run one after another, so they never race each other; the script catches races with other servers. Do not useWATCH/MULTIhere: concurrent updates on one shared client interleave theirWATCHandEXECand lose writes. - Timed buffs: one key per effect with
EX, plus a per-player sorted set scored by expiry time to list them. Expiry needs no sweeper job. SETclears an existing TTL unless you passEXagain. Every write in the template passes it.
Pattern 3: per-action rate limit
Copy templates/rate-limiter.ts when an action needs a cooldown or spam cap:
attacks, chat, trades, crafting.
- Key per player and action:
rl:<action>:<playerId>. Limits differ per action, so one global limit per player is the wrong shape. - Sliding window on a sorted set: each attempt is a member scored by its
timestamp. The template runs remove-old, add, count and expire in one
MULTI, so two concurrent attempts cannot both pass. - A denied attempt is removed again. Otherwise a player who spams the button stays locked out past the window.
- Check the limit on the server for every action message, including actions
that arrive over WebSocket (
game-backend-architecture).
Pattern 4: cache-aside for player data
No file; the code is short enough to write in place.
- Read
player:<id>from Redis. On a hit, parse and return it. - On a miss, load from the database, write it with
SET key value EX ttl, and return it. A missing row stays uncached unless you cache a "not found" marker with a short TTL. - On every database write to that player, delete the cache key after the write commits. Do not update the cache in place from game logic.
- If the cached JSON fails to parse, delete the key and fall through to the database.
Cache only what the game reads often and can tolerate seeing a few seconds late (profile, loadout, cosmetics). Wallet balances and inventory counts are read from the database inside the transaction that changes them.
Pitfalls
- Treating Redis as the record of truth for match results, rewards or currency. Write those to the database; Redis may lose them.
- Read-then-write on shared keys from more than one server. Use a Lua
script (as
update()does), a single command, orMULTI/WATCHon a connection that no concurrent
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- boilerplate/leaderboard.ts
- references/sources.md
- templates/ephemeral-state.ts
- templates/rate-limiter.ts
FAQ
Что делает скилл redis-game-patterns?
Four Redis patterns for game servers: sorted-set leaderboards, heartbeat presence with short-lived match state and timed buffs, a per-player per-action sliding-window rate limit, and cache-aside for player data. Use when a game needs ranked scores, an online/offline indicator, action cooldowns or anti-spam limits, or a fast read path in front of the player database, on Redis through ioredis.
Как установить скилл redis-game-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл redis-game-patterns запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…