Why This Matters at Engineering Leadership Scale
AI coding assistants write clean, idiomatic TypeScript and Python with 100% mocked unit-test coverage - yet routinely hide concurrency bugs that explode when two real HTTP requests land within 5 milliseconds.
At Head of Engineering and Engineering Manager scale, you should never rescue routine sprint tickets. Instead, auditing 3 critical-path PRs per month (billing mutations, webhook handlers, migrations, and AI gateways) keeps your technical judgment sharp and teaches Tech Leads to catch concurrency bugs before they cause duplicate charges or corrupted audit records.
Core Mental Model & Framework
AI generates code linearly ("check X, then do Y") because training data reflects single-request tutorials. Under concurrency, two requests run check before either executes act.
| Classic AI Concurrency Red Flag | What Breaks Under Load | Exact Fix to Demand in PR Review |
|---|---|---|
Check-then-act balance update (SELECT -> if -> UPDATE) | Parallel deductions read the same balance and overdraw | Atomic SQL: UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1 RETURNING balance |
Check-then-insert idempotency (if (!(await exists(id))) insert()) | Simultaneous webhook retries both pass if and insert duplicates | UNIQUE (tenant_id, event_id) + INSERT ... ON CONFLICT DO NOTHING RETURNING event_id |
Shared mutable module cache/array across await | Concurrent requests interleave or corrupt per-request state | Keep state request-scoped; serialize shared mutations in DB/Redis |
Unbounded Promise.all(items.map(fn)) | 2,000 items fire 2,000 concurrent DB/HTTP calls, exhausting pools | Bounded concurrency pool (p-limit(8)) or batched SQL |
Mocked unit tests never expose these bugs because jest.fn() mocks run sequentially and simulate zero row-level locking.
Step-by-Step Implementation Tutorial
1. Scan Every await Read-Then-Write Pair
Whenever an AI PR awaits a read (getBalance, eventExists), runs an if check, and awaits a write (deduct, insert), ask: "What happens if two identical requests hit line 1 at the exact same millisecond?"
2. Audit the Buggy AI Diff vs. the Atomic Fixed Diff
// =========================================================================
// BUGGY AI-GENERATED DIFF (DO NOT APPROVE)
// Fails under concurrent webhook retries, overdraws credits, starves pools
// =========================================================================
export async function handleUsageWebhook(
db: Pool, tenantId: string, eventId: string, cost: number, userIds: string[]
) {
// BUG 1: Check-then-act race on duplicate Jira/Stripe webhook retries
const exists = await db.query(
`SELECT 1 FROM processed_events WHERE tenant_id = $1 AND event_id = $2`,
[tenantId, eventId]
);
if (exists.rows.length > 0) return { status: "duplicate" };
// BUG 2: Check-then-act lost update allows negative balance
const acct = await db.query(
`SELECT credits FROM tenant_wallets WHERE tenant_id = $1`, [tenantId]
);
if ((acct.rows[0]?.credits ?? 0) < cost) throw new Error("Insufficient credits");
await db.query(
`UPDATE tenant_wallets SET credits = credits - $1 WHERE tenant_id = $2`,
[cost, tenantId]
);
await db.query(
`INSERT INTO processed_events (tenant_id, event_id) VALUES ($1, $2)`,
[tenantId, eventId]
);
// BUG 3: Unbounded Promise.all hammers downstream notification API
await Promise.all(userIds.map((uid) => notifyUsageChange(tenantId, uid)));
return { status: "processed" };
}Now look at the atomic fix: one DB transaction with ON CONFLICT DO NOTHING and conditional WHERE credits >= $1, followed by post-commit bounded fan-out via p-limit.
// =========================================================================
// FIXED PRODUCTION DIFF
// Atomic DB serialization + unique idempotency + bounded post-commit fan-out
// =========================================================================
import pLimit from "p-limit";
const notifyLimit = pLimit(8);
export async function handleUsageWebhook(
db: Pool, tenantId: string, eventId: string, cost: number, userIds: string[]
) {
const client = await db.connect();
let remaining = 0;
try {
await client.query("BEGIN");
// FIX 1: Requires UNIQUE(tenant_id, event_id); DB serializes concurrent retries
const inserted = await client.query(
`INSERT INTO processed_events (tenant_id, event_id)
VALUES ($1, $2) ON CONFLICT (tenant_id, event_id) DO NOTHING RETURNING event_id`,
[tenantId, eventId]
);
if (inserted.rowCount === 0) {
await client.query("ROLLBACK");
return { status: "duplicate" };
}
// FIX 2: Conditional atomic UPDATE prevents concurrent overdrafts
const updated = await client.query(
`UPDATE tenant_wallets SET credits = credits - $1, updated_at = NOW()
WHERE tenant_id = $2 AND credits >= $1 RETURNING credits`,
[cost, tenantId]
);
if (updated.rowCount === 0) {
await client.query("ROLLBACK");
throw new InsufficientCreditsError(tenantId, cost);
}
remaining = updated.rows[0].credits;
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
// FIX 3: Dispatch side effects AFTER commit with bounded concurrency
await Promise.allSettled(
userIds.map((uid) => notifyLimit(() => notifyUsageChange(tenantId, uid)))
);
return { status: "processed", remaining };
}3. Demand Optimistic Locking & One Parallel Integration Test
For multi-field updates computed in memory, demand WHERE id = $1 AND tenant_id = $2 AND version = $3 (returning 409 Conflict when rowCount === 0). Require one real containerized PostgreSQL test running Promise.all([handleUsageWebhook(...), handleUsageWebhook(...)]) asserting exactly one "processed" and one "duplicate".
Worked Production Scenario: Before vs. After
Context: A B2B compliance SaaS team opened a 650-line AI-assisted Jira webhook PR with 18 green mocked unit tests. During a 15-minute leadership audit, we caught if (!(await eventExists(eventId))) before insert and an unbounded Promise.all emailing up to 350 compliance watchers inside the request.
After: Rather than rewriting the branch, we left clear failure-trace comments. In 30 minutes, the author added UNIQUE (tenant_id, event_id), switched to ON CONFLICT DO NOTHING, moved notifications post-commit behind pLimit(10), and added a parallel Testcontainers integration test.
| Metric | Before | After |
|---|---|---|
| Duplicate audit records on simultaneous retries | 100% reproducible | 0 (DB unique constraint) |
| DB connection hold time (350 watchers) | 4.8 seconds | 6 milliseconds (post-commit) |
| Outbound SMTP / pool exhaustion alerts / week | 14 | 0 (pLimit(10)) |
| Author rework time from review comments | N/A | 30 minutes |
Common Failure Modes & Anti-Patterns
- Holding a DB transaction open during external HTTP calls: Locks rows for seconds while waiting on third-party APIs. Fix: Commit DB changes first, then dispatch notifications (or use a transactional outbox).
- Adding an in-memory
Setlock across multiple pods: Load balancers route retry #1 to Pod A and retry #2 to Pod B, bypassing local memory locks. Fix: Push serialization into shared DB unique constraints or atomic conditionalUPDATEs. - Trusting mocked unit tests as concurrency proof: Mocks never simulate row locks or interleaved writes. Fix: Require one parallel
Promise.allintegration test against a real database container.
How to Handle Pushback in the Room
Peer Engineering Manager: "Once you manage 25+ engineers and Tech Leads, reviewing PRs for race conditions sounds like micromanagement."
Calm Response: "I never rescue routine tickets or block daily merges. Auditing three critical-path PRs a month - migrations, authz, and concurrent webhooks - keeps my judgment calibrated and gives me real codebase examples to coach Tech Leads."
Pushing Product Manager: "CI is green and the customer wants this live today - can we harden concurrency next sprint?"
Calm Response: "Mocked tests do not run two retries at once, so green CI gives zero protection against duplicate compliance records. Adding ON CONFLICT DO NOTHING takes thirty minutes now versus days of manual audit cleanup later."
Key Takeaways & This Week's Action Rep
- Flag every
awaitread-then-write pair: AnySELECT->if->UPDATE/INSERTis a live race condition. - Serialize mutations in PostgreSQL: Use
ON CONFLICT DO NOTHING, conditionalUPDATE, or optimisticversionlocks. - Bound every
Promise.allfan-out: Always pair dynamic arrays withp-limit. - Prove concurrency against a real DB: Add one parallel
Promise.allintegration test on critical endpoints.
This Week's Action Rep: Audit one webhook or billing PR merged in the last 30 days with your Tech Lead for read-then-write races and unbounded Promise.all loops, and add a 3-line concurrency check to your PR template.