redis-best-practices
Redis development best practices for caching, data structures, and high-performance key-value operations
What this skill does
# 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:1234
```
## Data Structures
### Strings
- Use for simple key-value storage, counters, and caching
- Consider using MGET/MSET for batch operations
```redis
# Simple caching
SET cache:user:1234 '{"name":"John","email":"[email protected]"}' EX 3600
# Counters
INCR stats:pageviews:homepage
INCRBY stats:downloads:file123 5
# Atomic operations
SETNX lock:resource:456 "owner:abc" EX 30
```
### Hashes
- Use for objects with multiple fields
- More memory-efficient than multiple string keys
- Supports partial updates
```redis
# Store user profile
HSET user:1234 name "John Doe" email "[email protected]" 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:1234
```
### Lists
- Use for queues, recent items, and activity feeds
- Consider blocking operations for queue consumers
```redis
# Message queue
LPUSH queue:emails '{"to":"[email protected]","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 9
```
### Sets
- Use for unique collections, tags, and relationships
- Supports set operations (union, intersection, difference)
```redis
# 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:users
```
### Sorted Sets
- Use for leaderboards, priority queues, and time-series data
- Elements sorted by score
```redis
# 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 1705333200
```
### Streams
- Use for event streaming and log data
- Supports consumer groups for distributed processing
```redis
# 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-0
```
## Caching Patterns
### Cache-Aside Pattern
```python
# 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 user
```
### Write-Through Pattern
```python
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
```redis
# 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 key
```
## Expiration and Memory Management
### TTL Best Practices
- Always set TTL on cache keys
- Use jitter to prevent thundering herd
- Consider sliding expiration for session data
```redis
# 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:123
```
### Memory Management
```redis
# 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-lru
```
## Transactions and Atomicity
### MULTI/EXEC Transactions
```redis
# 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)
EXEC
```
### Lua Scripts
- Use for complex atomic operations
- Scripts execute atomically
```lua
-- 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
```
```redis
# Execute Lua script
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
```
## Pub/Sub and Messaging
```redis
# 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
```redis
# On replica
REPLICAOF master_host 6379
# Check replication status
INFO replication
```
### Redis 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
```redis
# Hash tags ensure keys go to same slot
SET {user:1234}:profile "data"
SET {user:1234}:settings "data"
```
## Persistence
### RDB Snapshots
```redis
# Manual snapshot
BGSAVE
# Configure automatic snapshots
CONFIG SET save "900 1 300 10 60 10000"
```
### AOF (Append-Only File)
```redis
# Enable AOF
CONFIG SET appendonly yes
CONFIG SET appendfsync everysec
# Rewrite AOF
BGREWRITEAOF
```
## Security
- Require authentication
- Use TLS for connections
- Bind to specific interfaces
- Disable dangerous commands
```redis
# 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
```redis
# 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 keyspace
```
## Connection Management
- Use connection pooling
- Set appropriate timeouts
- Handle reconnection gracefully
```python
# 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 valRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.