Find the bug: lost update when adding loyalty points

Backend Live Coding November 13, 2026 python

Lost update: two concurrent calls read the same value and one of the changes is lost.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ======================================================================
# Q: Find the bug.
#
# Lost update: two concurrent calls read the same value and one of the changes
# is lost. In addition, save() writes all fields. Fix:
# Customer.objects.filter(pk=customer_id).update(points=F('points') + points).
# If a check is needed before the change: select_for_update() inside
# transaction.atomic().
# ======================================================================

def add_loyalty_points(customer_id, points):
    c = Customer.objects.get(pk=customer_id)
    c.points += points
    c.save()