Simple Django User Session Clearing using Celery

5 months ago
1 min read

Django provides session support out-of-the-box and stores sessions in the django_session database table. Django leaves it up to the project maintainers to purge sessions in their Django project. This means that if it's not done on a regular basis the table grows infinitely. However, they provide a simple command called clearsessions for it. Using it within a Celery task in a cron schedule resolves any long-term storage issues with large tables for sessions. The below solution requires both Celery for the task and Celery-beat for the cron schedule.


app.conf.beat_schedule = {
    # Clear expired sessions
    "clear_sessions": {
        "task": "config.celery_app.clear_sessions",
        "schedule": crontab(hour=0, minute=0, day_of_week=0),
    ... other tasks

def clear_sessions():
    """Clear expired sessions by using Django management command."""

Recently, the django_session table grew to a couple of gigabytes and I added this solution to clear the table. Now it's a default addition to any Django and Celery project.

Similar Posts

4 years ago
mailgun statuscake terraform cloudflare devops s3 rds django

Kickstarting Infrastructure for Django Applications with Terraform

8 min read

When creating Django applications or using cookiecutters as Django Cookiecutter you will have by default a number of dependencies that will be needed to be created as a S3 bucket, a Postgres Database and a Mailgun domain.

5 months ago
celery json structlog opentelemetry tracing django logging

Django Development and Production Logging

12 min read

Django comes with many great built-in features, logging is one of them. Pre-configured logging setups that vary between development (debug mode) and production environments. Easy integration to send you emails on errors, out-of-the-box support for various settings as log levels …

1 year ago
django monitoring celery error-tracking sentry

Django Error Tracking and Performance Monitoring with Sentry

6 min read

As good as a framework that Django is, the default method of sending an email when getting an error leave much to be desired. The database or cache acting flaky? Expect 1000s of emails depicting that error, which usually does …