redis-best-practices
Skill275 starsChanged 35 days agoApache-2.0View on GitHub
Redis development best practices for caching, data structures, and high-performance key-value operations
3 other projects use a version of this.
Adopted by
Most recently taken up by
- JetBrains/junie-extensionstheir own version, first seen Oct 13, 2026
- baekenough/oh-my-customcodetheir own version, first seen Oct 3, 2026
- simba-git/redis-best-practicestheir own version, first seen Jan 24, 2026
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- baekenough/oh-my-customcode★ 42same name
- JetBrains/junie-extensions★ 23same name
- simba-git/redis-best-practices★ 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 repository264 other files it gives its agents.
- accessibility-a11ySkill
- alpine-jsSkill
- analytics-data-analysisSkill
- android-developmentSkill
- angular-developmentSkill
- angularSkill
- anime-jsSkill
- anthropic-claude-developmentSkill
- api-developmentSkill
- apollo-graphqlSkill
- aspnet-coreSkill
- astroSkill
- auth0-authenticationSkill
- autogen-developmentSkill
- automl-hyperparameter-optimizationSkill
- aws-developmentSkill
- azureSkill
- backend-developmentSkill
- bash-scriptingSkill
- beautifulsoup-parsingSkill
- bitbucket-workflowSkill
- blazorSkill
- blender-python-addonSkill
- blockchainSkill
- bootstrapSkill
- business-central-developmentSkill
- cheerio-parsingSkill
- chrome-extension-developmentSkill
- ci-cd-best-practicesSkill
- clean-architectureSkill
- clean-codeSkill
- clerk-authenticationSkill
- cloudflare-developmentSkill
- computer-vision-opencvSkill
- convexSkill
- cppSkill
- c-sharpSkill
- cssSkill
- cypressSkill
- data-analysis-jupyterSkill
- data-analystSkill
- data-jupyter-pythonSkill
- deep-learning-pythonSkill
- deep-learning-pytorchSkill
- deep-learningSkill
- deno-typescriptSkill
- design-systemsSkill
- devopsSkill
- django-pythonSkill
- django-rest-api-developmentSkill
- dockerSkill
- dotnetSkill
- drizzle-ormSkill
- drupal-developmentSkill
- elasticsearch-best-practicesSkill
- electron-developmentSkill
- elixirSkill
- embedded-stm32Skill
- esbuild-bundlerSkill
- ethereumSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
25 rules. 0 are common, 25 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 3 edited versions we read keep these.
25
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Use Redis for caching, session storage, real-time analytics, and message queuing
- Distinctive: line 21
Use colons as namespace separators
- Distinctive: line 23
Keep keys short but descriptive
- Distinctive: line 24
Use consistent naming patterns across your application
- Distinctive: line 41
Use for simple key-value storage, counters, and caching
- Distinctive: line 42
Consider using MGET/MSET for batch operations
- Distinctive: line 58
Use for objects with multiple fields
- Distinctive: line 79
Use for queues, recent items, and activity feeds
- Distinctive: line 80
Consider blocking operations for queue consumers
- Distinctive: line 100
Use for unique collections, tags, and relationships
- Distinctive: line 121
Use for leaderboards, priority queues, and time-series data
- Distinctive: line 143
Use for event streaming and log data
- Distinctive: line 214
Always set TTL on cache keys
- Distinctive: line 215
Use jitter to prevent thundering herd
- Distinctive: line 216
Consider sliding expiration for session data
- Distinctive: line 267
Use for complex atomic operations
- Distinctive: line 312
Use replicas for read scaling
- Distinctive: line 325
Use for automatic failover
- Distinctive: line 330
Use for horizontal scaling
- Distinctive: line 332
Use hash tags for related keys
- Distinctive: line 366
Use TLS for connections
- Distinctive: line 428
Use pipelining for batch operations
- Distinctive: line 429
Avoid large keys (>100KB values)
- Distinctive: line 430
Use SCAN instead of KEYS in production
- Distinctive: line 432
Consider using RedisJSON for complex JSON operations
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Redis Best Practices
Core Principles
- Use Redis for caching, session storage, real-time analytics, and message queuing
- Choose appropriate data structures for your use case
- Implement proper key naming conventions and expiration policies
- Design for high availability and persistence requirements
- Monitor memory usage and optimize for performance
Key Naming Conventions
- Use colons as namespace separators
- Include object type and identifier in key names
- Keep keys short but descriptive
- Use consistent naming patterns across your application
# Good key naming examples
user:1234:profile
user:1234:sessions
order:5678:items
cache:api:products:list
queue:email:pending
session:abc123def456
rate_limit:api:user:1234Data Structures
Strings
- Use for simple key-value storage, counters, and caching
- Consider using MGET/MSET for batch operations
# Simple caching
SET cache:user:1234 '{"name":"John","email":"john@example.com"}' EX 3600
# Counters
INCR stats:pageviews:homepage
INCRBY stats:downloads:file123 5
# Atomic operations
SETNX lock:resource:456 "owner:abc" EX 30Hashes
- Use for objects with multiple fields
- More memory-efficient than multiple string keys
- Supports partial updates
# Store user profile
HSET user:1234 name "John Doe" email "john@example.com" created_at "2024-01-15"
# Get specific fields
HGET user:1234 email
HMGET user:1234 name email
# Increment numeric fields
HINCRBY user:1234 login_count 1
# Get all fields
HGETALL user:1234Lists
- Use for queues, recent items, and activity feeds
- Consider blocking operations for queue consumers
# Message queue
LPUSH queue:emails '{"to":"user@example.com","subject":"Welcome"}'
RPOP queue:emails
# Blocking pop for workers
BRPOP queue:emails 30
# Recent activity (keep last 100)
LPUSH user:1234:activity "viewed product 567"
LTRIM user:1234:activity 0 99
# Get recent items
LRANGE user:1234:activity 0 9Sets
- Use for unique collections, tags, and relationships
- Supports set operations (union, intersection, difference)
# User tags/interests
SADD user:1234:interests "technology" "music" "travel"
# Check membership
SISMEMBER user:1234:interests "music"
# Find common interests
SINTER user:1234:interests user:5678:interests
# Online users tracking
SADD online:users "user:1234"
SREM online:users "user:1234"
SMEMBERS online:usersSorted Sets
- Use for leaderboards, priority queues, and time-series data
- Elements sorted by score
# Leaderboard
ZADD leaderboard:game1 1500 "player:123" 2000 "player:456" 1800 "player:789"
# Get top 10
ZREVRANGE leaderboard:game1 0 9 WITHSCORES
# Get player rank
ZREVRANK leaderboard:game1 "player:123"
# Time-based data (score = timestamp)
ZADD events:user:1234 1705329600 "login" 1705330000 "purchase"
# Get events in time range
ZRANGEBYSCORE events:user:1234 1705329600 1705333200Streams
- Use for event streaming and log data
- Supports consumer groups for distributed processing
# Add events to stream
XADD events:orders * customer_id 1234 product_id 567 amount 99.99
# Read from stream
XREAD COUNT 10 STREAMS events:orders 0
# Consumer groups
XGROUP CREATE events:orders order-processors $ MKSTREAM
XREADGROUP GROUP order-processors worker1 COUNT 10 STREAMS events:orders >
# Acknowledge processed messages
XACK events:orders order-processors 1234567890-0Caching Patterns
Cache-Aside Pattern
# Pseudo-code for cache-aside
def get_user(user_id):
# Try cache first
cached = redis.get(f"cache:user:{user_id}")
if cached:
return json.loads(cached)
# Cache miss - fetch from database
user = database.get_user(user_id)
# Store in cache with expiration
redis.setex(f"cache:user:{user_id}", 3600, json.dumps(user))
return userWrite-Through Pattern
def update_user(user_id, data):
# Update database
database.update_user(user_id, data)
# Update cache
redis.setex(f"cache:user:{user_id}", 3600, json.dumps(data))Cache Invalidation
# Delete specific cache
DEL cache:user:1234
# Delete by pattern (use with caution in production)
# Use SCAN instead of KEYS for large datasets
SCAN 0 MATCH cache:user:* COUNT 100
# Tag-based invalidation using sets
SADD cache:tags:user:1234 "cache:user:1234:profile" "cache:user:1234:orders"
# Invalidate all related caches
SMEMBERS cache:tags:user:1234
# Then delete each keyExpiration and Memory Management
TTL Best Practices
- Always set TTL on cache keys
- Use jitter to prevent thundering herd
- Consider sliding expiration for session data
# Set with expiration
SET cache:data:123 "value" EX 3600
# Set expiration on existing key
EXPIRE cache:data:123 3600
# Check TTL
TTL cache:data:123
# Persist key (remove expiration)
PERSIST cache:data:123Memory Management
# Check memory usage
INFO memory
# Get key memory usage
MEMORY USAGE cache:large:object
# Configure max memory policy
CONFIG SET maxmemory 2gb
CONFIG SET maxmemory-policy allkeys-lruTransactions and Atomicity
MULTI/EXEC Transactions
# Transaction block
MULTI
INCR stats:views
LPUSH recent:views "page:123"
EXEC
# Watch for optimistic locking
WATCH user:1234:balance
balance = GET user:1234:balance
MULTI
SET user:1234:balance (balance - 100)
EXECLua Scripts
- Use for complex atomic operations
- Scripts execute atomically
-- Rate limiting script
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current = tonumber(redis.call('GET', key) or '0')
if current >= limit then
return 0
end
redis.call('INCR', key)
if current == 0 then
redis.call('EXPIRE', key, window)
end
return 1# Execute Lua script
EVAL "return redis.call('GET', KEYS[1])" 1 mykeyPub/Sub and Messaging
# Publisher
PUBLISH channel:notifications '{"type":"alert","message":"New order"}'
# Subscriber
SUBSCRIBE channel:notifications
# Pattern subscription
PSUBSCRIBE channel:*High Availability
Replication
- Use replicas for read scaling
- Configure proper persistence on master
# On replica
REPLICAOF master_host 6379
# Check replication status
INFO replicationRedis Sentinel
- Use for automatic failover
- Deploy at least 3 Sentinel instances
Redis Cluster
- Use for horizontal scaling
- Data automatically sharded across nodes
- Use hash tags for related keys
# Hash tags ensure keys go to same slot
SET {user:1234}:profile "data"
SET {user:1234}:settings "data"Persistence
RDB Snapshots
# Manual snapshot
BGSAVE
# Configure automatic snapshots
CONFIG SET save "900 1 300 10 60 10000"AOF (Append-Only File)
# Enable AOF
CONFIG SET appendonly yes
CONFIG SET appendfsync everysec
# Rewrite AOF
BGREWRITEAOFSecurity
- Require authentication
- Use TLS for connections
- Bind to specific interfaces
- Disable dangerous commands
# Set password
CONFIG SET requirepass "your_strong_password"
# Authenticate
AUTH your_strong_password
# Rename dangerous commands (in redis.conf)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command KEYS ""Monitoring
# Server info
INFO
# Memory stats
INFO memory
# Client connections
CLIENT LIST
# Slow log
SLOWLOG GET 10
# Monitor commands (debug only)
MONITOR
# Key count per database
INFO keyspaceConnection Management
- Use connection pooling
- Set appropriate timeouts
- Handle reconnection gracefully
# Python example with connection pool
import redis
pool = redis.ConnectionPool(
host='localhost',
port=6379,
max_connections=50,
socket_timeout=5,
socket_connect_timeout=5
)
redis_client = redis.Redis(connection_pool=pool)Performance Tips
- Use pipelining for batch operations
- Avoid large keys (>100KB values)
- Use SCAN instead of KEYS in production
- Monitor and optimize memory usage
- Consider using RedisJSON for complex JSON operations
# Pipeline example (pseudo-code)
pipe = redis.pipeline()
pipe.get("key1")
pipe.get("key2")
pipe.set("key3", "value")
results = pipe.execute()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.

