The Analogy: A Hotel Front Desk on a Sold-Out Night
Picture a hotel front desk on a sold-out night, worked by a single clerk. Most of what checking in a guest involves is not the clerk's own effort -- it is waiting: waiting for housekeeping to radio back that a room is cleaned, waiting for the card terminal to authorize a deposit. A plodding clerk takes one guest and stands frozen at the counter until housekeeping answers, then finishes that guest before waving the next one forward, so the line crawls while everyone waits on a radio. A sharp clerk starts a guest, and the instant the room-check is radioed off, turns to the next arrival rather than standing idle; the waits overlap, and the desk clears a dozen guests in the time a single room-check would have taken alone.
Behind the desk sits a rack of reservation cards. If the clerk finds a booking by starting at the front and flipping through every card, the last guest of a full night waits through hundreds of cards. So the cards are filed in order of confirmation number: the clerk opens to the middle, decides which half holds the number, halves that, and lands on any card in a rack of hundreds after a handful of glances. That speed is not free -- every new booking has to be slotted into its correct place in the order, never just dropped on top of the pile.
On the wall hangs a board of room statuses. Assigning a room is a read followed by a write: the clerk reads that room 412 is free, then writes the guest's name against it. With one clerk at the desk this is flawless -- read, write, read, write, and the board always tells the truth.
On the worst night of the year a second clerk is pulled in to work the same desk. A weary couple and a late business traveler reach the two clerks at the same moment, and room 412 is the last one free. Both clerks glance at the board, both see 412 available, and both promise it. Each writes their guest against 412; the second name simply covers the first, and the board now looks perfectly consistent with exactly one booking on that room. No alarm sounds. Two parties arrive at midnight holding keys to the same door, and a hotel that read as fully in order has quietly sold a room it does not have.
Syntax or Core Structure
Django runs async views when you serve it through an ASGI server. An async def view can hold many I/O-bound requests at once on a single worker, because while one request waits on a slow database call or an external API, the event loop runs another -- exactly the sharp clerk turning to the next guest instead of freezing at the counter. The win is real only for I/O-bound work: a view that does heavy CPU work never yields, and it stalls every other request sharing that worker just as surely as a clerk who refuses to look up.
The stand-in below strips async to its essence: three requests that each spend some time waiting on I/O, run first one-at-a-time and then overlapped. It reduces overlapping waits to the single longest wait, which is optimistic -- real scheduling has overhead, and the ORM is still synchronous -- but it shows the shape of the win.
def run_sync(waits):
clock = 0
for w in waits:
clock = clock + w
return clock
def run_async(waits):
longest = 0
for w in waits:
if w > longest:
longest = w
return longest
WAITS = [3, 2, 4]
print("requests: " + str(len(WAITS)))
print("sync ticks: " + str(run_sync(WAITS)))
print("async ticks: " + str(run_async(WAITS)))
print("ticks saved: " + str(run_sync(WAITS) - run_async(WAITS)))
Output:
requests: 3
sync ticks: 9
async ticks: 4
ticks saved: 5
Run one at a time, the three waits stack up to 9 ticks of a guest standing at the counter. Overlapped, the worker starts all three and the desk clears in the longest single wait, 4 ticks; the 5 saved ticks are the entire reason to reach for async. The catch is that the saving only appears when the work is genuinely waiting on something outside the process.
That is also where the sharpest Django gotcha lives: the ORM is synchronous, so calling Product.objects.get(...) directly inside an async def view raises SynchronousOnlyOperation. You either wrap the call in sync_to_async, which hands it to a thread so it does not block the loop, or you use the async ORM methods -- aget, acount, and async for over a queryset -- which are built to await cleanly.
Technical Depth: Indexes Turn Scans into Seeks
A query that filters on a column with no index forces the database to read every row and compare it -- a full table scan that costs on the order of n comparisons for n rows. An index keeps a sorted structure (a B-tree) over that column, so the database binary-searches to the matching rows in about log2(n) comparisons and stops early. The stand-in below counts the comparisons each strategy makes against the same sorted list of ids, for one value that is present and one that is absent.
def scan(rows, target):
comparisons = 0
for r in rows:
comparisons = comparisons + 1
if r == target:
return comparisons, True
return comparisons, False
def index_lookup(rows, target):
lo = 0
hi = len(rows) - 1
comparisons = 0
while lo <= hi:
mid = (lo + hi) // 2
comparisons = comparisons + 1
if rows[mid] == target:
return comparisons, True
if rows[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return comparisons, False
IDS = [10, 20, 30, 40, 50, 60, 70, 80]
print("rows: " + str(len(IDS)))
for target in [70, 55]:
sc, sfound = scan(IDS, target)
ic, ifound = index_lookup(IDS, target)
print("scan find " + str(target) + ": " + str(sc) + " comparisons, found=" + str(sfound))
print("index find " + str(target) + ": " + str(ic) + " comparisons, found=" + str(ifound))
Output:
rows: 8
scan find 70: 7 comparisons, found=True
index find 70: 3 comparisons, found=True
scan find 55: 8 comparisons, found=False
index find 55: 3 comparisons, found=False
The scan touches every row until it stumbles onto the target, so finding 70 costs seven comparisons and proving 55 is absent costs the full eight. The index halves the search space on each step: it settles 70 and rejects 55 in three comparisons each. With eight rows the gap is modest, but the scan grows in a straight line while the index grows by log2(n) - at a million rows the scan averages five hundred thousand comparisons and the B-tree needs about twenty. That is the whole reason db_index=True or a Meta.indexes entry exists.
An index is not free, and that is the trap people miss. The database keeps the index sorted, so every INSERT, UPDATE, and DELETE on an indexed column must also edit the index - writes pay a tax so reads can fly. Index the columns you filter and order by often; leave the write-heavy, rarely-queried columns alone.
When an index earns its keep
| Column usage | Index it? | Why |
|---|---|---|
| Filtered in WHERE on most queries | Yes | Turns a full scan into a seek |
| Only two or three distinct values | Rarely | The planner scans anyway; the index barely narrows |
| Written constantly, never filtered | No | Pure write tax for no read benefit |
| Named in ORDER BY on large tables | Yes | The sorted index supplies rows already ordered |
A composite index reads left to right
A composite index on (customer_id, created) is sorted first by customer_id, then by created within each customer. The database can only use it from the left: a filter that starts at customer_id rides the index, but a filter on created alone has to scan, because the rows for any single date are scattered across every customer block.
| Query filter | Uses the index? | Why |
|---|---|---|
| customer_id = 42 | Yes | Matches the leftmost column |
| customer_id = 42 AND created after a date | Yes | Leftmost column, then the next one in order |
| created after a date, no customer_id | No | Skips the leftmost column, so the sort cannot help |
This leftmost-prefix rule is why column order in Meta.indexes is a design decision, not an afterthought: put the column you always filter on first, and the one you sometimes add second.
Real World Example: Overselling Stock When Two Checkouts Race
A concert has one hundred tickets. Two checkout requests arrive at almost the same instant, each for a group of seats. The naive handler reads the current stock, subtracts in Python, and writes the new number back. When requests overlap, both read the same starting number before either writes, so the second write is computed from a stale value and silently erases the first request's decrement. The counter looks consistent afterwards - it just sold more tickets than existed.
The stand-in below models that race deterministically. run_naive collapses each overlapping group to a single surviving write - the lost-update outcome - while run_atomic mirrors what F("stock") - 1 does: it pushes the subtraction into the database so every order counts. The gap between the two final numbers is the oversell.
START = 100
GROUPS = [3, 2, 1]
def run_naive(groups):
stock = START
for g in groups:
stock = stock - 1
return stock
def run_atomic(orders):
stock = START
for _ in range(orders):
stock = stock - 1
return stock
orders = 0
for g in GROUPS:
orders = orders + g
lost = 0
for g in GROUPS:
lost = lost + (g - 1)
naive = run_naive(GROUPS)
atomic_stock = run_atomic(orders)
print("start stock: " + str(START))
print("orders: " + str(orders))
print("naive final stock: " + str(naive))
print("atomic final stock: " + str(atomic_stock))
print("naive lost updates: " + str(lost))
print("oversold by: " + str(naive - atomic_stock))
Output:
start stock: 100
orders: 6
naive final stock: 97
atomic final stock: 94
naive lost updates: 3
oversold by: 3
Six seats were ordered, so the honest final stock is ninety-four. The naive path lands on ninety-seven because each of the three overlapping groups read the same stock value and only the last write in each group survived - three decrements vanished. The counter never went negative and never threw an error, which is exactly why lost updates are so dangerous: nothing in the logs looks wrong, but the venue has promised seats it does not have. Pushing the arithmetic into the database with Product.objects.filter(pk=pk).update(stock=F("stock") - 1) closes the gap, because the UPDATE reads and writes in one statement the database serializes; select_for_update() inside a transaction is the alternative when you must read, decide, and write across several rows.
This code is a teaching model, and its shortcuts are worth naming. It collapses each concurrency group to exactly one surviving write, but real races are probabilistic - the number lost depends on precise timing, not a tidy g - 1. There are no real threads, locks, or transactions here; run_atomic simulates the correct total rather than enforcing it, so it cannot actually refuse an oversell. Even the real F() expression only makes the decrement atomic - it does not stop stock from going negative on its own, so production code still needs a database CHECK (stock >= 0) constraint or a conditional update() that matches only rows with stock left, and select_for_update() trades the race for lock contention and the risk of deadlock under load.
Common Mistakes
- Calling the synchronous ORM inside an
async defview. Writinguser = User.objects.get(pk=1)in an async view raisesSynchronousOnlyOperationat runtime. Django refuses to run blocking database code on the event loop. Wrap it insync_to_async(...)or use the async methodsaget,acount, andasync for.
- Believing async makes CPU-bound work faster. The event loop only overlaps waiting. A view that hashes passwords, resizes images, or crunches numbers holds the loop the entire time and blocks every other request on that worker. Async helps I/O-bound endpoints; CPU-bound work belongs in a task queue like Celery.
- Indexing every column "to be safe." Each index must be updated on every
INSERT,UPDATE, andDELETE, so an over-indexed table has slow writes and a bloated storage footprint. Index the columns you actually filter and order by, and measure before adding more.
- Assuming a composite index helps any column it names. An index on
(customer_id, created)does nothing for a query that filters oncreatedalone. The leftmost-prefix rule means you must use the columns from the left; skip the first column and the sorted structure is useless.
- Read-modify-write on a shared counter. Reading
stock, subtracting in Python, and saving is a lost-update bug the moment two requests overlap. UseF("stock") - 1so the database does the arithmetic in one atomic statement, or take a row lock withselect_for_update().
- Using
select_for_update()outside a transaction. The row lock it takes is only held for the duration of a transaction, so calling it in autocommit mode raises an error or silently grabs and releases the lock instantly. Wrap the read-decide-write inwith transaction.atomic():so the lock actually protects the critical section.
- Calling
len(queryset)when you only need a count.len()pulls every row into memory and builds the objects just to count them;queryset.count()sends aSELECT COUNT(*)and returns one number. On a large table the difference is megabytes of wasted memory and a much slower query.
- Filtering on a transformed column and expecting the index to fire. A plain index on
createdcannot serveWHERE DATE(created) = ...orWHERE UPPER(email) = ..., because the database indexed the raw value, not the function of it. Filter on the bare column, or add a functional index that matches the exact expression.
- Mixing a blocking library into an async view. Marking a view
async defdoes nothing if it calls a synchronous HTTP client, a blocking file read, ortime.sleep. Those calls freeze the whole event loop and every request it was juggling. Use async-native libraries, or hand the blocking call tosync_to_async.
Best Practices
- Reach for async views only on I/O-bound work. Endpoints that mostly wait - calling external APIs, streaming responses, talking to slow services - are where the event loop earns its keep. Leave CPU-bound and simple database-backed views synchronous; async adds real complexity and only pays off when there is waiting to overlap.
- Measure queries before you add indexes. Count the queries a view fires with
django-debug-toolbarorassertNumQueries, and read the plan withEXPLAIN(QuerySet.explain()). Add an index to fix a filter that shows up as a slow sequential scan, not on a hunch - an unused index is pure write overhead.
- Order composite index columns by how you filter. Put the column present in the most queries first, honoring the leftmost-prefix rule, and add the secondary column second. One well-ordered composite index often replaces two single-column ones.
- Do concurrent arithmetic in the database. For counters, balances, and stock levels, use
F()expressions so theUPDATEreads and writes atomically. It removes the read-modify-write window entirely and is faster than fetching the row into Python.
- Guard multi-row critical sections with a transaction and a row lock. When you must read a row, decide, then write - and
F()cannot express the logic - wrap the block inwith transaction.atomic():and takeselect_for_update()so no other request can read the row until you commit.
- Use the async ORM in async views. Call
await Model.objects.aget(...),await qs.acount(), and iterate withasync for, or wrap legacy synchronous calls insync_to_async. Never let a blocking query touch the event loop.
- Back critical invariants with a database constraint. Application checks race; a
CheckConstraintsuch asstock >= 0or aUniqueConstraintis enforced by the database no matter how many requests collide. Treat it as the last line of defence behindF()and locks.
- Profile with real data volumes. A sequential scan on ten rows is invisible; on ten million it is an outage. Test index and concurrency behavior against a dataset sized like production, because the bugs that matter here only appear at scale.
Practice Exercises
- Trace the overlap model with new waits. Change
WAITSto[5, 1, 1, 5]and predict, by hand, whatrun_syncandrun_asyncprint before running the code. Then explain in one sentence whyrun_asyncreturns the single longest wait rather than the sum, and name one real situation where the "collapse to the longest" assumption is too optimistic.
- Count the comparisons yourself. Using the
scanandindex_lookupfunctions, work out by hand how many comparisons each takes to find30and to prove45is absent in[10, 20, 30, 40, 50, 60, 70, 80]. Run the code to check, then describe how the index's comparison count grows as the list doubles in size.
- Order a composite index. A table of orders is filtered three ways: by
customer_idalone, bycustomer_idandstatustogether, and bystatusalone. Decide the column order for a single composite index that helps the first two queries, and explain, using the leftmost-prefix rule, why it cannot help the third.
- Close the oversell for real. Rewrite the checkout so it cannot sell stock it does not have. Sketch the Django code using
F("stock") - 1insidetransaction.atomic(), add a conditional.filter(stock__gte=quantity)so the update matches only rows with enough stock, and name the database constraint you would add as a final backstop.