pythonintermediate
Redis Cache-Aside Pattern in Python
Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.
pythonPress ⌘/Ctrl + Shift + C to copy
import json, redis, psycopg2
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
conn = psycopg2.connect('dbname=mydb user=postgres')
TTL = 300
def get_user(user_id: int) -> dict:
key = f'user:{user_id}'
cached = r.get(key)
if cached:
return json.loads(cached)
cur = conn.cursor()
cur.execute('SELECT id, name, email FROM users WHERE id = %s', (user_id,))
row = cur.fetchone()
if row is None:
return {}
user = {'id': row[0], 'name': row[1], 'email': row[2]}
r.setex(key, TTL, json.dumps(user))
return user
print(get_user(42))Use Cases
- query caching
- read-heavy workloads
- latency reduction
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javaintermediate
Spring Boot Caching with Redis
Add caching to Spring Boot services with @Cacheable, @CacheEvict, TTL configuration, and Redis.
Best for: Reducing database load with application-level caching
#spring-boot#caching
typescriptadvanced
Redis Cache Get/Set Helper
Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.
Best for: Database query caching
#redis#cache
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching
typescriptintermediate
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
Best for: API caching
#express#caching