Skip to main content
// half-baked code · #04
hard10-15 min21% solve rate892 attempts

The Race Condition in Your Cache

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

Node.jsAsync/AwaitPerformance

The Code

This code passed code review and works in development. But it has a bug that will cause problems in production.

cache.js
javascript
1class UserCache {
2 constructor() {
3 this.cache = new Map();
4 }
5
6 async getUser(userId) {
7 // Check cache first
8 if (this.cache.has(userId)) {
9 return this.cache.get(userId);
10 }
11
12 // Fetch from database
13 const user = await database.fetchUser(userId);
14
15 // Store in cache
16 this.cache.set(userId, user);
17
18 return user;
19 }
20
21 async updateUser(userId, data) {
22 // Update database
23 await database.updateUser(userId, data);
24
25 // Invalidate cache
26 this.cache.delete(userId);
27 }
28}
29
30// This cache implementation has a race condition
31// that can serve stale data indefinitely.
32// Can you find it?
// need a hint?

Progressive Hints

0 of 3 revealed
Hint 1 locked
Hint 2 locked
Hint 3 locked
// ready for the answer?

Ready for the Solution?

Enter your email to get the full solution with explanation, the fix, and why this bug is so common.

No spam. Unsubscribe any time.