My account

Concurrency

When two pieces of code use the same data at the same time, the result can depend on luck. Learn to see race conditions and deadlocks, fix them with a lock or an atomic database update, and avoid shared data when you can.

Not reviewedWritten with AI helpReading time: 15 minOnline shop examplePython code

Author: bezzad

Contents

The problem: one phone, two buyers

Our online shop has a flash sale. Only one phone is left in stock. The web app serves requests with several threads. The code is:

stock = {"phone-x": 1}

def buy(product_id: str) -> bool:
    if stock[product_id] > 0:      # check
        charge_customer()          # takes some time
        stock[product_id] -= 1     # act
        return True
    return False
  1. In tests one user buys the phone. It works.
  2. On sale day two users click “Buy” at the same moment. Both pay. Both get a “Thank you” page. But we have only one phone, and now the stock is -1.

Each line is correct. The problem is timing: two threads ran the same lines at the same time, on the same data.

A few words first

  1. Concurrency means several tasks are in progress at the same time. They may take turns on one CPU core.
  2. Parallelism means several tasks really run at the same moment, on several CPU cores.
  3. A process is a running program. Each process has its own memory.
  4. A thread runs inside a process. All threads of one process share the same memory. This is useful, and it is also the source of the danger.
Process 1Thread 1Thread 2Thread 3Shared memorystock = 1Process 2Thread 1Its own memorystock = 1
Threads share memory, so they can step on each other's data. Processes do not share memory, so a lock in one process does not protect the others.
What about Python's GIL? In the normal CPython build, the GIL lets only one thread run Python code at a time. But the interpreter can switch threads between any two steps, so race conditions still happen. Also, newer Python versions have a build without the GIL. Never count on the GIL to protect your data.

Race condition: when luck decides

A race condition happens when the result depends on the order in which threads run.

The smallest example is a counter. “Add one” looks like one step, but it is really three:

  1. Read the current value.
  2. Add one to it.
  3. Write the result back.

If one thread is paused between step 1 and step 3, another thread can read the old value. Then one of the updates is lost.

Thread ACounterThread BtimeRead: 1010Read: 1010Write: 10 + 111Write: 10 + 111Expected 12, but the counter shows 11
Both threads read 10. Both write 11. Two visits, but the counter went up only once.

Try it yourself. The demo below runs two threads that each add one to a counter 1,000 times.

Live example: two threads, one counter

Each thread adds one to the counter 1,000 times. Each addition is three steps: read, add, write. The scheduler can switch threads between any two steps.

