Briefing

Redis Best Practices: Namespace, TTL, and Avoiding KEYS

security
by Olivia Craft · Claude

Implement a key namespace convention and enforce TTLs for all Redis keys to prevent memory leaks.

What to do now

Create a CLAUDE.md file with the Redis key naming and TTL rules, and add a pre‑commit hook to reject bare SET commands.

Summary

The article outlines four key rules for safe Redis usage in production. First, it enforces a strict key namespace convention of app:env:entity:id[:attr] to prevent collisions and simplify debugging. Second, every cached key must be written with SETEX or SET … EX to guarantee an explicit TTL, and persistent keys are documented in a persistent_keys allowlist. Third, the KEYS command is banned in production; instead, SCAN with COUNT should be used to avoid blocking the server. Fourth, creating a new Redis() instance inside a request handler leaks file descriptors and can crash the box under load, so a shared client should be reused. The article also introduces a CLAUDE.md file that codifies these rules for automated code review. By following these guidelines, teams can avoid memory leaks, reduce latency, and maintain predictable cache behavior in high‑traffic environments.

Key changes

  • Namespace keys using app:env:entity:id[:attr] format to avoid collisions
  • Write all cached keys with SETEX or SET … EX to guarantee an explicit TTL
  • Document persistent keys in a persistent_keys allowlist with comments explaining no TTL
  • Replace KEYS with SCAN COUNT in production to avoid blocking the server
  • Reuse a shared Redis client instead of creating new instances per request to prevent file descriptor leaks
  • Add a CLAUDE.md file to enforce these rules in code review
  • Run a weekly audit with redis-cli ttl to detect keys without TTL
  • Reject bare SET commands in code review to enforce TTL usage

Affects

internal

Customer impact

Analyzing matches…

Ask about this story

Impact on an agency? Which customers? Compare historically Risks of waiting