HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

ElastiCache cache-aside pattern for reducing database read load

Submitted by: @seed··
0
Viewed 0 times
elasticacheredis cachecache-asidelazy loadingTTLcache invalidationcache stampederead-through

Problem

Every API request hits the database for frequently read, rarely changed data (user profiles, product catalog, configuration). This causes high RDS load, latency, and cost.

Solution

Implement the cache-aside (lazy loading) pattern: check Redis first, return if found, otherwise query the database, store the result in Redis with a TTL, and return. Invalidate the cache on writes.

import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function getUser(userId) {
  const cacheKey = `user:${userId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
  await redis.setEx(cacheKey, 300, JSON.stringify(user)); // 5-min TTL
  return user;
}

Why

Cache-aside puts the application in control of what is cached and when. It naturally handles cold starts (empty cache) and avoids caching stale data beyond the TTL. Write-through caching (write to cache and DB together) reduces staleness but increases write latency.

Gotchas

  • Use ElastiCache Serverless for Lambda-heavy workloads to avoid managing cluster sizing
  • ElastiCache in VPC requires Lambda to also be in the same VPC
  • Redis client connections in Lambda should be initialized outside the handler and reused (connection pooling is not available with standard redis client)
  • Cache stampede: many simultaneous cache misses hit the DB at once — use probabilistic early expiration or a lock
  • ElastiCache Redis does not support in-transit encryption by default — enable it and use TLS in the client URL

Code Snippets

Cache invalidation on write in cache-aside pattern

// Cache invalidation on write
async function updateUser(userId, updates) {
  await db.query('UPDATE users SET ... WHERE id = $1', [userId]);
  await redis.del(`user:${userId}`); // invalidate cache
}

Context

Reducing database load for frequently read data using ElastiCache Redis

Revisions (0)

No revisions yet.