← Back to Chapters

Signals + Celery Combo

⚡ Signals + Celery Combo

? Quick Overview

Combining Django Signals with Celery allows you to trigger background tasks in response to application events, such as saving a model or user registration. This ensures that long-running tasks don’t block user requests, improving application performance.

? Key Concepts

  • Django Signals for event-driven actions
  • Celery for asynchronous background processing
  • Loose coupling between app components

? Syntax & Theory

? What are Django Signals?

Django signals enable different parts of your application to communicate by triggering actions when certain events occur.

? What is Celery?

Celery is a distributed task queue system that runs time-consuming tasks asynchronously in the background.

? Combining Signals with Celery

Signals trigger Celery tasks so heavy operations are handled asynchronously.

? Code Examples

? View Code Example
# Install required packages
pip install celery redis
? View Code Example
# celery configuration
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE','myproject.settings')
app=Celery('myproject')
app.config_from_object('django.conf:settings',namespace='CELERY')
app.autodiscover_tasks()
? View Code Example
# background task
from celery import shared_task
@shared_task
def send_notification(user_email):
    print(f"Notification sent to {user_email}")
? View Code Example
# signal definition
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import send_notification
from .models import User
@receiver(post_save,sender=User)
def send_welcome_email(sender,instance,created,**kwargs):
    if created:
        send_notification.delay(instance.email)

? Live Flow Explanation

  • User is created
  • Signal is fired
  • Celery task is queued
  • Worker executes task asynchronously

? Interactive Simulation

Click the button below to observe how the Django (Main Thread) finishes quickly while Celery (Worker) handles the heavy task in the background.

?️ Django (Main Thread)
 
? Celery (Background Worker)
 

? Use Cases

  • Email notifications
  • Data processing
  • Audit logging
  • Third-party API calls

✅ Tips & Best Practices

  • Keep Celery tasks lightweight
  • Avoid heavy logic inside signals
  • Enable retries and logging

? Try It Yourself

  • Create a post_save signal for a model
  • Trigger a Celery task asynchronously
  • Test failure handling and retries