Fullstack CourseLearn by building
Back to week 4

Topic

Caching with Redis

Definition

Redis is an in-memory key-value data store commonly used as a cache, session store, or rate-limit counter that trades some durability for very low read and write latency.

In simpler words

Redis is a fast, temporary place to remember answers so Nest does not have to ask Postgres again right away.

No install is required this week. The goal is judgment: when caching solves a real, measured problem, and when it just adds a second source of truth to babysit.

After this you can

  • Name what belongs in a cache versus what belongs in Postgres
  • Explain cache invalidation and stale-read risk
  • Pick a TTL or eviction strategy for a concrete endpoint
  • Describe a Redis failure mode and its blast radius

When Redis earns its place

Definition

Caching is justified when a read is expensive or frequent relative to how often its underlying data changes, and slightly stale results are acceptable for a bounded window.

In simpler words

Cache values that are read a lot, change rarely, and can be a few seconds old without causing harm.

Good candidates: a ticket-status dashboard summary hit on every page load, a rarely-changing settings blob, a rate-limit counter, or a session lookup.

Bad candidates: a single ticket a user is actively editing, anything where staleness causes a wrong authorization decision, or data that has never been measured as slow.

Ask what happens if this value is ten seconds stale. If the answer is nothing bad, it is a caching candidate. If the answer touches money, auth, or inventory, be careful.

Cache-aside read

async getTicketCounts() {
  const cached = await this.redis.get('tickets:counts');
  if (cached) return JSON.parse(cached);

  const counts = await this.ticketsRepo.count();
  await this.redis.set('tickets:counts', JSON.stringify(counts), 'EX', 30);
  return counts;
}

Cache-aside checks Redis first, falls back to Postgres, then repopulates the cache with a short TTL.

Invalidation and failure modes

Definition

Cache invalidation is the deliberate act of removing or refreshing a cached value when its underlying data changes, and a cache failure mode describes how the system should behave if the cache is unavailable or wrong.

In simpler words

Decide up front how a cached value gets cleared, and what happens if Redis is down or returning stale data.

Two invalidation styles exist: TTL expiry, which is simple and always slightly stale, and explicit invalidation on write, which is fresher but adds more code paths to keep correct.

A cache should be allowed to fail. If Redis is unreachable, the endpoint should fall back to Postgres rather than return a server error. Treat a cache as an optimization, never a dependency the API cannot live without.

A common bug is caching per-user data under a shared key, which leaks one user data to another. Always include the tenant or user id in the cache key.

Keep in mind

  • Measure before caching. An unmeasured cache is a guess with new bugs.
  • Prefer short TTLs over manual invalidation until you have proven you need the freshness.
  • A cache outage should degrade performance, not correctness or availability.

Test

Check your understanding

At least 10 questions — mix of concept, syntax, practical, and logic. Score ≥ 80% (enforced by the API) to save progress.

Checking your session…

10 questions · concept 3 · syntax 2 · practical 3 · logic 2

Concept1. Which statement best defines caching with Redis?
Syntax2. Which code-level choice matches caching with Redis?
Practical3. A reviewer spots a bug related to caching with Redis. What is the right fix?
Logic4. Which reasoning correctly explains caching with Redis?
Concept5. Which boundary does correct use of caching with Redis preserve?
Practical6. What is the safest next step when applying caching with Redis?
Syntax7. Which implementation direction matches the rule for caching with Redis?
Logic8. Which consequence follows from applying caching with Redis correctly?
Concept9. Which claim about caching with Redis is true in this Nest + Postgres monorepo?
Practical10. Which team practice best demonstrates caching with Redis?