skills/redis-patterns-expert/SKILL.md
Use when designing caching strategies (cache-aside, write-through, write-behind), implementing distributed locks, building rate limiters, leaderboards, real-time streams (XADD/consumer groups), pub/sub, or tuning eviction policies. Triggers: thundering-herd on cache miss, dogpile on key expiry, Redlock vs SET-NX-PX choice, sliding-window rate limiter, hot-key on a single cluster slot, big-key blowup, MULTI/EXEC across slots, KEYS in production. NOT for Redis Cluster operations/admin (different domain), embedded KV (SQLite, leveldb), in-process LRU caches, or Memcached.
npx skillsauth add curiositech/windags-skills redis-patterns-expertInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Redis is a data-structure server. The interesting part isn't the commands — it's the patterns. Most of the trouble comes from treating Redis as a database when you should treat it as a coordination primitive, or vice versa.
Cache-aside (most common):
async function getUser(id: string) {
const cached = await redis.get(`user:${id}`);
if (cached) return JSON.parse(cached);
const fresh = await db.users.findById(id);
// SET with EX in one command — never SET then EXPIRE.
await redis.set(`user:${id}`, JSON.stringify(fresh), 'EX', 300 + Math.floor(Math.random() * 60));
return fresh;
}
The + random() jitter prevents the dogpile when many keys expire together. Without it, every cache key set during a deploy expires within the same minute 5 minutes later → thundering herd.
Stale-while-revalidate with a soft + hard TTL:
const SOFT = 300, HARD = 600;
const entry = await redis.get(key);
if (entry) {
const { value, mtime } = JSON.parse(entry);
if (Date.now() - mtime < SOFT * 1000) return value;
// Stale but valid — refresh in background, return cached.
void refresh(key);
return value;
}
// No entry — block on origin.
Single-flight — collapse concurrent regeneration to one origin call:
async function getUserSingleflight(id: string) {
const cacheKey = `user:${id}`;
const lockKey = `user:${id}:lock`;
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
const lockAcquired = await redis.set(lockKey, '1', 'NX', 'EX', 5);
if (!lockAcquired) {
// Someone else is fetching. Sleep + retry the cache.
await sleep(50);
return getUserSingleflight(id);
}
try {
const fresh = await db.users.findById(id);
await redis.set(cacheKey, JSON.stringify(fresh), 'EX', 300);
return fresh;
} finally {
await redis.del(lockKey);
}
}
Single-instance Redis lock with safe release:
-- release.lua
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end
const token = crypto.randomUUID();
const acquired = await redis.set(lockKey, token, 'NX', 'PX', leaseMs);
if (!acquired) throw new Error('lock not acquired');
try {
// ... critical section, must complete before leaseMs ...
} finally {
await redis.eval(releaseScript, 1, lockKey, token);
}
The token prevents you from releasing someone else's lock if your work overran the lease. Don't use GET + DEL separately — that's a TOCTOU race.
Redlock (multi-instance) is contentious; for most applications a single Redis primary with a finite lease is fine. If you need stronger guarantees, use a real consensus system (etcd, Consul).
-- sliding-window.lua
-- KEYS[1] = bucket key ARGV[1] = window seconds ARGV[2] = limit ARGV[3] = now-ms
local now = tonumber(ARGV[3])
local window = tonumber(ARGV[1]) * 1000
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
local count = redis.call('ZCARD', KEYS[1])
if count >= tonumber(ARGV[2]) then
return 0
end
redis.call('ZADD', KEYS[1], now, now)
redis.call('PEXPIRE', KEYS[1], window)
return 1
Token bucket is cheaper if you can tolerate burstiness; sliding window is fairer.
// Top scorers
await redis.zincrby('game:scores', points, userId);
await redis.zrevrange('game:scores', 0, 9, 'WITHSCORES');
// Time-series with score = epoch
await redis.zadd('user:42:events', Date.now(), JSON.stringify(event));
await redis.zrangebyscore('user:42:events', Date.now() - 3600_000, '+inf');
// Cap to last 1000 events
await redis.zremrangebyrank('user:42:events', 0, -1001);
Durable queue with multiple consumers and at-least-once delivery:
// Producer
await redis.xadd('jobs', '*', 'type', 'send_email', 'to', user.email);
// One-time setup
await redis.xgroup('CREATE', 'jobs', 'workers', '$', 'MKSTREAM');
// Consumer
const messages = await redis.xreadgroup(
'GROUP', 'workers', `worker-${pid}`,
'COUNT', 10, 'BLOCK', 5000,
'STREAMS', 'jobs', '>',
);
for (const [stream, entries] of messages ?? []) {
for (const [id, fields] of entries) {
try {
await handle(fields);
await redis.xack('jobs', 'workers', id);
} catch {
// No XACK → message stays in the PEL (pending entries list).
}
}
}
// Reclaim work from a crashed peer
const pending = await redis.xpending('jobs', 'workers', 'IDLE', 60000, '-', '+', 100);
for (const { id } of pending) {
await redis.xclaim('jobs', 'workers', `worker-${pid}`, 60000, id);
}
// Cap stream growth
await redis.xadd('jobs', 'MAXLEN', '~', 100000, '*', ...fields);
The ~ makes MAXLEN approximate (cheaper). PEL is your story for poison messages — set a max-deliveries threshold and dead-letter beyond it.
const sub = redis.duplicate(); // SUBSCRIBE blocks the connection
await sub.subscribe('user-events');
sub.on('message', (channel, payload) => handle(JSON.parse(payload)));
await redis.publish('user-events', JSON.stringify({ userId, kind: 'login' }));
At-most-once delivery; subscribers offline at publish time miss the message. For durable jobs, use Streams.
EVAL ships the script every time; EVALSHA after SCRIPT LOAD is faster. Atomic — the whole script runs without other clients interleaving. KEYS are passed for cluster routing; non-key arguments go in ARGV. Cluster requires all KEYS to live on the same slot — use hash tags {user:42} for related keys.
maxmemory 100mb
maxmemory-policy allkeys-lru
| Policy | When to use |
|--------|-------------|
| noeviction | Redis as durable store (you should be using a real DB). |
| allkeys-lru | Pure cache. |
| allkeys-lfu | Cache where some keys are hot for a long time. |
| volatile-lru | Mixed: some keys must persist (no TTL), evict only TTL'd ones. |
| volatile-ttl | Evict shortest-TTL first; useful for staged data. |
Symptom: Latency spikes correlate with admin commands.
Diagnosis: KEYS * blocks the server while it scans every key.
Fix: SCAN cursor-based iteration. For Cluster, scan each shard.
DEL on a 10M-item structureSymptom: Single command takes seconds; replicas lag; clients time out.
Diagnosis: DEL is synchronous in the main thread.
Fix: UNLINK (non-blocking, async free). For sorted sets, batch via ZSCAN + ZREM chunks.
SET then EXPIRESymptom: Occasional keys with no TTL.
Diagnosis: Crash between SET and EXPIRE leaves the key forever.
Fix: SET key val EX seconds in one command.
Symptom: Single hash >1M fields; replication breaks; OOM on restart.
Diagnosis: Unbounded growth — usually session data or user-item maps.
Fix: Shard by user prefix (session:abc:user:42), or move to a sorted-set + TTL pattern.
Symptom: Workers restart, miss the work, customer support tickets. Diagnosis: Pub/sub is at-most-once. Subscribers offline at publish lose the message. Fix: Use Streams + consumer groups. Always.
Symptom: One node CPU at 100%, others idle.
Diagnosis: Cache key collision → all reads on one slot.
Fix: Add a per-key salt or shard the key (user:42:cache:0, …:1) and randomize reads.
KEYS in production code (verify by linter or grep).MAXLEN ~ N.maxmemory and maxmemory-policy set explicitly per-environment.UNLINK over DEL for any structure with thousands of items.webhook-receiver-design (use a DB unique constraint instead).lru-cache npm) — single-node, no shared state.data-ai
license: Apache-2.0 NOT for unrelated tasks outside this domain.
tools
Drawing the `'use client'` boundary correctly in React Server Components apps (Next.js App Router, RSC frameworks) — leaf-pushing, slot composition, serialization rules, and environment poisoning prevention. Grounded in react.dev and Next.js 16 docs.
development
Use when designing rate limiting for an API, choosing between token bucket / sliding window / leaky bucket / fixed window, implementing it in Redis, deciding edge (Cloudflare/Upstash) vs origin enforcement, sizing per-user vs per-IP vs per-endpoint quotas, returning the right 429 response with Retry-After, or fixing the boundary-burst bug in fixed-window limiters. Triggers: 429 too many requests, INCR + EXPIRE, ZADD + ZREMRANGEBYSCORE + ZCARD, X-RateLimit-Remaining header, Cloudflare WAF rate limiting rules, Upstash @upstash/ratelimit, leaky bucket shaping vs policing, distributed rate limiter consistency. NOT for DDoS mitigation specifically (different scale), CAPTCHA / bot management, full WAF design, or per-user quota billing.
tools
Use when designing or fixing the retrieval side of a RAG system, choosing chunking strategy (fixed-size / recursive / semantic), implementing hybrid search (BM25 + dense) with RRF fusion, adding a cross-encoder reranker, evaluating with RAGAS, or running an index-freshness pipeline. Triggers: "RAG keeps citing the wrong doc", chunk size 512 tokens with overlap, RRF reciprocal rank fusion, dense+sparse hybrid, cross-encoder rerank top-5, RAGAS faithfulness / context precision, voyage-3-large vs text-embedding-3-large, daily / hourly reindex cadence. NOT for fine-tuning vs RAG decision (separate skill), agentic tool-use designs, vector DB operational tuning, or general LLM prompt engineering.