You ask Claude to "add caching to the user profile endpoint," and 30 seconds later you ship something that looks fine in review:
-
SET user_42 <json>— flat key, no namespace, collides the moment a second service shares the cluster. - No TTL — the entry lives forever until
maxmemoryevicts your hottest keys. -
KEYS user_*in a cleanup job — single-threaded Redis stalls every other client for hundreds of ms. -
new Redis()inside the request handler — file descriptors leak and the box falls over at moderate load.
The model didn't fail. It pattern-matched on blog posts where Redis is a toy with twelve keys and zero ops concerns. Production makes each one a real incident.
A CLAUDE.md at the root of your repo fixes this. Claude Code reads it on every task. Cursor, Aider, and Copilot do the same. Below are four of the thirteen rules I drop into every Redis project — full set in the free gist linked at the end.
Rule 1 — Namespace every key: app:env:entity:id[:attr]
Why: Redis has no schema and no folders. The key is the namespace. Without a convention, debugging "what's this weird value?" requires MONITOR in production. With one, SCAN MATCH billing:prod:invoice:* answers it in one command.
Bad:
r.set("user_42", json.dumps(profile))
r.set("cart", json.dumps(cart))
r.set("lock", "1")
Good:
def key(*parts: str) -> str:
return ":".join(["billing", os.environ["ENV"], *parts])
r.setex(key("user", str(user_id), "profile"), 3600, json.dumps(profile))
r.setex(key("cart", str(user_id)), 86400, json.dumps(cart))
r.set(key("lock", "checkout", str(user_id)), "1", ex=30, nx=True)
Rule for CLAUDE.md:
All Redis keys follow `<app>:<env>:<entity>:<id>[:<attr>]`.
Use a `key()` helper — literal string keys are rejected in code review.
`:` is reserved as the separator. User input in a key segment is normalised
(lowercase, no whitespace, no colons) before joining.
Rule 2 — Every key has an explicit TTL — or a documented reason it doesn't
Why: A key without a TTL lives forever. AI happily writes SET cache:user:42 <json> and ships an unbounded memory leak. Six months later, INFO memory shows 40 GB of stale objects and your hottest keys are getting evicted to make room for data nobody has read since launch.
Bad:
r.set(key("cache", "user", str(uid)), json.dumps(profile))
# Lives forever. Compounds across millions of users.
Good:
# Expiry encoded at write time, never as a separate forgotten step.
r.setex(key("cache", "user", str(uid)), 3600, json.dumps(profile))
# Or, if you want SET semantics with NX/XX:
r.set(key("cache", "user", str(uid)), json.dumps(profile), ex=3600, nx=True)
Rule for CLAUDE.md:
Every cached key is written with `SETEX` or `SET ... EX <seconds>` — never bare `SET`.
Persistent keys (config, feature flags) live in a `persistent_keys` allowlist
and are documented in code with a comment explaining why no TTL applies.
A weekly audit runs `redis-cli --scan | xargs -L1 redis-cli ttl` and pages on
any key with `-1` outside the allowlist.
Rule 3 — Never KEYS in production — use SCAN with COUNT
Why: Redis is single-threaded for command execution. KEYS pattern* is O(N) and blocks the event loop. On a 10M-key instance it stalls every other client for seconds — your API p99 spikes, queues back up, and pages fire. AI reaches for KEYS because it's the first command on the docs page.
Bad:
# Stalls the entire Redis instance until it returns.
for k in r.keys("session:prod:*"):
r.delete(k)
Good:
# Cursor-based, incremental, never blocks.
cursor = 0
while True:
cursor, batch = r.scan(cursor=cursor, match="session:prod:*", count=500)
if batch:
r.delete(*batch) # batch delete in one round trip
if cursor == 0:
break
Rule for CLAUDE.md:
`KEYS` is forbidden outside test fixtures. CI greps `\bKEYS\b` and fails the build.
Replace with `SCAN 0 MATCH pattern COUNT 500` in a cursor loop.
Same rule for `HGETALL` (use `HSCAN`), `SMEMBERS` (`SSCAN`), `LRANGE 0 -1` (paginate).
Any O(N) command on a key whose size you don't bound is a production hazard.
Rule 4 — Pool connections — never open one per request
Why: TCP handshakes, AUTH round-trips, and TLS negotiation cost more than most Redis commands. A single pooled connection processes thousands of pipelined commands per second; a thousand fresh connections processes nothing because the kernel is busy with sockets and TIME_WAIT. AI generates new Redis() in the handler because each function "needs its own client."
Bad:
// Express middleware
app.get("/profile", async (req, res) => {
const r = new Redis(process.env.REDIS_URL); // fresh connection per request
const data = await r.get(`user:${req.userId}`);
res.json(JSON.parse(data));
});
Good:
// One client per process, instantiated at startup.
const redis = new Redis(process.env.REDIS_URL, {
maxRetriesPerRequest: 3,
enableOfflineQueue: false,
lazyConnect: false,
});
app.get("/profile", async (req, res) => {
const data = await redis.get(key("user", req.userId));
res.json(JSON.parse(data));
});
Rule for CLAUDE.md:
One Redis client (or pool) per process, instantiated at startup, injected via DI/context.
`max_connections` is set explicitly based on expected concurrency — never "unlimited."
Serverless processes use a connection-pooling proxy (Upstash, Redis Cloud's pooler) —
short-lived processes can't pool effectively on their own.
Health checks verify the pool is reused, not re-created.
How to Use These Rules
- Drop a
CLAUDE.mdat the root of the repo, next to yoursrc/and your Redis client wrapper. - Paste the rules. Edit what doesn't fit your stack (which client, which deployment, which monitoring).
- Restart Claude Code so it picks up the new context file. The same file works for Cursor, Aider, Codex, and Copilot Workspace.
The full set covers pipelining, Pub/Sub vs Streams, Lua atomicity, data-type selection, eviction policy, cluster hash tags, Sentinel vs Cluster, the secrets-in-Redis trap, and the metrics that catch every issue above before it pages someone.
Get the Rules
Free Redis gist with all 13 rules → gist.github.com/oliviacraft/eeabe2478ce0d44d2ce91f26bff537af
The 13 rules above are one chapter of the CLAUDE.md Rules Pack — 44 editions covering Go, Rust, Python, FastAPI, Next.js, React Native, Terraform, Docker, Kubernetes, PostgreSQL, GraphQL, Java, Redis, and more. Production-tested AI guardrails, packaged as drop-in CLAUDE.md files.
→ Get the full pack on Gumroad: oliviacraftlat.gumroad.com/l/skdgt — one-time payment, lifetime updates.
Top comments (0)