Concurrency bugs often begin with an assignment that looks too small to fail:
counter = counter + 1
The difficulty is not the addition. It is that another request may run between our read and write.
This article follows that problem as state moves from one process to Redis, PostgreSQL, and NoSQL databases. Counter and inventory examples connect the ideas.
Key terms
| Term | Simple meaning |
|---|---|
| Atomic operation | An operation that behaves as one complete step. Other work cannot observe it half-finished or interrupt it in the middle. |
| Transaction | A group of operations handled as one unit. In SQL, the group commits or rolls back together; other systems may provide different guarantees. |
| Isolation | How much one transaction is protected from other transactions running at the same time. For example, it determines whether a transaction can see another transaction’s unfinished changes. |
| Lock | A mechanism that makes competing work wait before accessing protected data. |
| Invariant | A business rule that must always remain true, such as “stock cannot be negative.” |
| Conflict | When concurrent operations overlap in a way that cannot safely succeed as planned. For example, two customers both try to buy the last item. The system may make one wait, reject one, or ask one to retry. |
1. One Counter, Two Workers
Two workers can read the same counter value and overwrite each other’s increment. Protect the complete read and write sequence.
Walk through a lost update
Assume an in-memory counter starts at 10. Conceptually, an increment has three steps:
value = read(counter)
new_value = value + 1
write(counter, new_value)
Two workers can interleave those steps like this:
| Time | Worker A | Worker B | Stored counter |
|---|---|---|---|
| 1 | Reads 10 |
10 | |
| 2 | Reads 10 |
10 | |
| 3 | Calculates 11 |
10 | |
| 4 | Calculates 11 |
10 | |
| 5 | Writes 11 |
11 | |
| 6 | Writes 11 |
11 |
After the last operation, the expected result was 12: we started at 10 and completed two increments. The stored value is only 11, so one increment disappeared.
Concurrency means multiple tasks make progress during overlapping periods. A race condition means the result depends on their timing. This particular race is a lost update: one write overwrites another update based on stale data.
The read–calculate–write sequence is a critical section: code that must behave as one indivisible unit with respect to competing workers.
This is conceptual pseudocode, not a claim about whether one expression is atomic in a particular Python implementation. Runtime details change. Correctness should rest on a documented synchronization guarantee.
2. Locks and Atomic Operations
Protect a sequence with a mutex
A mutex, short for mutual exclusion lock, is like a key to a room. One thread holds the key; other threads using that mutex wait:
from threading import Lock
counter = 10
counter_lock = Lock()
def increment() -> None:
global counter
with counter_lock:
current = counter
updated = current + 1
counter = updated
The context manager releases the lock even if the protected code raises an exception. Worker B waits until Worker A leaves the block, so it reads 11 and writes 12.
This protects the enclosed sequence from other threads that use the same lock. It does not coordinate code that ignores the lock, nor does it coordinate another process or server. Keep the critical section short: slow I/O while holding a popular lock makes every waiter slower.
Use a mutex when several in-memory steps must observe and change state together.
Protect one operation with an atomic primitive
Some languages expose an atomic integer. Java, for example, includes AtomicInteger in its standard library:
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger counter = new AtomicInteger(10);
int updated = counter.incrementAndGet();
Python’s standard library does not provide a general-purpose AtomicInteger with this API. For a Python counter shared by threads, use a lock:
from threading import Lock
counter = 10
counter_lock = Lock()
def increment() -> int:
global counter
with counter_lock:
counter += 1
return counter
| Operation | Java standard library | Python standard library |
|---|---|---|
| Increment one shared integer | AtomicInteger.incrementAndGet() |
Protect the integer with threading.Lock |
| Update only if the value is unchanged | AtomicInteger.compareAndSet() |
Protect the check and update with the same lock |
Other languages and third-party libraries use names such as fetch_add, compare_exchange, or compare_and_set. Check the atomic types documented for your language and runtime instead of assuming an ordinary integer operation is atomic.
Two concurrent atomic increments produce 12. Each caller also receives a well-defined old or new value according to the API contract.
An atomic increment protects one operation. A lock can protect a sequence of operations and related variables. Atomics can avoid lock overhead for simple state, but more elaborate lock-free algorithms are difficult to design and review.
Use an atomic primitive for a small operation directly supported by a trustworthy library. Use a lock when the invariant spans a sequence.
A check followed by an atomic increment is still unsafe
Now add a rule: increment only when the counter is below 100. This version is broken:
# Broken
if counter.load() < 100:
counter.fetch_add(1)
Each individual operation may be atomic while the combined decision is not.
| Time | Worker A | Worker B | Counter |
|---|---|---|---|
| 1 | Loads 99; check passes |
99 | |
| 2 | Loads 99; check passes |
99 | |
| 3 | Atomically increments | 100 | |
| 4 | Atomically increments | 101 |
One fix is to put the check and increment under the same mutex. Languages with atomic types may instead offer compare-and-set (CAS): “change the value only if it is still the value I read.” If another worker changed it first, CAS reports failure:
# Pseudocode
loop:
observed = counter.load()
if observed >= 100:
return false
if counter.compare_and_set(expected=observed, new=observed + 1):
return true
# Another worker changed it. Re-read and retry.
Java’s standard AtomicInteger implements the same idea:
boolean incrementBelow100(AtomicInteger counter) {
while (true) {
int observed = counter.get();
if (observed >= 100) {
return false;
}
if (counter.compareAndSet(observed, observed + 1)) {
return true;
}
// The value changed. Read it again and retry.
}
}
Python’s standard-library equivalent uses the simpler mutex version:
def increment_below_100() -> bool:
global counter
with counter_lock:
if counter >= 100:
return False
counter += 1
return True
CAS protects this one counter if every writer uses compatible atomic operations. A conflict causes a retry, so heavy contention can waste CPU or starve unlucky callers. Production code usually bounds retries or uses a lock when contention is high.
3. Processes and Servers Change the Boundary
An ordinary thread lock lives inside one process. Two application processes have different locks and usually different heaps. Two servers definitely do.
There are two distinct cases:
- Each server increments its own in-memory counter. There is no race over one memory location, but there is also no single global count.
- Multiple servers update the same Redis key or database row. The shared system must coordinate the writes.
The governing principle is simple:
Coordination must cover every writer that can affect the invariant.
4. Redis: Shared Atomic Operations
Replace GET and SET with INCR
Moving the counter to Redis makes it shared, but it does not automatically make client-side logic safe:
# Broken: another client can write between GET and SET.
value = int(redis_client.get("page:views") or 0)
redis_client.set("page:views", value + 1)
| Time | Client A | Client B | Redis value |
|---|---|---|---|
| 1 | GET → 10 |
10 | |
| 2 | GET → 10 |
10 | |
| 3 | SET 11 |
11 | |
| 4 | SET 11 |
11 |
Call Redis’s native INCR command instead:
new_value = redis_client.incr("page:views")
Redis documents INCR as atomic, so concurrent clients do not lose increments. It protects that key operation as long as every writer uses safe commands.
Conditions need one server-side decision
A fixed-window rate limiter commonly needs to increment a counter and give a new counter an expiry. Separate commands leave failure gaps: the increment may succeed and the process may crash before setting the expiry.
A short script can make the decision and update execute atomically:
-- KEYS[1] = rate-limit key
-- ARGV[1] = limit, ARGV[2] = window in seconds
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
if current >= tonumber(ARGV[1]) then
return {0, current}
end
local updated = redis.call('INCR', KEYS[1])
if updated == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
return {1, updated}
The Lua script fixes the gap between separate commands. Redis runs the entire script before it starts another client’s command. No other request can slip between GET, INCR, and EXPIRE, and a newly created counter cannot be left without its expiry because the application crashed between two network calls.
This also means a slow script makes other Redis clients wait. Keep the script small and avoid long loops or heavy work.
Choosing a Redis mechanism
Choose the smallest suitable mechanism:
- Use a native atomic command such as
INCR,SET ... NX, or a documented conditional command when it expresses the whole change. - Use a short Lua script when a small conditional sequence must run inside Redis without interruption. A Redis Function is reusable server-side code installed in Redis, while an ad hoc Lua script is supplied by the application. Use a Function when the same logic is deployed and reused.
- Use
WATCHwithMULTI/EXECwhen the application must read a value and calculate the result itself.WATCHasks Redis to notice changes to selected keys.MULTIstarts collecting the intended writes, andEXECapplies them only if none of the watched keys changed. If another client changed one,EXECapplies nothing and the application reads the latest value and tries again.
from redis import WatchError
for attempt in range(5):
with redis_client.pipeline() as pipe:
try:
pipe.watch("counter")
current = int(pipe.get("counter") or 0)
if current >= 100:
pipe.unwatch()
break
pipe.multi()
pipe.set("counter", current + 1)
pipe.execute()
break
except WatchError:
if attempt == 4:
raise
Pipelines, transactions, and cluster slots
A pipeline sends several commands together to save network trips. It has two possible jobs:
redis_client.pipeline()in redis-py batches the commands and runs them as a transaction by default, so another client cannot run a command in the middle.redis_client.pipeline(transaction=False)only batches the commands for speed. Another client may run commands between them.
Write the mode explicitly when correctness depends on the commands staying together.
A Redis transaction runs its queued commands without commands from other clients being inserted between them. It is still different from a SQL transaction. If a queued command has a runtime error (for example, it tries to increment a list), Redis can report that error while other valid commands in the same transaction still run. Redis does not undo those successful commands. Validate the commands and value types before executing the transaction.
Redis Cluster divides keys among servers using numbered buckets called hash slots. Redis normally calculates a key’s slot from its whole name. Curly braces tell Redis to calculate it from only the text inside the braces. For example, both rate:{user-42}:count and rate:{user-42}:meta use user-42, so Redis puts them in the same slot. One server can then run a transaction or script over both keys. The tradeoff is that a very busy user’s keys can overload that slot.
5. PostgreSQL: Two Customers, One Item
Suppose inventory.stock is 1. The invariant is:
Stock must never become negative.
Walk through two buyers competing for one item
This application code is unsafe:
# Broken, even if each statement succeeds.
cursor.execute("SELECT stock FROM inventory WHERE sku = %s", (sku,))
stock = cursor.fetchone()[0]
if stock > 0:
cursor.execute(
"UPDATE inventory SET stock = %s WHERE sku = %s",
(stock - 1, sku),
)
| Time | Customer A | Customer B | Stored stock |
|---|---|---|---|
| 1 | Reads 1 | 1 | |
| 2 | Reads 1 | 1 | |
| 3 | Writes 0 | 0 | |
| 4 | Writes 0; also reports success | 0 |
The number is not negative, but two customers were promised the only item. This violated the rule that successful sales cannot exceed stock.
Conditional update: put the check in the write
Start with the smallest solution: put the stock check and decrement in one statement.
UPDATE inventory
SET stock = stock - 1
WHERE sku = $1 AND stock >= 1
RETURNING stock;
PostgreSQL checks stock >= 1 at the moment it updates the row. The first buyer changes stock from 1 to 0. The second buyer’s condition no longer matches, so that request changes no row.
Check RETURNING or the affected-row count:
- One returned row means the purchase reserved the item.
- No returned row means the item was already sold out.
The check and change cannot be separated by another request, which solves this race without an explicit application lock.
This is ideal for a local rule expressible in one statement. It protects the selected row when all writers preserve the condition. A row-level constraint supplies a final guard:
ALTER TABLE inventory
ADD CONSTRAINT stock_nonnegative CHECK (stock >= 0);
The constraint rejects any attempt to store a negative value, including updates from another service or an admin script. However, this constraint only checks the row being changed. It cannot enforce a rule that depends on several rows.
Pessimistic locking: lock before deciding
Use this approach when the decision needs several queries or application steps.
A transaction and a row lock solve different parts of the problem:
- The transaction groups the read and write. They either commit together or are rolled back together.
- The row lock prevents another transaction from changing the inventory row while the current transaction is deciding what to do.
BEGIN;
SELECT stock
FROM inventory
WHERE sku = $1
FOR UPDATE;
-- Application verifies stock >= 1.
UPDATE inventory SET stock = stock - 1 WHERE sku = $1;
COMMIT;
SELECT ... FOR UPDATE locks the selected inventory row. If Customer A locks it first, Customer B’s update waits. Customer A checks the stock, decrements it, and commits. PostgreSQL then releases the lock. Customer B continues, reads the new stock of 0, and reports “sold out.”
The lock is held until COMMIT or ROLLBACK. Keep the transaction short. For example, do not call a payment API while holding the row lock, because every request for that row must wait for the network call to finish.
Use pessimistic locking when conflicts are likely and waiting is cheaper than discarding work.
Optimistic concurrency: detect a stale version
Pessimistic locking assumes a conflict may happen and makes other writers wait. Optimistic concurrency allows them to work without waiting, but checks whether their data became stale before saving.
Assume the application read stock = 1 and version = 7. It includes version 7 in its update:
UPDATE inventory
SET stock = $1, version = version + 1
WHERE sku = $2 AND version = $3
RETURNING version;
If Customer A updates first, PostgreSQL changes the version to 8. Customer B’s update still expects version 7, so its WHERE condition matches no row. Customer B must reload the record and decide whether retrying still makes sense.
Use optimistic concurrency when conflicts are uncommon and retries are cheap. It does not prevent conflicts; it detects them. Every writer must advance and check the version, or use another compatible guarded update.
Recommended approach
The three approaches form a useful progression:
- Use a conditional update when the complete rule fits in one statement.
- Use pessimistic locking when the decision has several steps and conflicts are common. Other writers wait.
- Use optimistic concurrency when conflicts are uncommon. Writers do not wait, but a stale writer fails and may retry.
Uniqueness belongs in a constraint
Assume the existing short_links table already defines code as a primary key or unique column. Two requests try to add the same value, abc123.
| Time | Request A | Request B |
|---|---|---|
| 1 | Checks for abc123; not found |
|
| 2 | Checks for abc123; not found |
|
| 3 | Inserts abc123 |
|
| 4 | Tries to insert abc123 |
The earlier existence checks did not protect anything because both requests completed the check before either inserted. Insert directly and let PostgreSQL enforce uniqueness:
INSERT INTO short_links (code, destination)
VALUES ('abc123', $1)
ON CONFLICT (code) DO NOTHING
RETURNING code;
One insert succeeds. PostgreSQL detects that the other insert has the same unique value, waits if necessary to learn the first insert’s outcome, and then follows ON CONFLICT. The second request gets no returned row and can generate a different code or return the existing link.
The application does not need an explicit FOR UPDATE lock here. There is no existing abc123 row to lock before the first insert. PostgreSQL coordinates concurrent inserts through the unique index that supports the primary-key or UNIQUE constraint. The constraint is what guarantees that two committed rows cannot contain the same code; ON CONFLICT only tells PostgreSQL how the losing insert should behave.
6. NoSQL: Ask for Specific Guarantees
“NoSQL” describes many different systems. It does not imply the absence of atomic operations or transactions. Identify the exact operation, item/document boundary, deployment mode, and failure guarantee.
DynamoDB
A single DynamoDB UpdateItem can increment a counter atomically:
table.update_item(
Key={"pk": "page#home"},
UpdateExpression="ADD view_count :one",
ExpressionAttributeValues={":one": 1},
)
Combine the inventory decrement and condition in one request:
table.update_item(
Key={"pk": "sku#blue-mug"},
UpdateExpression="SET stock = stock - :one",
ConditionExpression="stock >= :one",
ExpressionAttributeValues={":one": 1},
)
If stock is zero, DynamoDB returns a conditional-check failure. A version attribute works similarly: require version = :expected and update both the value and version. Reload and retry only after reconsidering the operation against current state.
Suppose placing an order must change two DynamoDB items:
- Decrease stock on the
blue-muginventory item, but only if stock is available. - Create a new order item.
TransactWriteItems sends both changes as one request. If stock is available, DynamoDB decrements it and creates the order. If the stock condition fails, DynamoDB creates no order and leaves the stock unchanged. This is useful because the application cannot crash after completing only half of the operation.
client.transact_write_items(
TransactItems=[
{"Update": {
"TableName": "shop",
"Key": {"pk": {"S": "inventory#blue-mug"}},
"UpdateExpression": "SET stock = stock - :one",
"ConditionExpression": "stock >= :one",
"ExpressionAttributeValues": {":one": {"N": "1"}},
}},
{"Put": {
"TableName": "shop",
"Item": {
"pk": {"S": "order#42"},
"sku": {"S": "blue-mug"},
},
}},
]
)
- Guarantee: both changes succeed, or neither change happens.
- Cost: transactional reads and writes consume twice the capacity of ordinary reads and writes.
- Limits: at most 100 distinct items, all within one AWS account and Region.
MongoDB
MongoDB writes are atomic at the single-document level. Use $inc instead of a client-side read and replacement:
db.pages.updateOne(
{ _id: "home" },
{ $inc: { viewCount: 1 } }
)
Inventory can use the current stock in the update filter:
const result = db.inventory.updateOne(
{ _id: "blue-mug", stock: { $gte: 1 } },
{ $inc: { stock: -1 } }
)
// result.modifiedCount === 1 means the purchase reserved stock.
Because matching and modifying one document are atomic, only an update whose condition still matches succeeds. A filter containing the expected version provides optimistic concurrency.
MongoDB also supports transactions across multiple documents. Reuse the order example: decrement the inventory document and insert a separate order document. Both changes commit, or neither does.
modifiedCount is the number of documents actually changed by updateOne. A value of 1 means stock was available and decremented. A value of 0 means the filter did not match. In this example, the item was sold out.
await session.withTransaction(async () => {
const stock = await inventory.updateOne(
{ _id: "blue-mug", stock: { $gte: 1 } },
{ $inc: { stock: -1 } },
{ session }
)
if (stock.modifiedCount !== 1) {
// No document changed, so stock was unavailable.
throw new Error("Sold out")
}
await orders.insertOne(
{ _id: "order-42", sku: "blue-mug" },
{ session }
)
})
If the order insert fails, MongoDB rolls back the inventory decrement. If stock is already zero, the thrown error stops the transaction and no order is inserted.
- Guarantee: the inventory update and order insert both commit, or neither happens.
- Cost: more coordination and network work than one document update; MongoDB does not specify a fixed cost multiplier.
- Conflict effect: another order changing the same inventory may wait or need to retry.
- Limits: transactions require a replica set or sharded cluster; a standalone MongoDB server cannot run them.
- Hosting: Atlas manages the cluster. With self-hosting, your team operates its failover, upgrades, backups, and monitoring.
| Question | DynamoDB | MongoDB |
|---|---|---|
| Smallest atomic boundary | One item | One document |
| Multi-record operation | TransactWriteItems across items |
Transaction across documents |
| Relative transaction cost | Two underlying reads or writes per item | Extra coordination, round trips, and resource use; no fixed multiplier |
| Hosting model | AWS-managed service | MongoDB Atlas or self-hosted |
| Important scope limit | One AWS account and Region, up to 100 distinct items | Requires a replica set or sharded cluster |
“Good document boundaries” means storing data that changes together in one document when that model is natural. For example, an order and its line items can be embedded in one order document and updated atomically. This avoids a multi-document transaction. It does not help when information must remain separate, such as two account documents in a money transfer, so some operations still need transactions.
Part 1 Decision Guide
| Need | Usual starting point | Conflict behavior |
|---|---|---|
| One in-memory operation | Documented atomic primitive | CAS may require a retry |
| Local multi-step operation | Process-local mutex | Other participating threads wait |
| Shared Redis counter | INCR |
Redis performs the increment as one operation |
| Conditional database update | Condition in the update | No match means reject or reload |
| Several items or documents | Database transaction | All changes commit or none do |
The main lesson is to identify the data that must stay correct, then choose the smallest primitive that protects the complete change.
Part 2 continues with multi-entity money transfers, transaction isolation, idempotency, distributed locks, contention, and cross-service workflows.
References
- Redis strings and atomic counters (opens in a new tab)
- Redis transactions,
WATCH, and error behavior (opens in a new tab) - Redis Lua scripting and atomic execution (opens in a new tab)
- PostgreSQL explicit locking (opens in a new tab)
- PostgreSQL constraints (opens in a new tab)
- DynamoDB update expressions (opens in a new tab)
- DynamoDB condition expressions (opens in a new tab)
- DynamoDB transactions (opens in a new tab)
- MongoDB atomicity and transactions (opens in a new tab)
- MongoDB transactions (opens in a new tab)
Join the discussion
Spot a mistake or have another perspective? Share your feedback, insights, or suggestions.