pythonintermediate

Redis Cache-Aside Pattern in Python

Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.

python
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.