Performance: When async helps and when it does not
This concept affects server response time and how quickly the browser receives data to start rendering.
Jump into concepts and practice - no test required
async def view(request): data = await slow_api_call_async() return HttpResponse(data)
def view(request): data = slow_api_call() return HttpResponse(data)
| Pattern | Server Threads Used | Blocking Behavior | Response Time Impact | Verdict |
|---|---|---|---|---|
| Sync view with slow I/O | 1 thread per request | Blocks thread until I/O done | High delay, poor concurrency | [X] Bad |
| Async view with slow I/O | Event loop with async tasks | Does not block event loop | Lower delay, better concurrency | [OK] Good |
| Async view with CPU-heavy task | Event loop blocked by CPU | Blocks event loop | Delays all async tasks | [X] Bad |
| Sync view with CPU-heavy task | 1 thread per request | Blocks thread but no async overhead | Expected CPU delay | [!] OK |
async def fetch_data(request):
data = await some_network_call()
return JsonResponse({'result': data})some_network_call() is a slow network request?async def cpu_task(request):
result = heavy_calculation()
return JsonResponse({'value': result})