Software Studio
Back to Articles

Redis Beyond Caching: Patterns for Real Applications

RedisNode.jsArchitecture
Cover illustration for Redis Beyond Caching: Patterns for Real Applications

Most developers know Redis as a cache. Set a key, get a key, maybe set a TTL. But Redis is a full-fledged data structure server, and its capabilities go far beyond caching.

Here are the patterns I reach for most, and the one rule that keeps all of them safe.

Rate limiting with a sliding window

Rate limiting is one of the most practical Redis use cases. The sliding window pattern uses a sorted set with timestamps as scores. For each request:

  1. Add the current timestamp.
  2. Remove entries older than the window.
  3. Check the set size. If it exceeds the limit, reject the request.
async function isAllowed(userId: string, limit: number, windowMs: number) {
  const key = `rate:${userId}`;
  const now = Date.now();

  const results = await redis
    .multi()
    .zadd(key, now, `${now}:${crypto.randomUUID()}`)
    .zremrangebyscore(key, 0, now - windowMs)
    .zcard(key)
    .pexpire(key, windowMs)
    .exec();

  const count = Number(results?.[2]?.[1] ?? 0);
  return count <= limit;
}

This provides accurate per-user rate limiting with minimal code. Unlike a fixed window, it can't be gamed by bunching requests around the moment the counter resets.

Session management for stateless servers

Session management with Redis solves the stateless server problem. In a horizontally scaled environment, with multiple Cloud Run instances or Kubernetes pods, you can't store sessions in memory. The next request may land on a different instance that has never heard of the user.

Redis provides a fast, shared session store. The session ID goes in a cookie, and the session data lives in Redis with a TTL matching your session duration. Expired sessions clean themselves up, and logging a user out everywhere is a single delete.

Job queues with BullMQ

Job queues with BullMQ, which is backed by Redis, handle background processing elegantly. When a user uploads an image, you don't process it synchronously. You push a job to a Redis-backed queue, return a 202 Accepted, and a worker picks up the job.

await imageQueue.add("resize", { imageId }, {
  attempts: 3,
  backoff: { type: "exponential", delay: 1000 },
});

BullMQ handles retries, backoff, priorities and dead letter queues. The user gets an immediate response, and a slow or failing job never ties up a web request.

Pub/Sub for real-time events

Pub/Sub enables real-time features without a dedicated message broker. When an article is published, publish an event to a Redis channel. Subscribers receive the event immediately:

  • WebSocket servers
  • Cache invalidation workers
  • Notification services

For simple event distribution within a single application, Redis Pub/Sub is lighter than Kafka or Google Pub/Sub.

One thing to know: delivery is fire-and-forget. A subscriber that is offline when a message is published never sees it. Use it for events that are fine to miss, and use a queue for work that must happen.

Distributed locking

Distributed locking prevents concurrent operations from conflicting. When two instances try to process the same webhook, a Redis lock ensures only one succeeds. The lock uses SET with the NX and PX options:

const acquired = await redis.set(
  `lock:webhook:${eventId}`,
  instanceId,
  "PX", 30000,
  "NX",
);

if (!acquired) return; // another instance is handling it

NX means "only set if the key doesn't exist," and PX gives the lock an expiry so a crashed instance can't hold it forever. The Redlock algorithm extends this to Redis clusters for higher availability.

Leaderboards and counters

Leaderboards and counters use Redis's sorted sets and atomic increment operations. ZINCRBY atomically increments a score. ZRANGEBYSCORE retrieves rankings.

These operations are O(log n) regardless of set size, making them suitable for leaderboards with millions of entries. Because the increment is atomic, two simultaneous updates can never overwrite each other.

The rule: Redis holds what you can rebuild

The operational consideration: Redis is in-memory.

  • Data that can't be reconstructed, such as user data and transaction records, belongs in PostgreSQL.
  • Data that can be reconstructed, such as caches, sessions and rate limits, is perfect for Redis.

The test is simple. If Redis dies and restarts empty, your application should continue working, just slower while caches rebuild. If losing Redis would lose something you can't get back, that data is in the wrong place.

Running Redis on GCP

For GCP deployments, Memorystore for Redis provides a managed instance with automatic failover. For development, a local Redis container works perfectly. The same client code works against both.

Picking the right pattern

  • Too many requests from one user? Sliding window rate limiter.
  • Sessions across multiple instances? Redis session store with a TTL.
  • Slow work in a request? BullMQ job queue.
  • Events several services care about? Pub/Sub.
  • Two instances doing the same thing? A lock with SET NX PX.
  • Rankings or counters? Sorted sets.

For the data that does belong in your primary database, see PostgreSQL Performance: Queries That Scale.