0
0
Djangoframework~8 mins

pre_delete and post_delete signals in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: pre_delete and post_delete signals
MEDIUM IMPACT
These signals affect the server-side processing time before and after deleting database records, impacting backend response time and user experience.
Performing cleanup tasks when deleting a database record
Django
from django.db.models.signals import pre_delete
from django.dispatch import receiver
import threading

@receiver(pre_delete, sender=MyModel)
def async_cleanup(sender, instance, **kwargs):
    # Run cleanup asynchronously
    threading.Thread(target=lambda: instance.related_set.all().delete()).start()
Runs cleanup asynchronously, so delete request returns quickly without waiting for cleanup to finish.
📈 Performance GainReduces blocking time to near zero, improving backend response speed
Performing cleanup tasks when deleting a database record
Django
from django.db.models.signals import pre_delete
from django.dispatch import receiver
import time

@receiver(pre_delete, sender=MyModel)
def heavy_cleanup(sender, instance, **kwargs):
    # Blocking long-running task
    time.sleep(5)  # Simulate slow operation
    instance.related_set.all().delete()
Blocking or slow operations in pre_delete delay the delete request, increasing server response time and user wait time.
📉 Performance CostBlocks request processing for 5+ seconds, increasing backend latency
Performance Comparison
PatternServer BlockingDatabase LoadUser Wait TimeVerdict
Synchronous heavy work in pre_deleteHigh (blocks request)High (multiple deletes)High (slow response)[X] Bad
Asynchronous cleanup in pre_deleteLow (non-blocking)High (same deletes)Low (fast response)[OK] Good
Rendering Pipeline
Although these signals run on the server, their execution time affects how fast the server responds to delete requests, indirectly impacting user experience.
Server Processing
Database Operations
⚠️ BottleneckBlocking synchronous operations in signal handlers
Optimization Tips
1Avoid long blocking operations in pre_delete and post_delete signals.
2Use asynchronous tasks for heavy cleanup triggered by delete signals.
3Monitor server response times to detect slow signal handlers.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of running heavy synchronous code in a pre_delete signal?
AIt blocks the delete request, increasing server response time.
BIt causes the browser to re-render the page multiple times.
CIt increases the size of the JavaScript bundle.
DIt causes layout shifts on the client side.
DevTools: Network
How to check: Open DevTools Network tab, perform a delete request, and observe the request duration time.
What to look for: Long server response times indicate blocking operations in signals; faster responses indicate optimized signal handling.