Introduction
Cache Architecture Overview
Implementing Redis in Your Application
// userService.
const redis = require('./redisClient');
const db = require('./database'); // Assume a generic async DB client
const USER_CACHE_TTL = 60 * 5; // 5 minutes in seconds
async function getUserById(userId) {
const cacheKey = user:${userId};
// Attempt to fetch from Redis first
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
// Cache miss - fetch from DB
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
if (user) {
// Store in Redis with TTL
await redis.setex(cacheKey, USER_CACHE_TTL, JSON.stringify(user));
}
return user;
}
module.exports = { getUserById }; </code></pre>
<p>Key points:</p> <ul> <li>Use <code>setex</code> to attach a TTL, preventing stale data.</li> <li>Serialize objects with <code>JSON.stringify</code> because Redis stores strings.</li> <li>Wrap Redis calls in <code>async/await</code> for readability.</li> </ul> <h3>Python Example</h3> <pre><code class="language-python"># redis_client.py import os import redisredis_client = redis.StrictRedis( host=os.getenv('REDIS_HOST', '127.0.0.1'), port=int(os.getenv('REDIS_PORT', 6379)), password=os.getenv('REDIS_PASSWORD'), decode_responses=True # Return strings instead of bytes )
user_service.py
import
from redis_client import redis_client
from database import async_query # Assume an async Postgres driver
USER_CACHE_TTL = 300 # seconds (5 minutes)
async def get_user_by_id(user_id: int): cache_key = f"user:{user_id}" cached = redis_client.get(cache_key) if cached: return json.loads(cached) # Cache miss - query the DB user = await async_query('SELECT * FROM users WHERE id = %s', (user_id,)) if user: redis_client.setex(cache_key, USER_CACHE_TTL, json.dumps(user)) return user </code></pre>
<p>Best practices shared between the two implementations:</p> <ul> <li>Keep cache keys predictable and namespace‑prefixed (e.g., <code>user:{id}</code>).</li> <li>Never store raw DB rows; always serialize to a known format.</li> <li>Handle Redis connection failures gracefully-fallback directly to the DB.</li> </ul>