Redis Cache Get/Set Helper
Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.
import { createClient, RedisClientType } from 'redis';
let client: RedisClientType;
export async function getRedis(): Promise<RedisClientType> {
if (!client) {
client = createClient({ url: process.env.REDIS_URL });
client.on('error', (err) => console.error('Redis error:', err));
await client.connect();
}
return client;
}
export async function cacheGet<T>(key: string): Promise<T | null> {
const redis = await getRedis();
const raw = await redis.get(key);
return raw ? (JSON.parse(raw) as T) : null;
}
export async function cacheSet<T>(
key: string,
value: T,
ttlSeconds = 3600
): Promise<void> {
const redis = await getRedis();
await redis.set(key, JSON.stringify(value), { EX: ttlSeconds });
}
export async function cacheAside<T>(
key: string,
fetcher: () => Promise<T>,
ttl = 3600
): Promise<T> {
const cached = await cacheGet<T>(key);
if (cached !== null) return cached;
const fresh = await fetcher();
await cacheSet(key, fresh, ttl);
return fresh;
}Sponsored
Upstash — Serverless Redis
Use Cases
- Database query caching
- Session storage
- API response caching
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
LRU Cache with TTL Support
Extend functools.lru_cache with time-based expiration for caching expensive function calls with staleness control.
Redis Docker Setup with Persistence
Docker Compose for Redis with persistence, password auth, memory limits, and a health check.
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
Bull Queue Job Producer & Consumer
Create a job queue with Bull for background processing with retries and concurrency control.