← All posts

· 5 min read

Optimistic vs. Pessimistic Locking: How Real-World Systems Prevent Race Conditions

Two customers, one last item, and a race condition. How optimistic and pessimistic locking keep concurrent updates safe — with a production case study from Shopify's inventory-reservation redesign.

Node.jsPostgreSQLConcurrencyDatabase DesignBackend

Video

Watch the video overview of this article

The problem: What happens when two customers buy the last item?

Imagine an e-commerce store has only one camera left in stock. Two customers click Buy Now at almost the same time.

Both requests check the inventory and see one item available. Both proceed with their orders.

The result? Two orders for a single item.

This is a race condition: multiple operations compete to modify shared data, and their timing can produce an incorrect result.

The solution isn't simply to make your application faster. It's to ensure that conflicting operations cannot violate the rules of your business.

Two common approaches are optimistic locking and pessimistic locking.

Figure — How the two strategies resolve the same race
Two customers request the last item
Concurrency strategy

Optimistic locking

  1. Both read stock = 1, version = 7
  2. Customer A updates with version 7
  3. Success: stock = 0, version = 8
  4. Customer B tries version 7
  5. Version mismatch: update rejected

Pessimistic locking

  1. Customer A locks product row
  2. Customer B waits
  3. Customer A decrements stock and commits
  4. Customer B acquires lock
  5. Stock is 0: purchase rejected
No overselling

1. Optimistic Locking: Assume Conflicts Are Rare

Optimistic locking allows operations to proceed without explicitly locking a record first. Before accepting an update, the system checks whether the data has changed since it was read.

Think of it like editing a shared document. You read version 5, make your changes, and attempt to save. If someone else has already created version 6, your update is rejected rather than silently overwriting their work.

A common implementation uses a version number or conditional update.

How it works:

  1. Read the record and its version.
  2. Prepare the update.
  3. Save only if the version still matches.
  4. Reject or retry if another operation changed the record.

Best suited for: Profile updates, document editing, and other workloads where conflicts are relatively uncommon.

The trade-off: When many operations compete for the same record, repeated conflicts and retries can become expensive.

Amazon DynamoDB documents this version-based approach in its optimistic locking guidance.

2. Pessimistic Locking: Protect the Data Before Updating It

Pessimistic locking takes the opposite approach. It assumes that conflicting operations are possible and locks the relevant database records before performing a critical update.

Imagine two customers attempting to reserve the last available seat. The first transaction locks the seat and checks its availability. The second transaction must wait until the first transaction finishes.

Once the first customer reserves the seat, the second transaction sees the updated state and cannot reserve it again.

How it works:

  1. Begin a database transaction.
  2. Lock the relevant record.
  3. Check the current state and perform the update.
  4. Commit or roll back the transaction, releasing the lock.

Best suited for: Highly contested resources, inventory reservations, and workflows where competing transactions must be coordinated.

The trade-off: Other requests may have to wait. Long-running transactions and inconsistent lock ordering can also cause performance problems and deadlocks.

PostgreSQL documents row-level locking through SELECT ... FOR UPDATE in its explicit locking documentation.

3. A Real Production Case: How Shopify Redesigned Inventory Reservations

In a May 2026 engineering article, Shopify described replacing Redis with MySQL for inventory reservations.

The business problem was straightforward: during checkout, the system must ensure that two concurrent customers cannot reserve the same last unit.

Shopify's previous design kept temporary reservations in Redis while its inventory ledger lived in MySQL. Because changes across the two systems could not be handled in a single atomic database transaction, certain failure sequences could leave inventory reservations and the permanent inventory ledger inconsistent.

The article describes these as architectural failure modes, rather than claiming that a specific overselling incident occurred.

What did Shopify change?

Shopify moved its reservation mechanism into MySQL, allowing reservation and inventory operations to participate in database transactions.

It used MySQL's SKIP LOCKED feature and represented available inventory as individual units rather than relying on a single heavily contended quantity row.

When one transaction locks an available unit, another transaction can skip that locked row and select a different available unit instead of waiting for it.

The engineering team also improved lock ordering, transaction isolation, indexing, and database connection usage. Shopify reported that the redesigned system met its high-throughput targets during peak 2025 traffic.

What can we learn from this?

  • Correctness depends on how related state is stored and updated.
  • Locking and data modeling must work together to reduce contention.
  • Database transactions can simplify consistency when related operations live in the same database.
  • Real performance bottlenecks aren't always where engineers initially expect them.

Read the full case study: Shopify Engineering — We replaced Redis with MySQL for inventory reservations.

4. Which Strategy Should You Choose?

Consideration Optimistic locking Pessimistic locking
Basic approach Detect conflicting updates Protect records before updating
When conflicts occur Reject or retry Wait for the lock
Main advantage Avoids explicit lock waiting Coordinates competing transactions
Main drawback Retries under contention Blocking and deadlocks
Suitable workload Infrequent conflicts Frequently contested resources

There is no universal winner.

Optimistic locking is often appropriate when conflicts are uncommon and retries are inexpensive. Pessimistic locking can be appropriate when transactions frequently compete for the same resource and waiting is acceptable.

For simple inventory deductions, an atomic conditional database update may be enough. More complex workflows may require transactions, row locks, or additional safeguards.

Conclusion

Optimistic and pessimistic locking solve the same fundamental problem in different ways.

Optimistic locking detects a conflict before accepting an update. Pessimistic locking coordinates access before the critical update takes place.

Shopify's inventory-reservation redesign demonstrates how database transactions, locking, and data modeling can work together in a production system. AWS's documentation illustrates how optimistic concurrency control is used to detect conflicts without relying on traditional locking.

The important lesson for backend engineers is this:

Don't choose a locking strategy because it sounds faster. Choose it based on how frequently conflicts occur, what must remain consistent, and what happens when concurrent operations collide.

References