Skip to content

typescript.race_condition

Correctness High

Detects potential race conditions in asynchronous code.

Race conditions:

  • Data corruption — Concurrent updates overwrite each other
  • Inconsistent state — Operations interleave unpredictably
  • Hard to reproduce — Bugs appear randomly
// ❌ Before (race condition)
let balance = 0;
async function withdraw(amount: number): Promise<void> {
if (balance >= amount) {
await delay(10); // Simulates async DB call
balance -= amount; // Another call might have changed balance!
}
}
// ✅ After (with mutex/lock)
import { Mutex } from 'async-mutex';
const balanceMutex = new Mutex();
let balance = 0;
async function withdraw(amount: number): Promise<void> {
await balanceMutex.runExclusive(async () => {
if (balance >= amount) {
await delay(10);
balance -= amount;
}
});
}
  • Shared state modified in async functions
  • Check-then-act patterns without locks
  • Concurrent array/object mutations