0
0
Djangoframework~8 mins

Defining tasks in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: Defining tasks
MEDIUM IMPACT
This affects how background work impacts server responsiveness and page load times.
Running long operations during a web request
Django
from celery import shared_task

@shared_task
def long_task():
    # Long running code here
    pass

def view(request):
    long_task.delay()
    return HttpResponse('Task started')
Runs task asynchronously in background, freeing request to respond immediately.
📈 Performance GainNon-blocking request, reduces INP by avoiding main thread delay.
Running long operations during a web request
Django
def view(request):
    # Long task runs synchronously
    result = long_task()
    return HttpResponse(result)
Blocks the web server process, delaying response and increasing input latency.
📉 Performance CostBlocks rendering and response for duration of task, increasing INP significantly.
Performance Comparison
PatternServer BlockingResponse DelayUser Interaction ImpactVerdict
Synchronous task in viewBlocks server threadDelays response by task durationHigh input delay (INP)[X] Bad
Asynchronous task with CeleryNo blockingImmediate responseLow input delay (INP)[OK] Good
Rendering Pipeline
When tasks run synchronously, the server delays sending HTML, blocking browser rendering. Asynchronous tasks let the server respond quickly, so browser can start rendering sooner.
Server Response
Browser Rendering
Interaction Responsiveness
⚠️ BottleneckServer Response blocking due to synchronous task execution
Core Web Vital Affected
INP
This affects how background work impacts server responsiveness and page load times.
Optimization Tips
1Never run long tasks synchronously in request handlers.
2Use task queues like Celery to define asynchronous tasks.
3Asynchronous tasks improve server response and reduce input delay.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with running long tasks synchronously in a Django view?
AIt blocks the server response, increasing input delay.
BIt increases CSS rendering time in the browser.
CIt causes layout shifts on the page.
DIt reduces the bundle size.
DevTools: Network
How to check: Open DevTools Network tab, reload page, and observe time to first byte and total response time.
What to look for: Long server response times indicate blocking synchronous tasks; short times indicate good async handling.