Cache-Aside: The Most Common and Reliable Pattern
Cache-Aside (also called lazy loading) is the most reliable caching pattern because the application explicitly manages what goes into the cache and when it expires. The logic: check the cache first — if found return immediately; if not found, query the database, store the result in the cache, and return it. This pattern handles cache invalidation gracefully and never returns stale data longer than the TTL allows.
- const cached = await redis.get(`course:${id}`);
- if (cached) return JSON.parse(cached);
- const course = await db.courses.findById(id);
- await redis.setex(`course:${id}`, 3600, JSON.stringify(course));
- Optimal TTL: infrequently changing data (courses) = 1 hour, frequently changing (stats) = 5 minutes
- Cache warming: pre-populate cache for frequently accessed data before peak traffic periods
- Versioned keys: course:v2:${id} — increment version when data schema changes to avoid stale deserialization
- Null caching: cache null results with a short TTL to prevent repeated DB hits for non-existent keys
Write-Through: Keeping Cache and Database Synchronized
Write-through caching updates both the cache and the database in the same operation, ensuring the cache is never stale. This is the right choice when data is read very frequently and consistency between cache and DB is important. The tradeoff is slightly slower writes — every write pays the cache update overhead even if the data is never read from cache.
- Write-Through: write DB + Cache together in the same operation
- Write-Behind (Write-Back): write Cache immediately + DB asynchronously — faster but risk of data loss
- Cache Invalidation: sometimes simpler — on update, delete the key from Cache
- Cache Stampede: when TTL expires for important data, hundreds of requests hit DB simultaneously — a serious problem
- Solution: Probabilistic Early Expiration or Cache lock
- Mutex pattern: use a Redis lock to prevent multiple cache-miss requests from hitting DB simultaneously
- Stale-while-revalidate: serve stale cache immediately while refreshing in background
- Two-phase invalidation: mark cache as stale before updating DB to prevent temporary inconsistency
Session Management in Redis
Storing sessions in Redis is a prerequisite for horizontal scaling. Filesystem or in-memory sessions break the moment you run more than one server process. Redis sessions are shared across all server instances, survive process restarts, and automatically expire after the configured TTL without any cleanup job. This is not optional for production SaaS — it is the baseline.
- connect-redis with express-session: sessions stored in Redis, not memory or files
- Safe horizontal scaling: any server in the cluster reads the user's session
- Automatic TTL: Redis automatically deletes expired sessions — no cleanup job needed
- Session prefix: sess: as prefix — to distinguish from other Redis keys
- Redis Sentinel or Cluster: for high availability in production
- Session size: keep sessions small — store only userId and role, not full user objects
- Rolling expiry: update TTL on every request so active sessions don't expire
- Session invalidation: store a user_version in the session — increment on logout to invalidate all sessions
Precise Rate Limiting with Redis
Redis-based rate limiting is more precise and more flexible than in-memory alternatives because it works across all server instances simultaneously. The sliding window algorithm is the best balance of accuracy and cost: it counts requests in a rolling time window rather than a fixed one, preventing the burst problem that fixed-window algorithms suffer from at window boundaries.
- Add timestamp to sorted set on each request: ZADD rate:userId score timestamp
- Remove old requests: ZREMRANGEBYSCORE key 0 (now-window)
- Count requests in window: ZCARD rate:userId
- If count > limit: return 429 Too Many Requests
- rate-limiter-flexible library: implements this pattern and more without manual code
- Multiple tiers: per-IP, per-user, per-API-key limits enforced simultaneously
- Retry-After header: return the wait time so clients can back off intelligently
- Burst allowance: allow 2x the rate limit for 10 seconds to accommodate legitimate short bursts
Job Queues with BullMQ
A job queue decouples slow operations from HTTP request handlers, enabling fast API responses while heavy work — email sending, PDF generation, AI processing, video transcoding — runs asynchronously in the background. BullMQ is the best job queue for Node.js: it is battle-tested, feature-rich, and manages all the Redis interaction transparently including retry logic, concurrency, and job prioritization.
- BullMQ: best job queue for Node.js — built on top of Redis
- Use cases: sending emails, processing videos, generating reports, AI tasks
- Built-in retry logic: failed jobs auto-retry with exponential backoff
- Concurrency control: set the number of parallel jobs per worker
- Dashboard: Bull Board gives you a visual interface for monitoring queues
- Job priorities: high-priority jobs (payment confirmation) processed before low-priority (analytics)
- Cron jobs: BullMQ supports repeating jobs with cron syntax — replace your manual cron setup
- Job deduplication: prevent duplicate jobs for the same user or resource using job IDs
Distributed Locks: Preventing Race Conditions
A distributed lock ensures that a critical operation runs on exactly one server at a time, even across a cluster. Without it, billing jobs run multiple times, idempotency is violated, and race conditions corrupt data in ways that are difficult to debug. The Redlock algorithm provides the right guarantees for most SaaS use cases with minimal complexity.
- Redlock algorithm: the recommended algorithm for distributed locks
- ioredis + redlock library: ready and reliable implementation
- SET key value NX PX 30000: the basic pattern — Set if Not Exists with timeout
- Lease renewal: for long operations, renew the lock before it expires
- Beware Deadlocks: always set a TTL on the lock — never a lock without a timeout
- Lock granularity: lock per resource (billing:user:123) not globally — maximize concurrency
- Idempotency keys: combine distributed locks with idempotency keys for payment operations
- Observability: log lock acquisition, release, and timeouts to diagnose contention issues
Redis Operations Cheatsheet for SaaS Engineers
These Redis data structures and commands are the most useful for SaaS applications. Each data structure is optimized for a specific access pattern — using the right one prevents memory waste and enables faster operations than would be possible with a generic key-value approach.
- Strings: simple caching, counters (INCR/DECR), rate limiting counters
- Sorted Sets (ZADD/ZRANGE): leaderboards, rate limiting sliding windows, priority queues
- Hashes (HSET/HGET): user sessions, feature flags per user, partial object caching
- Lists (LPUSH/RPOP): simple FIFO queues, activity feeds, recent history
- Sets (SADD/SMEMBERS): unique visitors, tag systems, set operations (union/intersection)
- Pub/Sub (PUBLISH/SUBSCRIBE): real-time notifications, cache invalidation across servers
- Streams (XADD/XREAD): persistent event log, reliable message delivery with consumer groups
