Pins this version in aipm.package.json and aipm-lock.json.
aipm add @affaan-m/redis-patterns@1.0.0
Without project tracking
Writes the skill files only. Add --no-init to skip aipm.package.json and the lockfile.
aipm add @affaan-m/redis-patterns@1.0.0 --no-init
How to use
Install the skill above, then run this in your AI tool:
/redis-patterns <your description>
About
Quick reference for Redis best practices across common backend use cases.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub/sub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub/sub with Redis, or wh...
Skill instructions
Redis Patterns
Quick reference for Redis best practices across common backend use cases.
How It Works
Redis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI/EXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.
When to Activate
Adding caching to an application
Implementing rate limiting or throttling
Building distributed locks or coordination
Setting up session or token storage
Using Pub/Sub or Redis Streams for messaging
Configuring Redis in production (pooling, eviction, clustering)
Data Structure Cheat Sheet
Use Case
Structure
Example Key
Simple cache
String
product:123
User session
Hash
session:abc
Leaderboard
Sorted Set
scores:weekly
Unique visitors
Set
visitors:2024-01-01
Activity feed
List
feed:user:456
Event stream
Stream
events:orders
Counters / rate limits
String (INCR)
ratelimit:user:123
Bloom filter / HLL
HyperLogLog
hll:pageviews
Core Patterns
Cache-Aside (Lazy Loading)
python
import redis
import json
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
defget_product(product_id: int):
cache_key = f"product:{product_id}"
cached = r.get(cache_key)
if cached:
return json.loads(cached)
product = db.query("SELECT * FROM products WHERE id = %s", product_id)
r.setex(cache_key, 3600, json.dumps(product)) # TTL: 1 hourreturn product
Write-Through Cache
python
defupdate_product(product_id: int, data: dict):
# Write to DB first
db.execute("UPDATE products SET ... WHERE id = %s", product_id)
# Immediately update cache
cache_key = f"product:{product_id}"
r.setex(cache_key, 3600, json.dumps(data))
Cache Invalidation
python
# Tag-based invalidation — group related keys under a setdefcache_product(product_id: int, category_id: int, data: dict):
key = f"product:{product_id}"
tag = f"tag:category:{category_id}"
pipe = r.pipeline(transaction=True)
pipe.setex(key, 3600, json.dumps(data))
pipe.sadd(tag, key)
pipe.expire(tag, 3600)
pipe.execute()
definvalidate_category(category_id: int):
tag = f"tag:category:{category_id}"
keys = r.smembers(tag)
if keys:
r.delete(*keys)
r.delete(tag)
Session Storage
python
import time
import uuid
defcreate_session(user_id: int, ttl: int = 86400) -> str:
session_id = str(uuid.uuid4())
key = f"session:{session_id}"
pipe = r.pipeline(transaction=True)
pipe.hset(key, mapping={
"user_id": user_id,
"created_at": int(time.time()),
})
pipe.expire(key, ttl)
pipe.execute()
return session_id
defget_session(session_id: str) -> dict | None:
data = r.hgetall(f"session:{session_id}")
return data if data elseNonedefdelete_session(session_id: str):
r.delete(f"session:{session_id}")
import uuid
defacquire_lock(resource: str, ttl_ms: int = 5000) -> str | None:
lock_key = f"lock:{resource}"
token = str(uuid.uuid4())
acquired = r.set(lock_key, token, px=ttl_ms, nx=True)
return token if acquired elseNonedefrelease_lock(resource: str, token: str) -> bool:
release_script = """
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
end
"""
result = r.eval(release_script, 1, f"lock:{resource}", token)
returnbool(result)
# Usage
token = acquire_lock("order:payment:123")
if token:
try:
process_payment()
finally:
release_lock("order:payment:123", token)
For multi-node setups use the redlock-py library which implements the full Redlock algorithm.
Pub/Sub & Streams
Pub/Sub (Fire-and-Forget)
python
# Publisherdefpublish_event(channel: str, payload: dict):
r.publish(channel, json.dumps(payload))
# Subscriber (blocking — run in separate thread/process)defsubscribe_events(channel: str):
pubsub = r.pubsub()
pubsub.subscribe(channel)
for message in pubsub.listen():
if message['type'] == 'message':
handle(json.loads(message['data']))
Redis Streams (Durable Queue)
python
# Producerdefemit(stream: str, event: dict):
r.xadd(stream, event, maxlen=10000) # Cap stream length# Consumer group — guarantees at-least-once deliverytry:
r.xgroup_create('events:orders', 'processor', id='0', mkstream=True)
except Exception:
pass# Group already existsdefconsume(stream: str, group: str, consumer: str):
whileTrue:
messages = r.xreadgroup(group, consumer, {stream: '>'}, count=10, block=2000)
for _, entries in (messages or []):
for msg_id, data in entries:
process(data)
r.xack(stream, group, msg_id)
Prefer Streams over Pub/Sub when you need delivery guarantees, consumer groups, or replay.
import threading
_locks: dict[str, threading.Lock] = {}
_locks_mutex = threading.Lock()
defget_with_lock(key: str, fetch_fn, ttl: int = 300):
cached = r.get(key)
if cached:
return json.loads(cached)
with _locks_mutex:
if key notin _locks:
_locks[key] = threading.Lock()
lock = _locks[key]
with lock:
cached = r.get(key) # Re-check after acquiring lockif cached:
return json.loads(cached)
value = fetch_fn()
r.setex(key, ttl, json.dumps(value))
return value
Note: for multi-process deployments, replace the in-process lock with acquire_lock/release_lock from the Distributed Locks section above.
Examples
Add caching to a Django/Flask API endpoint:
Use cache-aside with setex and a 5-minute TTL on the response. Key on the request parameters.
Rate-limit an API by user:
Use fixed-window with pipeline(transaction=True) for low-traffic endpoints; use sliding-window Lua for accurate per-user throttling.
Coordinate a background job across workers:
Use acquire_lock with a TTL that exceeds the expected job duration. Always release in a finally block.
Fan-out notifications to multiple subscribers:
Use Pub/Sub for fire-and-forget. Switch to Streams if you need guaranteed delivery or replay for late consumers.
Quick Reference
Pattern
When to Use
Cache-aside
Read-heavy, tolerate slight staleness
Write-through
Strong consistency required
Distributed lock
Prevent concurrent access to a resource
Sliding window rate limit
Accurate per-user throttling
Redis Streams
Durable event queue with consumer groups
Pub/Sub
Broadcast with no delivery guarantees needed
Sorted Set leaderboard
Ranked scoring, pagination
HyperLogLog
Approximate unique count at low memory
Related
Skill: postgres-patterns — relational data patterns
Skill: backend-patterns — API and service layer patterns
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/affaan-m/redis-patterns/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@affaan-m/redis-patterns@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub/sub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub/sub with Redis, or wh...
Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You the...
Run aipm add @affaan-m/redis-patterns@1.0.0 in a project that has AIPM initialized.
Supported tools
@affaan-m/redis-patterns@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.