Redis Data Structures and Key Patterns
| Field | Value |
|---|---|
| Type | Skill Resource |
| Source | ~/.copilot/skills/database/references/redis.md |
| Description | Not specified |
Source Content
Redis Data Structures and Key Patterns
This is a lighter reference for Redis fundamentals; Postgres is the primary engine in this skill. Expand this reference as caching and real-time workloads appear.
Data Structures
Redis is a key-value cache and data structure server. Choose the right structure for your access pattern.
Strings
Simplest: atomic values, counters, session data.
SET key value [EX seconds] [NX|XX]GET keyINCR counterDECR counterAPPEND key " more"STRLEN keyExample: Session storage
SET session:abc123def "user_id=42&name=Alice&cart=[]" EX 3600GET session:abc123defHashes
Object-like: store multiple fields per key.
HSET user:123 name Alice email alice@example.com age 30HGET user:123 nameHGETALL user:123HINCRBY user:123 age 1HDEL user:123 ageBetter than strings for structured data; reduces key explosion.
Lists
Ordered sequences: queues, logs, leaderboards.
LPUSH mylist value1 value2 value3 -- Push to headRPUSH mylist value4 -- Push to tailLLEN mylistLRANGE mylist 0 -1 -- All elementsLPOP mylist -- Pop from headRPOP mylist -- Pop from tailLTRIM mylist 0 99 -- Keep first 100 elementsExample: Job queue
LPUSH jobs:pending '{"task": "send_email", "to": "alice@example.com"}'RPOP jobs:pending -- Consumer pulls jobs from tailSets
Unordered, unique values: tags, memberships, relationships.
SADD myset member1 member2 member3SMEMBERS mysetSCARD mysetSISMEMBER myset member1SREM myset member1SINTER set1 set2 -- IntersectionSUNION set1 set2 -- UnionSDIFF set1 set2 -- DifferenceExample: User followers
SADD followers:alice bob charlie daveSADD followers:bob alice charlieSINTER followers:alice followers:bob -- Mutual followersSorted Sets
Ordered by score: leaderboards, time-series, priority queues.
ZADD leaderboard 100 alice 95 bob 85 charlieZRANGE leaderboard 0 -1 -- By score ascendingZREVRANGE leaderboard 0 -1 -- By score descendingZRANK leaderboard alice -- Position ascendingZREVRANK leaderboard alice -- Position descendingZSCORE leaderboard aliceZINCRBY leaderboard 10 alice -- Increment scoreZREM leaderboard aliceZCOUNT leaderboard 80 100 -- Count in score rangeExample: Leaderboard
ZADD game:scores 1500 player_1 1200 player_2 950 player_3ZREVRANGE game:scores 0 9 WITHSCORES -- Top 10 with scoresStreams (Redis 5.0+)
Time-series event log: messages, metrics, activity tracking.
XADD mystream * field1 value1 field2 value2XLEN mystreamXRANGE mystream - + -- All messagesXREAD COUNT 10 STREAMS mystream 0 -- Read first 10XDEL mystream message_idExample: Activity log
XADD user:123:activity * action "login" ip "192.168.1.1" timestamp "2024-01-15T10:00:00Z"XRANGE user:123:activity - + LIMIT 10 -- Recent 10 activitiesKey Naming Patterns
Use colons to organize related keys:
-- User datauser:123:name Aliceuser:123:email alice@example.com-- Or hash:HSET user:123 name Alice email alice@example.com
-- Sessionsession:abc123def
-- Cachecache:product:456cache:user:789:profile
-- Counterscounter:api:requests:todaycounter:page:visits:article_1
-- Queuesqueue:email:pendingqueue:notifications:retry
-- Sets (relationships)followers:alicefollowing:alice
-- Leaderboardsleaderboard:weekly:scoresleaderboard:alltime:scores
-- Sorted sets (time-series)metrics:api:latency:2024-01-15metrics:api:errors:2024-01-15Expiration (Time-To-Live)
Every key can auto-expire. Useful for sessions, caches, temporary data.
SET temp_key value EX 3600 -- Expire in 3600 seconds (1 hour)SET temp_key value PX 3600000 -- Expire in 3600000 millisecondsEXPIRE key 60 -- Set expiration on existing keyTTL key -- Check remaining seconds (-1 = no expiry, -2 = expired)PERSIST key -- Remove expirationExample: Session with auto-expiry
SET session:user123 '{"user_id":123,"role":"admin"}' EX 1800 -- 30 minPipeline and Transactions
Pipeline (Batch Commands)
Send multiple commands at once for efficiency:
MULTIINCR counter:api:requestsZADD leaderboard 1 player_1HSET user:123 last_action "api_call"EXECTransactions (WATCH for Optimistic Locking)
WATCH mykey-- Check valueGET mykey-- If unchanged, executeMULTISET mykey newvalueINCR counterEXEC -- Succeeds only if mykey wasn't modifiedEviction Policies
When Redis hits maxmemory, it evicts keys based on the policy:
CONFIG SET maxmemory-policy allkeys-lru -- Evict least recently used keyCONFIG SET maxmemory-policy volatile-lru -- Evict LRU key with TTLCONFIG SET maxmemory-policy volatile-ttl -- Evict key with shortest TTLPolicies:
noeviction— Error if full (default).allkeys-lru— Evict any key, LRU order.allkeys-lfu— Evict any key, least frequently used.volatile-lru— Evict expiring keys, LRU order.volatile-lfu— Evict expiring keys, LFU order.volatile-ttl— Evict expiring keys with shortest TTL.random— Evict any random key.
Recommendation: Use volatile-lru or allkeys-lfu for caches; noeviction for critical data backed by persistence.
Persistence
Redis is in-memory; enable persistence to survive restarts.
RDB (Snapshots)
Periodic full snapshots. Fast recovery, simple, but can lose recent writes.
SAVE -- Blocking snapshotBGSAVE -- Non-blocking background snapshotAOF (Append-Only File)
Write-ahead log; more durable but slower writes.
CONFIG SET appendonly yes -- Enable AOFCONFIG SET appendfsync everysec -- Sync every second (good balance)Recommendation: Use BGSAVE for backups; enable AOF on production for durability.
Pub/Sub (Simple Messaging)
Publish messages to channels; subscribers receive immediately (no persistence).
-- SubscriberSUBSCRIBE channel:notifications-- (receives messages in real-time)
-- PublisherPUBLISH channel:notifications '{"type":"order_shipped","order_id":123}'Not suitable for reliable queues. Use Streams for persistent event logs.
When to Use Redis
Good for:
- Session storage (user auth, cart, preferences).
- Caching (database query results, API responses).
- Rate limiting (counter per IP, per user).
- Real-time analytics (counters, leaderboards).
- Job queues and task processing.
- Real-time pub/sub messaging.
- Temporary data (OTPs, password reset tokens).
Don’t use Redis for:
- Primary data storage (use Postgres/MySQL).
- Durable event logs (use Kafka or Streams with AOF).
- Complex queries or JOINs.
- Very large datasets (memory is expensive).
Common Patterns
Rate Limiting (Sliding Window)
INCR rate_limit:ip:192.168.1.1EXPIRE rate_limit:ip:192.168.1.1 60 -- 1-second window-- Check: if value > limit, rejectDistributed Lock
SET lock:resource "unique_token" NX EX 10-- If successful, you have the lock for 10 seconds-- Do workDEL lock:resource -- ReleaseLeaderboard with Time Decay
-- Every game, increment by scoreZADD leaderboard:weekly <score> <player>-- Every week, archive and resetRENAME leaderboard:weekly leaderboard:weekly:old-- New week starts freshPerformance Tips
- Use pipelining for batch operations.
- Set sensible TTLs to avoid memory bloat.
- Monitor memory usage:
INFO memory. - Use hashes instead of multiple strings for related data.
- Prefer sorted sets over lists for ordered data you query.
- Keep individual values < 1 MB.
- Use AOF with
everysecfor persistence without killing throughput.
References
- Redis Documentation
- Redis Data Types
- Redis Commands
- Redis Patterns — common use cases