# Preventing Redis Cache Stampedes: A Practical JavaScript Learning Exercise

As part of my Zephyra Technologies 45-Day Technical Challenge, Day 3 focused on troubleshooting a Redis cache stampede.

This exercise helped me understand how concurrent requests can overwhelm a database when cached data expires, and how mutex locks can help coordinate cache updates.

## The problem

The incident involved a popular product whose cached Redis entry expired.

Approximately 5,000 simultaneous requests then attempted to retrieve the same product.

Because the cache no longer contained the data, the requests queried PostgreSQL simultaneously, resulting in database overload and service degradation.

This behaviour is known as a **cache stampede** or **dogpile effect**.

## Understanding the root cause

The original code checked Redis but immediately queried PostgreSQL when the product was missing.

```javascript
let data = cache.get(productId);
if (data) return data;

data = await db.queryProduct(productId);
cache.set(productId, data, 60);
return data;
```

There was no mechanism to coordinate the workers performing the cache-miss operation.

## The solution: Mutex locking

A mutex lock helps control access to a shared operation.

In this scenario, the objective is to allow one worker to fetch the missing product while other workers wait.

The implementation follows this sequence:

1. Check Redis.
2. Acquire a lock if the product is missing.
3. Check Redis again.
4. Query PostgreSQL only if the product is still missing.
5. Store the result in Redis.
6. Release the lock.

## JavaScript implementation

```javascript
async function getProductWithLock(cache, db, productId, lockService) {
  let data = cache.get(productId);

  if (data) return data;

  await lockService.acquire(productId);

  try {
    data = cache.get(productId);

    if (data) return data;

    data = await db.queryProduct(productId);
    cache.set(productId, data, 60);

    return data;

  } finally {
    await lockService.release(productId);
  }
}
```

## Why double-check the cache?

The second cache check prevents unnecessary database queries.

For example, Worker A might acquire the lock and populate Redis while Worker B is waiting.

When Worker B eventually acquires the lock, it checks Redis again. Since the product is now available, Worker B can return the cached data instead of querying PostgreSQL.

## Why use per-key locking?

The lock uses `productId`, allowing different products to have separate locks.

This means a request for a laptop does not have to wait for a request fetching a mobile phone.

This approach is known as per-key locking.

## Handling failures

The `finally` block ensures that lock cleanup is attempted whether the database query succeeds or fails.

However, a production distributed lock requires more than simply acquiring and releasing a lock.

Important safeguards include:

- Lock leases or expiry times.
- Unique ownership tokens.
- Atomic ownership-checked release.
- Timeouts and retry handling.
- Fencing tokens or equivalent stale-worker protection.

These safeguards help prevent stale locks and unsafe behaviour when workers crash or resume unexpectedly.

## What I learned

This challenge helped me understand:

- Cache hits and cache misses.
- Cache stampedes and their effect on database performance.
- Mutex locks and per-key locking.
- Why a second cache check is necessary.
- JavaScript `try...finally` cleanup.
- Distributed lock failure scenarios.

The implementation is a learning exercise rather than a complete production-ready locking system.

My main takeaway is that high-throughput applications need to coordinate concurrent requests, not just cache frequently accessed data.

I'm documenting these challenges as I learn, with the goal of improving my practical problem-solving and understanding of backend and distributed systems.

**Day 3 of 45 — completed.**

Have you implemented cache-stampede protection in a real application? I'd be interested in learning about the approaches you've used.

#JavaScript #Redis #DistributedSystems #BackendDevelopment #LearningInPublic #Zephyra45Days
