Skip to main content
Menu
Challenges/The Race Condition in Your Cache
// challenge_AS

The Race Condition in Your Cache

This caching logic seems bulletproof but has a subtle race condition.

hardNode.jsAsync/AwaitPerformance10-15 min
Attempts
892
Solved
21%
Avg time
7min
Published
2024-02-01
// the code

Here's what passed code review.

A standard pattern. Nothing in this code is obviously wrong. It works perfectly in dev. It works perfectly in staging. It even works in production — for a while.

cache.jsjavascript
class UserCache {
  constructor() {
    this.cache = new Map();
  }

  async getUser(userId) {
    // Check cache first
    if (this.cache.has(userId)) {
      return this.cache.get(userId);
    }

    // Fetch from database
    const user = await database.fetchUser(userId);

    // Store in cache
    this.cache.set(userId, user);

    return user;
  }

  async updateUser(userId, data) {
    // Update database
    await database.updateUser(userId, data);

    // Invalidate cache
    this.cache.delete(userId);
  }
}

// This cache implementation has a race condition
// that can serve stale data indefinitely.
// Can you find it?
// stuck? progressive hints

Reveal hints one at a time.

Each hint nudges you closer without giving it away. Use as many as you need.

hint_01Start here →+
What happens if getUser() and updateUser() are called simultaneously?
hint_02Need another nudge?+
Consider the timing of async operations.
hint_03Need another nudge?+
The cache might be repopulated with stale data.
// submit your guess
// solution lands in your inbox

Want more code challenges? Subscribe.

New challenge every two weeks. Production bugs that passed review. ~5 min reads.