Performance: Calling tasks asynchronously
This affects how quickly the main web request responds by offloading long-running tasks to background workers.
Jump into concepts and practice - no test required
from myapp.tasks import long_running_task def view(request): long_running_task.delay() return HttpResponse("Task started, response sent immediately")
def view(request): result = long_running_task() return HttpResponse(f"Result: {result}")
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous task in view | Minimal | N/A | Blocks paint until response | [X] Bad |
| Asynchronous task with Celery | Minimal | N/A | Immediate paint and interaction | [OK] Good |
send_email asynchronously?.delay() method.send_email.delay() queues the task to run in the background.@shared_task
def add(x, y):
return x + y
result = add.delay(4, 5)result.get() return after the task completes?result.get() waits for the task to finish and returns the result, which is 4 + 5 = 9.@shared_task
def multiply(x, y):
return x * y
result = multiply(3, 7)multiply(3, 7), which runs it immediately and blocks.multiply.delay(3, 7).send_welcome_email.delay(user.id) after user creation, queuing the task.