Expected2,000
Counter0
Lost updates0
    Choose a mode.

    Our phone bug is the same family. It is called check-then-act: we check a condition (“stock is above zero”), and later we act on it (“take one from stock”). Between the check and the act, another thread can change the data. The slow charge_customer call in the middle makes this gap wide.

    Why tests do not catch it. A race needs two threads in the wrong place at the wrong moment. With one user, or with light load, this almost never happens. The bug shows up on the busiest day, and it is very hard to reproduce.

    Fix 1: a lock

    A lock lets only one thread at a time run a piece of code. This piece of code is called the critical section.

    import threading
    
    stock = {"phone-x": 1}
    stock_lock = threading.Lock()
    
    def buy(product_id: str) -> bool:
        with stock_lock:
            if stock[product_id] <= 0:
                return False
            stock[product_id] -= 1     # reserve the item
        charge_customer()              # slow work stays outside the lock
        return True
    1. The check and the act are now inside the same lock. No other thread can change the stock between them.
    2. The critical section is short. Other threads wait while one thread holds the lock. So do not put slow work inside it: network calls, file access, payments.
    3. If the payment fails, we must give the item back to the stock. This is one more reason to keep the reservation and the payment as clear, separate steps.

    Use a lock for every read and write of the shared data. If one place forgets the lock, the protection is gone.

    Deadlock: everyone waits forever

    Locks fix races, but they bring a new danger. Imagine a transfer between two accounts, and each account has its own lock:

    def transfer(src, dst, amount):
        with src.lock:
            with dst.lock:
                src.balance -= amount
                dst.balance += amount
    1. Thread 1 moves money from account A to account B. It takes the lock of A.
    2. At the same moment, thread 2 moves money from B to A. It takes the lock of B.
    3. Thread 1 now waits for the lock of B. Thread 2 waits for the lock of A.
    4. Nobody lets go. Both threads wait forever. This is a deadlock.
    Thread 1Thread 2Lock ALock Bholdsholdswaitswaits
    Each thread holds one lock and waits for the other one. The circle never breaks.

    How to avoid it:

    1. Always take locks in the same order. For example, the account with the smaller id first. Then the circle cannot form.
    2. Use fewer locks. One lock for a small piece of data is often enough. Many small locks are faster on paper, but harder to get right.
    3. Use a timeout. The acquire method of a lock can take a timeout. If it fails, let go of everything, wait a little, and try again.
    4. Never call unknown code while holding a lock. That code may take another lock.
    def transfer(src, dst, amount):
        first, second = sorted([src, dst], key=lambda a: a.id)
        with first.lock, second.lock:
            src.balance -= amount
            dst.balance += amount

    Fix 2: when the app runs on many servers

    In real life, the shop runs as several processes, often on several servers. Each process has its own memory, its own stock dictionary, and its own lock. A lock in memory protects only one process.

    So the data must live in one shared place, like the database, and the change must be atomic there. The best way is to check and change in one statement:

    def buy(conn, product_id: int) -> bool:
        cur = conn.execute(
            "UPDATE products SET stock = stock - 1 WHERE id = %s AND stock > 0",
            (product_id,),
        )
        return cur.rowcount == 1   # 0 means sold out
    1. The database locks the row while it runs this one statement.
    2. The condition “stock above zero” and the change happen together. There is no gap between them.
    3. The second buyer changes zero rows, and gets “sold out”.

    Another common way is optimistic concurrency. Every row has a version number. You update only if the version is still the one you read. If it changed, someone else won, and you read again and retry. Many ORMs support this.

    Read, change in code, write back: the same bug again. If you SELECT the stock, subtract one in Python, and then UPDATE the new number, you have the same race, only now in the database. A transaction alone does not stop it at the default isolation level of most databases. Do the change inside one statement, lock the row (SELECT … FOR UPDATE), or use a version number.

    The best lock is no shared data

    The simplest way to avoid races is to not share data that can change.

    1. Immutable data. Data that never changes after it is created is safe to share. Create a new object instead of changing the old one.
    2. Each worker has its own data. For example, each thread counts in its own variable, and you add the results at the end.
    3. Send messages instead of sharing memory. One thread puts work into a queue. Worker threads take work from it. The queue.Queue class is already thread-safe.
    import queue
    import threading
    
    orders = queue.Queue()
    
    def worker():
        while True:
            order = orders.get()
            process(order)
            orders.task_done()
    
    for _ in range(4):
        threading.Thread(target=worker, daemon=True).start()
    Async code is not free from races. With asyncio, code runs on one thread. But at every await, another task can run. If you check something, then await, then act, another task may have changed the data in between.

    In code review and in interviews

    When you see concurrent code, ask these questions:

    1. What data is shared? A global variable, a class field, a cache, a database row.
    2. Who writes it? If more than one thread or server writes it, it needs protection.
    3. Is there a gap between a check and an act? “If it exists, then create it” and “if there is stock, then take it” are classic examples.
    4. How many processes or servers run this code? If more than one, an in-memory lock is not enough.
    5. If there are two locks, are they always taken in the same order?

    Common mistakes

    Mistake Result The right way
    Changing shared data without a lock Lost updates. Wrong numbers under load. A lock, an atomic operation, or no shared data.
    Check outside the lock, act inside it The race is still there. Put the check and the act in the same critical section.
    Slow work inside a lock All other threads wait. The app feels frozen. Keep the critical section short. Do I/O outside.
    Two locks taken in different orders Deadlock. The service stops, the CPU is near zero. One fixed order for all locks, or one lock.
    An in-memory lock for an app on many servers Each server has its own lock. The race is still there. An atomic database update, or optimistic concurrency.
    “Python has a GIL, so it is safe” Races still happen between steps. Protect shared data the same way as in any language.
    Testing only with one user The bug shows up first in production. Load tests, and careful review of shared data.

    Summary in six lines

    1. Threads share memory. If two threads change the same data at the same time, updates can be lost.
    2. “Add one” and “check, then act” are not one step. Another thread can run in the gap.
    3. A lock makes a critical section run one thread at a time. Keep it short, and use it everywhere the data is touched.
    4. Two locks taken in different orders can cause a deadlock. Always take locks in one fixed order.
    5. With many processes or servers, an in-memory lock does not help. Use one atomic database statement or a version number.
    6. The best protection is no shared changing data: immutable objects, local data, or a queue.

    Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.