<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec" -->

---
title: How to Prevent Race Conditions in Django | daily.dev
description: A hands-on tutorial builds a Django credit system to demonstrate and fix race conditions where concurrent requests can spend the same credit twice. It walks...
canonical: https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: How to Prevent Race Conditions in Django | daily.dev
og:description: A hands-on tutorial builds a Django credit system to demonstrate and fix race conditions where concurrent requests can spend the same credit twice. It walks...
og:url: https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec
og:image: https://api.daily.dev/og/posts/MrAbLcweC.png
og:image:alt: How to Prevent Race Conditions in Django
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Prevent Race Conditions in Django

**[freeCodeCamp](https://daily.dev/sources/freecodecamp)** · 31 min read · 0 upvotes · 0 comments

## Summary

A hands-on tutorial builds a Django credit system to demonstrate and fix race conditions where concurrent requests can spend the same credit twice. It walks through reproducing the bug with two Django shells, then fixing it using database transactions combined with PostgreSQL row locks (select_for_update). The guide covers setting up Django 5.2, DRF, and PostgreSQL 17 with Docker, writing automated concurrency tests with ThreadPoolExecutor and barriers, verifying lock behavior, and testing rollback on failure. It closes with common pitfalls: reading inside the lock, coordinating at the database level rather than the client, considering F() expressions for simple counters, and separating concurrency from idempotency concerns.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://www.freecodecamp.org/news/how-to-prevent-race-conditions-in-django>

## Questions this post answers

### How do I prevent a race condition in Django where two simultaneous requests spend the same credit?

Wrap the balance check and deduction in a database transaction and acquire a row lock with select_for_update() before reading the balance. Under PostgreSQL's Read Committed isolation, a plain read does not block concurrent transactions, so both requests can read the same balance unless the row is explicitly locked with SELECT FOR UPDATE inside transaction.atomic().

_Developers building shared balance or inventory logic can find concurrency patterns like this through daily.dev._

### Why doesn't SQLite work for testing Django row locking with select_for_update?

SQLite does not implement the row lock that select_for_update() relies on, so PostgreSQL is required for this kind of concurrency testing. PostgreSQL 17 with Django 5.2 and djangorestframework 3.16 was used to demonstrate SELECT FOR UPDATE blocking competing transactions until a lock is released, returning the sqlstate 55P03 (lock_not_available) if a lock_timeout is exceeded.

_Anyone choosing a database for transactional integrity testing can track these trade-offs on daily.dev._

### How can I test that my Django code correctly waits for a database row lock instead of just testing outcomes?

Use a TransactionTestCase, open a transaction that calls select_for_update() to hold the lock, then run the target function in a separate thread with a shortened SET LOCAL lock_timeout so it fails fast with PostgreSQL error code 55P03 (lock_not_available) if it waits on the lock, confirming the function acquires the lock before checking the balance rather than after.

_Developers writing concurrency regression tests can find similar testing patterns on daily.dev._

## Similar posts on daily.dev

- [SQL: Incorrect by Construction](https://daily.dev/posts/sql-incorrect-by-construction-qbpedkdak) · Lobsters · 3 upvotes · 0 comments
- [Django Async ORM: How to Handle Database Transactions in Async Views](https://daily.dev/posts/django-async-orm-how-to-handle-database-transactions-in-async-views-q51wkylvs) · C\# Corner · 0 upvotes · 0 comments
- [Building async Python applications with Tortoise ORM and Amazon Aurora DSQL](https://daily.dev/posts/building-async-python-applications-with-tortoise-orm-and-amazon-aurora-dsql-mfleo5e03) · AWS Database Blog · 0 upvotes · 0 comments

---

Tags: [#python](https://daily.dev/tags/python), [#postgresql](https://daily.dev/tags/postgresql), [#django](https://daily.dev/tags/django)

[View this post on daily.dev](https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"How to Prevent Race Conditions in Django","url":"https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec"},"datePublished":"2026-09-12T00:29:26.285Z","dateModified":"2026-09-12T00:29:50.298Z","description":"A hands-on tutorial builds a Django credit system to demonstrate and fix race conditions where concurrent requests can spend the same credit twice. It walks...","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/86f0e57a051cbd6e25473808dbf693e8?_a=AQAEuop","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/86f0e57a051cbd6e25473808dbf693e8?_a=AQAEuop","isAccessibleForFree":true,"articleSection":"freeCodeCamp","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"freeCodeCamp","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1628412854/logos/freecodecamp","url":"https://daily.dev/sources/freecodecamp"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":0},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"python,postgresql,django","timeRequired":"PT31M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"freeCodeCamp","item":"https://daily.dev/sources/freecodecamp"},{"@type":"ListItem","position":3,"name":"How to Prevent Race Conditions in Django"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/how-to-prevent-race-conditions-in-django-mrablcwec#faq","mainEntity":[{"@type":"Question","name":"How do I prevent a race condition in Django where two simultaneous requests spend the same credit?","acceptedAnswer":{"@type":"Answer","text":"Wrap the balance check and deduction in a database transaction and acquire a row lock with select_for_update() before reading the balance. Under PostgreSQL's Read Committed isolation, a plain read does not block concurrent transactions, so both requests can read the same balance unless the row is explicitly locked with SELECT FOR UPDATE inside transaction.atomic(). Developers building shared balance or inventory logic can find concurrency patterns like this through daily.dev."}},{"@type":"Question","name":"Why doesn't SQLite work for testing Django row locking with select_for_update?","acceptedAnswer":{"@type":"Answer","text":"SQLite does not implement the row lock that select_for_update() relies on, so PostgreSQL is required for this kind of concurrency testing. PostgreSQL 17 with Django 5.2 and djangorestframework 3.16 was used to demonstrate SELECT FOR UPDATE blocking competing transactions until a lock is released, returning the sqlstate 55P03 (lock_not_available) if a lock_timeout is exceeded. Anyone choosing a database for transactional integrity testing can track these trade-offs on daily.dev."}},{"@type":"Question","name":"How can I test that my Django code correctly waits for a database row lock instead of just testing outcomes?","acceptedAnswer":{"@type":"Answer","text":"Use a TransactionTestCase, open a transaction that calls select_for_update() to hold the lock, then run the target function in a separate thread with a shortened SET LOCAL lock_timeout so it fails fast with PostgreSQL error code 55P03 (lock_not_available) if it waits on the lock, confirming the function acquires the lock before checking the balance rather than after. Developers writing concurrency regression tests can find similar testing patterns on daily.dev."}}]}
```

