
Concurrency Issues: Race Conditions and How to Avoid Them
Concurrency bugs are some of the hardest to catch because they only show up 'sometimes'. This post walks through what concurrency actually means, the formal anomalies transaction-isolation theory gives names to (dirty write, phantom read, write skew) and how each is solved, a race between two independent cron jobs in a RAG file-import pipeline I traced back at VNG, and how I approached finding a fix for it - with some directional support from my manager along the way.
1. What Is Concurrency? Concurrency vs Parallelism
Concurrency is what happens when more than one flow of work is in progress during the same window of time - they don't have to execute at the exact same instant, they just have to overlap. A single cashier who takes order A, starts preparing it, switches to take order B while A is cooking, then comes back to finish A, is running two orders concurrently. Nothing happens at the exact same moment, but the two orders are interleaved.
Parallelism is doing more than one thing at the exact same instant - two cashiers, each fully dedicated to one order, working side by side. Parallelism is one way to get concurrency done faster, but it isn't required to have concurrency in the first place.
- Concurrency: multiple tasks make progress during overlapping time windows (can be interleaved on a single worker).
- Parallelism: multiple tasks execute at the literal same instant (requires multiple workers/cores).

The important takeaway: you don't need multiple threads, multiple cores, or even multiple servers to have concurrency. A single-threaded server handling two overlapping requests is already concurrent - and that's exactly where concurrency bugs come from: two flows touching the same data without either one finishing first.
2. Common Concurrency Problems and How They're Solved
Databases and distributed systems research gave these bugs formal names decades ago, in the study of transaction isolation (the ANSI SQL standard, and Berenson et al.'s well-known 1995 paper "A Critique of ANSI SQL Isolation Levels"). Knowing the formal name of a bug is useful for a very practical reason: it tells you exactly which battle-tested solution already exists for it, instead of re-inventing one.
2.1. Dirty Write and Lost Update - the write/write conflicts
A dirty write is one transaction overwriting another's uncommitted write. Every database blocks this by default with a write lock, so it rarely needs extra thought.
A lost update is subtler: two transactions read the same committed value, both validate their write against it, and one silently overwrites the other.
async function withdraw(accountId: string, amount: number) { const account = await getAccount(accountId); // read if (account.balance < amount) throw new Error("Insufficient funds"); await saveAccount(accountId, { balance: account.balance - amount, // write, using a value that may now be stale }); }
Two concurrent 80 withdrawals against a balance of 100 can both read 100, both pass the check, and both write 20 - 160 paid out, balance only reflects one withdrawal.

Solution: atomic operations. An operation is atomic when it's all-or-nothing and no other flow can see or interrupt it mid-way. Instead of a read then a write with a gap in between, fold the check and the write into one request the database executes as a single step:

// Racy: read, then write - a gap where another writer can interleave const account = await getAccount(id); if (account.balance >= amount) { await saveAccount(id, { balance: account.balance - amount }); } // Atomic: the condition is part of the same request as the write const result = await accounts.updateOne( { _id: id, balance: { $gte: amount } }, // condition { $inc: { balance: -amount } } // mutation ); if (result.modifiedCount === 0) { throw new Error("Insufficient funds or account not found"); }
The database holds a row-level lock (or MVCC equivalent) for that one statement, so nothing else can touch the row mid-operation - the same idea as a CPU's compare-and-swap (CAS), just at the database level.
For conflicts that aren't a simple numeric comparison, attach a version number instead - optimistic locking:
const result = await documents.updateOne( { _id: id, version: expectedVersion }, { $set: { content: newContent }, $inc: { version: 1 } } ); if (result.modifiedCount === 0) { throw new Error("Document was modified by someone else, please retry"); }
2.2. Phantom Read
A phantom read happens when a transaction runs a query based on some condition (a predicate - "all rows where status = pending"), and later either re-runs that same query, or acts on the assumption that the result set is still accurate - but in the meantime, another transaction has inserted or deleted a row that matches the predicate. The rows the first transaction is reasoning about aren't the ones locked or checked; entirely new rows can silently "appear."

Nothing here is a lost update - A and B never touched the same row - the problem is that A's decision was based on a set of rows that changed underneath it, because ordinary row locks don't protect rows that don't exist yet.
Why an atomic conditional update doesn't save you here. The updateOne trick from §2.1 works because the condition and the write both target the same, already-existing row - the database can take a lock on that row before evaluating the condition. A phantom read has no row to lock: the "condition" is a predicate over rows that don't exist yet, or that live in a different table entirely, and the eventual write (an INSERT) creates a brand-new row rather than mutating one the database could have locked in advance.
Take a "one signup per email domain per day" rule enforced by a check-then-insert:
// Racy: the condition scans a set of rows; the insert targets a row that doesn't exist yet. // There's nothing to attach a row lock to before the count is taken. const count = await signups.count({ domain, day: today }); if (count > 0) throw new Error("Domain already used today"); await signups.insertOne({ domain, day: today, email });
Wrapping the insertOne in updateOne-style atomicity doesn't help - the mutation isn't "change this row if it still matches X," it's "create a row that didn't exist," so there's no existing row for the database to hold a lock on while it checks the predicate. Two requests for the same domain can both run the count before either insertOne lands, both see 0, and both insert.
Solution: either run the check-and-insert inside a Serializable transaction (the database detects the conflicting predicate and aborts one transaction), use an explicit range/predicate lock if your database supports it, or - often simplest - push the invariant into the schema itself, e.g. a unique constraint or a CHECK constraint that makes the bad state physically impossible to write, regardless of how the application code interleaves. In the signup example, a unique constraint on (domain, day) turns the second insertOne into a constraint violation instead of a silent duplicate - no predicate lock required.
2.3. Write Skew
Write skew is the anomaly that made database researchers realize phantoms and lost updates weren't the whole story. Two transactions each read an overlapping set of rows, each individually confirms some invariant still holds, and then each writes to a different row - so neither one technically stepped on the other's write - but the combination of both writes breaks the invariant.
The textbook example: two on-call engineers, with the rule "at least one engineer must always be on call." Both are currently on call.

This is the sneaky one, because it can't be fixed by locking the row you're about to write - you have to lock (or otherwise protect) the rows the decision was based on, even though you're not writing to them.
Solution: true Serializable isolation is the only isolation level that fully closes this gap (modern implementations, like PostgreSQL's Serializable Snapshot Isolation, detect these conflicts without needing explicit locks); short of that, explicitly locking every row the invariant depends on (SELECT ... FOR UPDATE on both engineers' rows before either check) forces the two transactions to serialize.
2.4. Isolation Levels at a Glance
| Isolation level | Dirty read | Non-repeatable read | Phantom read | Write skew |
|---|---|---|---|---|
| Read Uncommitted | possible | possible | possible | possible |
| Read Committed | prevented | possible | possible | possible |
| Repeatable Read / Snapshot Isolation | prevented | prevented | prevented in practice* | possible |
| Serializable | prevented | prevented | prevented | prevented |
*The ANSI SQL standard's original definition of Repeatable Read still technically allows phantoms; most real databases (Postgres, for example) implement snapshot isolation instead, which blocks them in practice - but even snapshot isolation still allows write skew, which is precisely why write skew earned its own category rather than being folded into "phantom read."
2.5. Deadlock, Livelock, and Starvation
A few more classics that show up outside of database transactions too, in any system where flows compete for shared resources:

- Deadlock: two flows each hold a resource the other needs, and both wait forever. Fix: always acquire locks in the same agreed-upon order everywhere, and set an acquisition timeout so a stuck flow fails loudly instead of hanging.
- Livelock: flows keep reacting to each other's state changes, but nothing makes real progress (e.g. two retries colliding on the same interval, forever). Fix: randomized backoff/jitter so retries fall out of lockstep.
- Starvation: one flow is repeatedly passed over because others keep being scheduled first. Fix: fairness policies such as priority aging, so a long-waiting task's priority increases until it finally gets its turn.
3. A RAG File-Import Bug I Ran Into at VNG
A while back at VNG, I picked up a vague bug report on a file-import pipeline feeding a RAG (Retrieval-Augmented Generation) system - files get uploaded, chunked, and embedded into a vector index for an LLM to retrieve at query time. Occasionally a file ended up in a state that shouldn't have been reachable: freshly re-imported and fully searchable, yet also flagged as removed, with no clean way to recover it. No repro steps, no error logs - a concurrency bug, not a plain logic bug.
An uploaded file could later be updated (re-chunked and re-embedded) or deleted (chunks removed, record marked inactive) - each handled by its own independent cron job polling its own request queue, neither aware the other queue or cron existed.
Splitting them into two collections wasn't an oversight - it was a deliberate isolation call, so a slow or buggy query on one couldn't corrupt the other, and each pipeline could evolve its schema independently. For a while that trade-off looked free.
What it didn't leave room for was a single, authoritative answer to "what's the current pending state of this file?" With two collections, that answer only ever existed as something computed by querying both - no single row was the source of truth.
To prevent conflicts, request creation already had a guard:
- Creating an update request first checks: is there already a pending delete request for this file? If so, reject.
- Creating a delete request first checks: is there already a pending update request for this file? If so, reject.

On paper that rules out "one delete + one update pending at once." Tracing the request-creation logs (not just the crons) for one bad file turned up this sequence, triggered by the same file being touched from two places within moments of each other:
- t1 - delete-request flow checks for a pending update → finds none → prepares to insert a delete request. The insert stalls briefly (network/queue latency).
- t2 - update-request flow checks for a pending delete → still finds none, since t1's insert hasn't landed → inserts an update request immediately.
- t3 - t1's insert finally lands too.
Result: both a delete and an update request are now pending for the same file - exactly what the guard was built to prevent, produced by a gap inside the guard itself.

The two independent crons then make it worse instead of catching it: each only reads its own queue, so neither checks whether the other queue also holds a live request for the same file. Whichever runs next just does what its queue says. Here the update cron ran first - fresh content re-embedded - and the delete cron ran shortly after, flagging the file removed and wiping out the refresh.
In the vocabulary of Section 2.2, this is a phantom read: each guard's "does the other type exist?" check is a predicate query followed by an INSERT of a brand-new row, so there's no existing row to lock ahead of time - two concurrent checks can both come back clean before either insert lands. Same shape as the "one signup per email domain per day" example, just with two guards each checking the other's absence.
4. How I Approached It - With Some Directional Support From My Manager
The hardest part wasn't the fix - it was going from "vague, unreproducible bug" to "I know exactly which two writes are racing, and why."
- Started from the data, not the code. Looked at what a "bad" file record actually looked like in storage, then worked backwards to every write path touching each field - instead of guessing top-down.
- Read the request-creation logs, not just the crons. Lining up when each pending request was actually inserted (not when its cron later picked it up) made the collision obvious: two inserts seconds apart, each preceded by a guard check that had genuinely come back clean at the time.
- Drew the timeline out. Sketching t1/t2/t3 turned a hunch into a confirmed hypothesis, and made it easy to explain without anyone reading the guard's code first.
- Named the anomaly. Recognizing it as a phantom read specifically ruled out lost-update fixes (a version check on the file wouldn't catch two brand-new rows from two different guards) and pointed at the real gap: check and insert needed to become one atomic step.
Once I could explain the bug clearly, I brought it to my manager before jumping into a fix. There were a few ways to close the gap - a Serializable transaction around each guard's check-and-insert, a distributed lock per file, or collapsing the two collections into one atomic conditional write - with very different risk and effort. My manager didn't hand me the fix, but set clear priorities: favor the smallest change that actually removes the race over a bigger rewrite, stay consistent with how the rest of the pipeline already guarded against similar conflicts, and document the fix's tradeoffs rather than leaving them implicit.
That "free" isolation turned out to have a real cost: every request-creation call already had to reach into the other collection just to run its guard check - so the two were coupled anyway, in the one place (a cross-collection existence check) hardest to make atomic. Two schemas to keep in sync, two near-identical guards to maintain, and a query that never bought the independence it was supposed to.
The trade-off underneath all of this is isolation vs. a single source of truth. Splitting state to isolate two flows is legitimate - but any invariant spanning both (here, "at most one pending request per file") has no single place left to enforce atomically, since enforcing it means reaching across the very boundary built to keep things apart. Either keep the isolation and accept the invariant stays check-then-act racy, or give the invariant its own authoritative home and accept more coupling. You can't fully have both.
So the fix was collapsing the two collections into one, creating the single source of truth that was missing from the start. Instead of separate update_requests/delete_requests collections each queried with a racy "count, then insert," I added one field on the file record - pendingRequestType - and replaced both guards with a single atomic conditional update: set it from null to update or delete, only if it's still null at write time. One place now holds the answer to "what's pending for this file," and it's the same row the write locks.

Merging did introduce its own concurrency question - a much easier one. Now two requests race to write the same row instead of racing across two collections that could never share a lock. That's the lost-update shape from Section 2.1, not the un-lockable phantom-read shape from Section 2.2 - and 2.1 already has the answer: the second request fails the conditional update outright and is rejected as a conflict, instead of racing past a stale check. I kept each cron's re-validation as a second line of defense, and added a regression test firing both request-creation calls concurrently to confirm exactly one ever wins.
5. Conclusion
Concurrency bugs rarely come from exotic thread-safety puzzles - most of the ones you'll actually run into come down to a handful of well-studied, well-named anomalies: dirty write, lost update, phantom read, write skew, deadlock, livelock, and starvation. Once you can name the shape of a bug, the fix is usually already a known pattern - an atomic conditional write, optimistic versioning, a Serializable transaction, consistent lock ordering, or backoff with jitter - rather than something you have to invent from scratch.
And when a bug report says "it only happens sometimes," that's the first clue to start looking for two flows - however far apart in time or code they are - that were never introduced to each other.


