Skip to main content
← Back to articles

Redis Caching Strategies for APIs

Cache-aside, TTL policies, and stampede protection for high-read endpoints.

Nestlancer Editorial

Share

Caching turns read-heavy endpoints from database bottlenecks into millisecond responses—when TTLs, invalidation, and stampede protection are deliberate.

Cache-aside pattern

async getPost(slug: string): Promise<Post> {
  const cached = await this.redis.get(`post:${slug}`);
  if (cached) return JSON.parse(cached);
  const post = await this.prisma.read.post.findUnique({ where: { slug } });
  await this.redis.set(`post:${slug}`, JSON.stringify(post), 'EX', 300);
  return post;
}

TTL policy matrix

DataTTLInvalidation
Public blog post5–15 minOn publish/update event
User session permissions1–5 minOn role change
Config flags30–60 secPub/sub on update

Stampede protection

Use probabilistic early expiration or request coalescing (single-flight) when hot keys expire. A viral post should not trigger 10,000 simultaneous database queries.

When not to cache

  • Rapidly mutating personalized dashboards
  • Financial balances requiring strong consistency
  • Responses larger than 1MB—consider CDN instead

Monitor hit ratio per endpoint. Below 60% on intentionally cached routes means TTL or key design needs rework.

Redis caching is a product decision as much as an infrastructure choice—stale data tolerance must be explicit.

Comments

Loading comments…

Related posts