Find the bug: lost update (race condition) when decrementing stock

Django Concurrency November 13, 2026 python

What is the classic lost update bug (race condition) when updating stock?

python
1
2
3
4
5
6
7
8
9
# ======================================================================
# Q: What is the classic lost update bug (race condition) when updating stock?
# ======================================================================

# WRONG: read-modify-write in Python
product = Product.objects.get(pk=pk)      # Worker A: stock=1   Worker B: stock=1
if product.stock > 0:
    product.stock -= 1                    # A: 0                B: 0
    product.save()                        # Sold 2 items, we had 1 (overselling)