redis-cache-patterns
Skill2 starsChanged 28 days agoApache-2.0View on GitHub
Implements enterprise Redis caching strategies (cache-aside, write-through, stale-while-revalidate), distributed locking (Redlock), sliding-window rate limiting, and pub/sub streams.
- Reads credentials
1 other project uses a version of this.
Adopted by
Most recently taken up by
- TienDat-Vna/BackSpectheir own version, first seen Sep 28, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- TienDat-Vna/BackSpec★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository108 other files it gives its agents.
- AGENTS.mdAGENTS.md
- everything-gemini-maintainerSkill
- adversarial-fuzz-generatorSkill
- agent-evalsSkill
- ai-first-engineeringSkill
- alloydb-omni-vectorSkill
- apache-kafka-streamsSkill
- api-craftsmanSkill
- architecture-designerSkill
- argon-3d-game-engineSkill
- argon-3d-scene-architectSkill
- argon-procedural-asset-generatorSkill
- argon-visual-critique-loopSkill
- argo-workflowsSkill
- autonomous-incident-healerSkill
- axum-web-serviceSkill
- bigquery-vector-searchSkill
- browser-qa-testerSkill
- chromadb-vector-storeSkill
- cilium-ebpf-networkingSkill
- clickhouse-analyticsSkill
- cloud-deploy-canarySkill
- cloudflare-r2-object-storageSkill
- cloudflare-workersSkill
- cloud-run-agentsSkill
- context-cachingSkill
- context-distillation-compressorSkill
- context-warmerSkill
- continuous-learningSkill
- cost-oracle-finopsSkill
- cross-repo-swarm-syncSkill
- cve-remediation-orchestratorSkill
- database-architectSkill
- dataproc-spark-analyticsSkill
- dbt-transformationSkill
- debezium-cdcSkill
- devops-pipelineSkill
- distributed-rate-limitingSkill
- docker-compose-orchestratorSkill
- duckdb-local-olapSkill
- dynamic-thinking-allocationSkill
- ebpf-microvm-sandboxSkill
- ebpf-sandbox-enforcerSkill
- elephant-goldfish-modelSkill
- envoy-ai-gatewaySkill
- ephemeral-swarm-orchestratorSkill
- fastapi-productionSkill
- fullstack-nextjsSkill
- game-audio-synthesizerSkill
- game-studioSkill
- gemini-function-callingSkill
- gemini-groundingSkill
- gemini-live-audio-transcriberSkill
- gemini-live-multimodalSkill
- gemini-live-screen-visionSkill
- gemini-multimodalSkill
- genetic-prompt-cross-pollinatorSkill
- git-craftsmanSkill
- github-opsSkill
- google-axSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
When calculating TTLs, always inject jitter (random variance) to prevent simultaneous mass-expiration of keys:
- Very specific: line 49
Never release a Redis lock with a plain DEL command, as doing so can accidentally delete a lock held by another process if the operation …
- Very specific: line 157
Structured Namespaces: Use colons for domain hierarchy (e.g., user:1042:profile, session:tok_9918).
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Redis Cache Patterns & Distributed Primitives
This skill provides production-tested patterns for high-throughput Redis caching, concurrency coordination, and resilient distributed systems.
🚀 Key Patterns
1. Cache-Aside with Jitter (Preventing Cache Stampedes)
When calculating TTLs, always inject jitter (random variance) to prevent simultaneous mass-expiration of keys:
import { Redis } from 'ioredis';
const redis = new Redis(process.env.REDIS_URL!);
export async function getCachedEntity<T>(
key: string,
fetchFn: () => Promise<T>,
baseTtlSeconds: number = 3600
): Promise<T> {
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached) as T;
}
const freshData = await fetchFn();
// Inject 10-15% random jitter to distribute TTL expiration spikes
const jitter = Math.floor(Math.random() * (baseTtlSeconds * 0.15));
const ttl = baseTtlSeconds + jitter;
await redis.set(key, JSON.stringify(freshData), 'EX', ttl);
return freshData;
}2. Distributed Locking with Safe Lua Release
Never release a Redis lock with a plain DEL command, as doing so can accidentally delete a lock held by another process if the operation took longer than the TTL. Use atomic Lua verification:
import { randomUUID } from 'crypto';
const RELEASE_LOCK_SCRIPT = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`;
export async function withDistributedLock<T>(
lockKey: string,
ttlMs: number,
task: () => Promise<T>
): Promise<T> {
const lockToken = randomUUID();
const acquired = await redis.set(lockKey, lockToken, 'PX', ttlMs, 'NX');
if (!acquired) {
throw new Error(`Failed to acquire distributed lock for key: ${lockKey}`);
}
try {
return await task();
} finally {
// Atomically release only if the token matches
await redis.eval(RELEASE_LOCK_SCRIPT, 1, lockKey, lockToken);
}
}3. Sliding-Window Rate Limiting (Sorted Sets)
Sliding-window rate limiters prevent burst exploitation around window boundaries:
export async function isRateLimited(
identifier: string,
limit: number,
windowSeconds: number
): Promise<{ allowed: boolean; remaining: number }> {
const now = Date.now();
const clearBefore = now - windowSeconds * 1000;
const key = `ratelimit:${identifier}`;
const pipeline = redis.pipeline();
pipeline.zremrangebyscore(key, 0, clearBefore);
pipeline.zadd(key, now, `${now}-${Math.random()}`);
pipeline.zcard(key);
pipeline.expire(key, windowSeconds);
const results = await pipeline.exec();
const count = (results?.[2]?.[1] as number) || 0;
return {
allowed: count <= limit,
remaining: Math.max(0, limit - count),
};
}4. Redis Streams with Consumer Groups
For reliable, decoupled background tasks without message loss:
// Producer: Append event to stream
export async function publishEvent(streamName: string, event: Record<string, string>) {
return await redis.xadd(streamName, '*', ...Object.entries(event).flat());
}
// Consumer: Read events with acknowledgments
export async function consumeEvents(
streamName: string,
groupName: string,
consumerName: string,
handler: (id: string, fields: string[]) => Promise<void>
) {
const response = await redis.xreadgroup(
'GROUP', groupName, consumerName,
'COUNT', 10,
'BLOCK', 2000,
'STREAMS', streamName, '>'
);
if (!response) return;
for (const [, messages] of response as any[]) {
for (const [id, fields] of messages) {
await handler(id, fields);
// Acknowledge processed message
await redis.xack(streamName, groupName, id);
}
}
}5. Memory & Performance Best Practices
- Structured Namespaces: Use colons for domain hierarchy (e.g.,
user:1042:profile,session:tok_9918). - Use Hashes for Objects: Storing small objects in Redis
HSETsaves ~40% memory compared to JSON strings due to memory-efficientziplist/listpackencodings. - Always Configure Eviction Policy: In
redis.conf, setmaxmemory-policy volatile-lruorallkeys-lruto avoid hard out-of-memory errors.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

