Background tasks, email and files in Django: the letter and the doorbell
TL;DR
Difficulty: Intermediate
Email, uploads and background tasks fail the same way: they reach outside the database, the only part of your system that can say "never mind".
- Every such effect is unsendable (email, SMS), orphanable (files) or repeatable (task messages), and each needs its own defence.
- The rule: write the letter in the database, let the queue only ring the doorbell. A row records what you intend, in the same transaction; the task message carries only its id.
- In Django 5.0: transaction.on_commit or Celery 5.4's delay_on_commit, a unique constraint, select_for_update, bounded retries, a sweeper, one beat process.
- Files: validate in layers (Django has no upload size limit of its own), process in a task, store privately with short signed URLs, sweep orphans yourself.
Django ships email and files, but no task queue, and most guides treat the three as separate topics. They fail in the gaps between them: the email for a booking that was rolled back, the photo nobody deleted, the report sent twice. Here they are as one problem with one rule, built in full on the Django version of the application of a chain of bike workshops in Limerick.
The question behind this chapter
"How do I send email, handle uploads and run slow work in the background in Django reliably?" Most answers to that question are three separate tutorials: one on Celery, one on send_mail, one on FileField. Each works in a demo. Put together in a real application, they fail in the gaps between them: the email that went out for a booking that was never saved, the photo still sitting in storage two years after its job card was deleted, the reorder report that arrived twice on Monday because two schedulers were running.
This chapter treats the three as one problem, because they are one problem. All three reach outside the database. I will show why that matters, give you one rule that covers all three, and then build it in full on the example application of this series: the "your bike is ready" email and SMS, the before and after photos of a repair, and the nightly parts reorder report.
The example is the same one as in the rest of the series, and it is invented. Freewheel Cycles is a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh, with 38 mechanics and about 1,150 repair bookings a week. Its developers, Aisling and Cian, built a two week spike of the core in both frameworks. This chapter is the Django version of the spike, written as of Django 5.0, Python 3.12 and Celery 5.4. The Rails version of the same features is in background jobs, email and files in Rails, and I compare the two at the end. The models come from the Django ORM chapter, which is worth reading first.
Three things a database cannot take back
A database transaction has a superpower nothing else in your application has: it can say "never mind". If anything goes wrong before the commit, every change in the transaction disappears as if it never happened. Django builds on this. Its documentation describes atomic blocks that commit on success and roll back on an exception1.
Everything outside the database lacks that superpower, and it fails in one of three ways. This is the model I use for the whole chapter:
- Unsendable. An email or an SMS cannot be recalled. Once the provider accepts it, the customer has it, whatever your database does next.
- Orphanable. A file written to storage does not vanish when the transaction that referred to it rolls back, or when the row that pointed to it is deleted. It stays, and nobody knows it is there.
- Repeatable. A task in a queue can be delivered more than once. Celery's own documentation says a message is only removed once a worker acknowledges it, and is redelivered if that worker dies first2.
Each of the three needs a different defence. Unsendable effects must wait until the database has committed. Orphanable effects need a sweep that compares storage with the database. Repeatable effects need code that can run twice and still do the right thing once. Almost every reliability bug in this area is one of these three, defended with the wrong tool.
Example: Saturday morning at Freewheel
Saturday morning is Freewheel's peak. About 30% of the week's online bookings arrive between Friday 6pm and Saturday noon. Imagine Aisling's first, naive version of the workshop board. A mechanic drags a job card to "ready", and the view does three things in a row: it saves the new status, it sends the "your bike is ready" email, and it records which parts were used on the repair.
Now the parts step fails, because the mechanic entered a quantity larger than the stock. The view raises an error, the transaction rolls back, and the card is back in "in repair". The email, however, has already left. A customer cycles across Limerick to collect a bike that is still on the stand. That is an unsendable effect sent too early.
The same morning, a mechanic uploads a before photo, the form fails validation on another field, and the mechanic tries again. Depending on how the view is written, the first file may already sit in storage with no row pointing to it. That is an orphan. And when the worker that sends the SMS restarts during a deploy, the message it was halfway through can be delivered again. Without a guard, the customer gets two texts. That is a repeat.
Three different failures, one cause: work that the database cannot take back was treated as if it could.
The letter and the doorbell
Here is the rule that turns the model into a design. Write the letter in the database. Let the queue only ring the doorbell.
The letter is a row that records the side effect you intend: "send the bike ready email for job card 4812". You write it inside the same transaction as the business change. If the transaction rolls back, the letter is gone too, and nothing is sent. If it commits, the letter is safely stored.
The doorbell is the task message. It carries nothing but the letter's id. Its only job is to say "there is a letter, go and deal with it". Two things follow, and they are the point of the whole design:
- A lost doorbell is harmless. If the message never reaches the queue (Redis was restarting at that second) or the worker gives up, the letter is still in the database. A small periodic task looks for letters that have waited too long and rings again.
- A doorbell rung twice is harmless. The worker locks the letter, checks whether it has already been sent, and only then acts. The second ring finds the letter marked as sent and does nothing.
This is not my invention. It is a small, Django sized version of the transactional outbox pattern, which Chris Richardson describes as storing the message in the database as part of the transaction that updates the business data, then sending it from a separate process3. What I add is the framing: the database is the only part of the system allowed to remember anything. The queue is a doorbell, and doorbells are allowed to be unreliable.
Example: the bike ready letter at Freewheel
At Freewheel, the letter is a Notification row: job card 4812, kind "bike ready", channel "email", status "pending". A second row says the same for "sms". Both are written in the transaction that moves the card to "ready". After the commit, two task messages carry the ids of those two rows. The worker that receives one locks the row, sees "pending", calls the email provider, and marks it "sent" with the provider's message id.
If the board update fails, there are no rows and no messages. If Redis is down for a minute, the rows wait as "pending" and the sweeper rings again ten minutes later. If a deploy restarts the worker and the message comes round twice, the second worker sees "sent" and stops. Niamh also gets a record of every message sent, with the provider's id, which is the first thing anyone needs when a customer is giving out that they never got a text.
What Django gives you, and what it leaves to you
Django ships two of the three pieces. It has a complete email library, with send_mail, the EmailMessage class, pluggable backends and protection against header injection4. It has a file API: FileField and ImageField on models, a storage abstraction, and the STORAGES setting (added in Django 4.2) that names the storage backends a project uses5.
It does not ship a background task system. There is no built in queue, no worker command and no common interface that libraries plug into. At the time of writing, a Django Enhancement Proposal (DEP) for a built in background task interface, written by Jake Howard, has been open for discussion since 9 February 20246. It is a proposal under discussion, not a feature: nothing in Django 5.0 changes because of it, and you pick a library today.
This is a genuine difference from Rails. Rails ships Active Job, an interface with its own default adapter (:async, which runs jobs in a thread pool inside the web process) that production backends plug into7. Django keeps the core smaller and leaves the field to libraries. The cost is more decisions up front. The benefit is that a library like Celery can offer more than a common interface could, for example chains and groups of tasks8, at the price of more configuration.
Example: what Aisling and Cian had to add
For the Rails spike, Aisling and Cian added one gem for the job backend and wrote job classes. For the Django spike, the list was longer. They added Celery with Redis as the broker (the message store between the web process and the workers), Anymail for the email provider, django storages for S3 compatible file storage, and Pillow, which Django requires for ImageField9. That is four libraries, each with its own documentation and release cycle. Someone has to own each one, and Niamh should see that on the plan.
Choosing a task queue
Five libraries do most of the background work in Django projects. They differ less in speed than in two things that matter far more for an application of Freewheel's size: what happens to a failing task by default, and how many processes you have to run.
| Library (version at this date) | Broker | What a failing task does by default | Schedules | Django integration |
|---|---|---|---|---|
| Celery 5.4.0 (17 April 2024)10 | RabbitMQ, Redis, Amazon SQS and others | Fails once. Retries only if you ask, then 3 at most2 | celery beat, a separate process11 | Built in since Celery 3.112 |
| Django Q2 1.6.2 (5 March 2024)13 | Redis, Django ORM, Amazon SQS, MongoDB, IronMQ | Presented again after 60 seconds, with unlimited attempts unless you set max_attempts | Built into the cluster, editable in the admin | Written for Django |
| Huey 2.5.0 (20 September 2023)14 | Redis, SQLite, file system, memory | Fails once. Retries if you set retries on the task | Periodic tasks like cron, built in | huey.contrib.djhuey |
| Dramatiq 1.16.0 (25 January 2024)15 | RabbitMQ, Redis | Retries with exponential backoff, up to 20 times | Recommends APScheduler alongside | The separate django dramatiq package |
| RQ 1.16.1 (9 March 2024)16 | Redis only | Fails once. Retries if you pass Retry(max=...) | enqueue_at and enqueue_in, cron through rq scheduler | The separate django rq package |
Two rows deserve a second look. Dramatiq assumes every task is safe to run twice and retries by default15. Django Q2 with its ORM broker stores tasks as ordinary rows in your own database, and its documentation calls that the "most convenient guaranteed delivery broker" for medium message rates13. That has a consequence the documentation does not spell out, and I think it is the most interesting thing in the table: if you enqueue to the ORM broker inside a transaction on the same database, the task row commits or rolls back with your data. The doorbell becomes part of the letter. That follows from how transactions work, not from any feature of Django Q2, and it is the same reason some Rails teams like database backed job backends.
Example: counting Freewheel's moving parts
Freewheel sends roughly 2,300 bike ready messages a week (an email and an SMS for each of about 1,150 repairs), a good few hundred photo processing tasks a day and one report a night. Any of the five libraries handles that without noticing. So Aisling and Cian compared processes to run and watch, not throughput:
- Celery with Redis: web, worker, beat and Redis. Four processes.
- Django Q2 with the ORM broker: web and the cluster, with PostgreSQL already there. Two processes.
- Huey with Redis: web, the consumer (which runs periodic tasks too) and Redis. Three processes.
They chose Celery with Redis. Celery is the long standing choice (its first release on the Python Package Index dates from 200910), it has the deepest documentation, and Python developers who join later are likely to have met it. The patterns in this chapter, the letter, the on commit enqueue and the idempotent task, carry over unchanged to any of the others.
My view: for a small team, the number of processes you must keep alive matters more than any benchmark. Celery is a sound default when you expect to grow into its features. If your volume looks like Freewheel's and nobody on the team wants to run Redis, Django Q2 with the ORM broker is a fair, simpler choice, and it gives you transactional enqueueing for free. What I would not do is pick by blog post popularity and then discover the default failure behaviour in production.
Setting up Celery in a Django project
Celery's own guide for Django gives the setup, and it is short12. You create a Celery application next to your settings, tell it to read its configuration from Django settings with the prefix CELERY_, and let it discover a tasks.py module in each installed app.
Example: the Celery application at Freewheel
Install the libraries first. The versions are the current ones at the time of writing:
python -m pip install "celery[redis]==5.4.0" "django-anymail[postmark]==10.3" \
"django-storages[s3]==1.14.2" "Pillow==10.3.0"
The Celery application lives next to settings.py:
# freewheel/celery.py
import os
from celery import Celery
# The worker needs to know which settings to load, just like manage.py does.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "freewheel.settings")
app = Celery("freewheel")
# Every Celery setting comes from Django settings, written as CELERY_SOMETHING.
app.config_from_object("django.conf:settings", namespace="CELERY")
# Finds tasks.py in every installed app: notifications, repairs, parts.
app.autodiscover_tasks()
# freewheel/__init__.py
# Load the Celery app when Django starts, so @shared_task binds to it.
from .celery import app as celery_app
__all__ = ("celery_app",)
Then the settings. Each line is a decision, so each has a comment:
# freewheel/settings.py (the lines this chapter adds)
import os
CELERY_BROKER_URL = os.environ["REDIS_URL"]
# Acknowledge a message only after the task has finished, so a crash means
# redelivery. Safe only because every task below can run twice.
CELERY_TASK_ACKS_LATE = True
# With late acknowledgement, take one message at a time per worker process.
CELERY_WORKER_PREFETCH_MULTIPLIER = 1
# No task may hang forever on a slow provider.
CELERY_TASK_SOFT_TIME_LIMIT = 240 # seconds: raises inside the task
CELERY_TASK_TIME_LIMIT = 300 # seconds: the worker kills the process
# Schedules run in the business's own time zone.
CELERY_TIMEZONE = "Europe/Dublin"
In development, Cian runs the worker and the scheduler in two terminals:
celery -A freewheel worker --loglevel=INFO
celery -A freewheel beat --loglevel=INFO
Enqueue after commit, never before
The first and most common Django task bug is in Celery's own documentation: a view creates a row and queues a task with its id, and the task starts before the view's transaction has committed. The worker looks for the row and cannot find it12. The reverse is worse: the task finds nothing wrong, the transaction then rolls back, and you have sent an email about something that does not exist.
Django's answer is transaction.on_commit. You give it a function, and Django runs that function only after the current transaction commits. If the transaction rolls back, the function is discarded and never called1. Celery 5.4, released on 17 April 2024, adds a shortcut: tasks gain a delay_on_commit method that does exactly this wrapping for you12. With the setup above, every @shared_task already has it.
Two details from the Django documentation matter in practice. If you call on_commit outside any transaction, the function runs immediately, which is fine because autocommit has already saved your row. And the function runs after the commit, not inside it, so if queueing fails, your data stays committed1. That second detail is exactly the gap the letter and the doorbell closes: a committed letter with a lost doorbell is picked up by the sweeper.
Example: marking a bike ready
This is the function the workshop board calls when a mechanic moves a card to "ready". The board itself is in the chapter on templates, htmx or an API.
# repairs/services.py
from django.db import transaction
from django.utils import timezone
from notifications.models import Notification
from notifications.tasks import deliver_notification
from .models import JobCard
def mark_ready(job_card_id):
with transaction.atomic():
# Lock the card so two clicks on the board cannot both pass the check.
card = JobCard.objects.select_for_update().get(pk=job_card_id)
if card.status == JobCard.Status.READY:
return card # already ready: nothing to change, nothing to send
card.status = JobCard.Status.READY
card.ready_at = timezone.now()
card.save(update_fields=["status", "ready_at"])
customer = card.booking.customer
channels = [Notification.Channel.EMAIL]
if customer.mobile:
channels.append(Notification.Channel.SMS)
for channel in channels:
# The letter: written in the same transaction as the status change.
note, created = Notification.objects.get_or_create(
job_card=card, kind=Notification.Kind.BIKE_READY, channel=channel
)
if created:
# The doorbell: queued only if and when the transaction commits.
deliver_notification.delay_on_commit(note.pk)
return card
Walk through the Saturday failure again with this code. If the parts step later in the same request raises, the whole transaction rolls back: no status change, no Notification rows, and the delay_on_commit callbacks are discarded. Nothing is sent. If everything commits, both messages are queued, each carrying one integer.
Niamh made one business decision here. The unique constraint on the letter (below) means a card gets one bike ready message per channel, ever. If a bike goes back into repair and comes out again, the customer is not texted twice. Had she wanted a second message, the letter would need a round number. That choice belongs to the business, not to the developer, which is why it is worth saying out loud.
Tasks that survive being run twice
A task is idempotent when running it twice has the same effect as running it once. Celery's documentation asks for this directly: ideally tasks are idempotent, and the acks_late option, which acknowledges a message only after the task returns, is only safe when they are2. With late acknowledgement, a worker that crashes halfway leaves the message unacknowledged, and another worker runs it again.
Three more rules from the same documentation keep tasks safe:
- Pass ids, not objects. Celery advises against passing Django model instances to tasks, because the task may run minutes later with stale data. Fetch the row inside the task instead2.
- Know the visibility timeout. With Redis as the broker, a message that is not acknowledged within the visibility timeout (one hour by default) is delivered again to another worker. A task scheduled further in the future than that, or one that runs longer, can run repeatedly17.
- Expect the hard limit to skip redelivery. When a worker process is killed, for example by the time limit, Celery acknowledges the message even with
acks_late, on purpose, so that a task that crashes the process is not retried forever2. That task is simply gone. The letter is what remembers it.
Example: the notification letter and its task
The letter is a small model with a unique constraint that makes a duplicate letter impossible at the database level:
# notifications/models.py
from django.db import models
class Notification(models.Model):
class Kind(models.TextChoices):
BIKE_READY = "bike_ready", "Bike ready"
class Channel(models.TextChoices):
EMAIL = "email", "Email"
SMS = "sms", "SMS"
class Status(models.TextChoices):
PENDING = "pending", "Pending"
SENT = "sent", "Sent"
FAILED = "failed", "Failed"
job_card = models.ForeignKey(
"repairs.JobCard", on_delete=models.CASCADE, related_name="notifications"
)
kind = models.CharField(max_length=30, choices=Kind) # Django 5.0 accepts the class
channel = models.CharField(max_length=10, choices=Channel)
status = models.CharField(max_length=10, choices=Status, default=Status.PENDING)
provider_message_id = models.CharField(max_length=200, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
sent_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["job_card", "kind", "channel"], name="one_letter_per_card_kind_channel"
)
]
indexes = [models.Index(fields=["status", "created_at"])] # for the sweeper
The task locks the letter, checks it, acts, and records the result in one short transaction:
# notifications/tasks.py
import requests
from anymail.exceptions import AnymailAPIError
from celery import shared_task
from django.db import transaction
from django.utils import timezone
from .models import Notification
from .senders import SmsTemporaryError, send_bike_ready_email, send_bike_ready_sms
SENDERS = {
Notification.Channel.EMAIL: send_bike_ready_email,
Notification.Channel.SMS: send_bike_ready_sms,
}
TEMPORARY_ERRORS = (
AnymailAPIError, # the email provider's API failed or timed out
SmsTemporaryError, # the SMS provider said "try again later"
requests.ConnectionError,
requests.Timeout,
)
@shared_task(
acks_late=True,
autoretry_for=TEMPORARY_ERRORS,
retry_backoff=5, # first retry after up to 5 s, then 10, 20, 40 ...
retry_backoff_max=600, # never wait more than 10 minutes between tries
retry_jitter=True, # a random wait up to that ceiling
max_retries=6,
)
def deliver_notification(notification_id):
with transaction.atomic():
# A second worker with the same id waits here until the first commits.
note = Notification.objects.select_for_update().get(pk=notification_id)
if note.status != Notification.Status.PENDING:
return f"skipped, already {note.status}"
# The one outside call. If it raises, the transaction rolls back,
# the letter stays pending and Celery retries.
provider_id = SENDERS[note.channel](note)
note.status = Notification.Status.SENT
note.provider_message_id = provider_id or ""
note.sent_at = timezone.now()
note.save(update_fields=["status", "provider_message_id", "sent_at"])
return "sent"
Holding a row lock while calling a provider is a trade off. It keeps a database connection busy for the length of one HTTP call, a few hundred milliseconds normally and at most the provider timeout. At Freewheel's volume that costs nothing and buys a simple guarantee: two deliveries of the same doorbell cannot both send. At a hundred times the volume, I would switch to a status of "sending" claimed in its own short transaction.
One gap remains, and no queue can close it: if the provider accepts the message and the worker dies before the commit, the letter is still "pending" and will be sent again. That window is milliseconds wide. If your provider accepts an idempotency key or a client reference, pass the letter's id and let the provider drop the duplicate.
Retries that cover a blip, not an outage
Retries exist for short, temporary failures: a timeout, a provider returning "try again". Celery's retry_backoff spaces them out exponentially. With a factor of 5, the first retry waits up to 5 seconds, the second up to 10, then 20, and so on, capped by retry_backoff_max, which defaults to 600 seconds. With retry_jitter, which is on by default, the actual wait is a random number between zero and that ceiling, so a thousand failed tasks do not all retry in the same second2.
The ceiling for retry number is (Foundations: expected value):
where is the longest possible wait before retry in seconds, is the retry_backoff factor, is the retry number starting at 1, and is retry_backoff_max.
The question that matters for design is how long the task can keep trying in the worst case, from the first attempt to the last. Add every backoff ceiling to the time each attempt can take:
where is the longest time from the first attempt to giving up, is max_retries, is the number of attempts including the first, and is the longest a single attempt can take, which is the provider timeout.
Because the jitter is uniform between zero and the ceiling, the expected wait before each retry is half its ceiling (Foundations: expected value):
where is the average total waiting time across all retries and is the ceiling from the first formula.
Example: how long Freewheel's SMS task keeps trying
Freewheel's task uses , and . Anymail's default timeout for the email provider is 30 seconds18, and Aisling set 10 seconds for the SMS provider, so the worst case uses . Doubling from 5, the six ceilings are 5, 10, 20, 40, 80 and 160 seconds, and none reaches the 600 second cap. Their sum is the waiting ceiling:
So seconds. With attempts of up to seconds each, the worst case for the whole task is:
That is seconds, just under nine minutes. The expected waiting time across the retries is half the waiting ceiling:
So on average seconds, about two and a half minutes, are spent waiting between attempts.
So the retries cover a provider blip of a few minutes. They do not cover an outage of half an hour, and they should not: a task that retries for hours ties up a worker and hides the problem. The half hour outage is the sweeper's job. The maths also sets the sweeper's threshold. If the sweeper picks up letters older than 15 minutes, it can never ring the doorbell while the original task is still retrying, because the worst case is under nine minutes. Had Aisling set ten retries, the ceilings would grow to 320, 600 and 600 seconds, the worst case would pass 40 minutes, and a 15 minute sweeper would start ringing doorbells for tasks still in flight.
Example: the sweeper that rings again
The sweeper is a periodic task. It runs every ten minutes, rings the doorbell again for letters pending longer than 15 minutes, and marks letters older than a day as failed so a manager sees them in the back office instead of a customer never hearing anything:
# notifications/tasks.py (continued)
from datetime import timedelta
@shared_task
def requeue_stuck_notifications():
now = timezone.now()
pending = Notification.objects.filter(status=Notification.Status.PENDING)
# Older than a day: stop trying and show it to a manager.
gave_up = pending.filter(created_at__lt=now - timedelta(days=1)).update(
status=Notification.Status.FAILED
)
# Older than 15 minutes, which is longer than the worst case retry window.
stuck = pending.filter(created_at__lt=now - timedelta(minutes=15))
ids = list(stuck.values_list("pk", flat=True)[:500])
for pk in ids:
deliver_notification.delay(pk) # safe: the task checks the status first
return {"requeued": len(ids), "failed": gave_up}
Notice what this does to Redis. If Redis loses every queued message in a restart, Freewheel loses nothing: every letter is still in PostgreSQL, and the sweeper rings again within ten minutes. Redis durability becomes a question of speed, not of correctness, which is a much better question to have.
The whole path of one notification, from the board to the customer, looks like this:
Sending email in Django
Django's email library has two levels. send_mail(subject, message, from_email, recipient_list) covers the simple case and is a thin wrapper. For anything more (HTML and text versions, attachments, extra headers, reply to addresses) the documentation points you to the EmailMessage class and its subclass EmailMultiAlternatives, which adds attach_alternative() for an HTML version next to the plain text4.
Where the email actually goes is decided by the EMAIL_BACKEND setting, not by your code4. That is what makes Django's email testable and portable:
- Development: the console backend,
django.core.mail.backends.console.EmailBackend, prints every email to the terminal instead of sending it. The documentation calls it the easiest way to configure email for local development4. - Tests: Django's test runner automatically replaces your backend with an in memory outbox,
django.core.mail.outbox, so tests can count and read messages without sending any19. - Production: either SMTP, Django's default backend, or a provider's HTTP API through a library. Anymail is the established one: it supports Amazon SES, Brevo, Mailgun, Mailjet, Postmark, SendGrid, SparkPost and others behind the same Django email API, so changing provider is a settings change18.
Two traps are worth knowing before you write the first template. Django's EMAIL_TIMEOUT setting, which applies to the SMTP backend, defaults to None, meaning no timeout of its own5. A worker blocked on a silent mail server is a worker doing nothing, so set one. And Django templates escape HTML by default20, whatever the file extension. A plain text email rendered from body.txt turns "Byrne & Sons" into Byrne & Sons unless you switch escaping off for that template.
Example: the bike ready email and SMS
The settings first. Development prints, production goes through Anymail:
# freewheel/settings.py
if DEBUG:
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
else:
EMAIL_BACKEND = "anymail.backends.postmark.EmailBackend"
ANYMAIL = {
"POSTMARK_SERVER_TOKEN": os.environ["POSTMARK_SERVER_TOKEN"],
"REQUESTS_TIMEOUT": 30, # seconds, Anymail's default, written down
}
DEFAULT_FROM_EMAIL = "Freewheel Cycles <workshop@freewheelcycles.example>"
SITE_URL = os.environ.get("SITE_URL", "http://localhost:8000") # tasks have no request
The sender functions turn a letter into a message. The email is rendered from three templates, subject, text and HTML:
# notifications/senders.py
import requests
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.urls import reverse
class SmsTemporaryError(Exception):
"""The SMS provider asked us to try again later."""
def _context(note):
card = note.job_card
booking = card.booking
return {
"customer": booking.customer,
"bike": booking.bike,
"workshop": booking.workshop,
# A link to the job page, by the card's random public token. The page
# checks who is asking. Never a link straight to a photo file.
"job_url": settings.SITE_URL + reverse("repairs:job_status", args=[card.public_token]),
}
def send_bike_ready_email(note):
context = _context(note)
subject = render_to_string("notifications/bike_ready/subject.txt", context).strip()
text = render_to_string("notifications/bike_ready/body.txt", context)
html = render_to_string("notifications/bike_ready/body.html", context)
message = EmailMultiAlternatives(
subject=subject,
body=text, # the plain text version every client can read
to=[context["customer"].email],
headers={"X-Freewheel-Notification": str(note.pk)},
)
message.attach_alternative(html, "text/html")
message.send() # raises on failure, so the task can retry
status = getattr(message, "anymail_status", None) # absent with the console backend
return status.message_id if status else ""
def send_bike_ready_sms(note):
context = _context(note)
text = render_to_string("notifications/bike_ready/sms.txt", context).strip()
response = requests.post(
settings.SMS_API_URL,
json={"to": context["customer"].mobile, "text": text, "reference": f"freewheel-{note.pk}"},
headers={"Authorization": f"Bearer {settings.SMS_API_TOKEN}"},
timeout=10,
)
if response.status_code == 429 or response.status_code >= 500:
raise SmsTemporaryError(response.status_code) # retried by the task
response.raise_for_status() # any other error is permanent: no retry
return response.json().get("id", "")
The SMS provider here is a stand in with an invented URL. Real providers differ in their API, but the shape is the same: a timeout on every call, temporary errors raised as a type the task retries, permanent errors left alone, and the letter's id passed as a reference.
The text template switches autoescaping off, because it is not HTML:
{% autoescape off %}Hello {{ customer.first_name }},
your {{ bike.make }} is ready to collect from {{ workshop.name }}.
We are open until {{ workshop.closes_at|time:"g.i a" }} today.
See the repair notes and photos: {{ job_url }}
Freewheel Cycles
{% endautoescape %}
The words in that template are Freewheel's, so the "we" in it is Freewheel speaking to its customer. The HTML version extends a shared email layout and keeps escaping on, which is exactly where you want it.
Schedules with celery beat
Celery beat is the scheduler: a separate process that sends task messages at set times, read by default from the beat_schedule setting11. It does not run tasks itself. Two facts from its documentation shape how you deploy it. First, you must make sure only one scheduler runs for a schedule at a time, or every task runs as many times as there are schedulers11. Two web containers that each start beat "for convenience" send the nightly report twice. Second, schedules use UTC unless you set a time zone, and Celery uses Django's TIME_ZONE when it runs inside a Django project11.
A local time zone brings one more trap: the night the clocks change. In Ireland the clocks go forward at 1am in March and back at 2am in October, so a job set between 1am and 2am either meets a missing hour or a doubled one21. I do not trust any scheduler's handling of that night. I schedule outside it.
Example: the nightly parts reorder report
Freewheel keeps about 2,400 spare parts in stock. Every night the application lists the parts at or below their reorder level, grouped by supplier, saves the list as a CSV file and emails it to the managers. The report gets a letter of its own, one row per night, so a second run of the same night does nothing:
# parts/models.py (the report; Part and Supplier are in the ORM chapter)
class ReorderReport(models.Model):
for_date = models.DateField(unique=True) # one report per night, enforced
file = models.FileField(upload_to="reports/reorder/", blank=True)
line_count = models.PositiveIntegerField(default=0)
emailed_at = models.DateTimeField(null=True, blank=True)
# parts/tasks.py
import csv
import io
from datetime import date
from pathlib import Path
from anymail.exceptions import AnymailAPIError
from celery import shared_task
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.mail import EmailMessage
from django.db.models import F
from django.utils import timezone
from .models import Part, ReorderReport
def _reorder_csv():
parts = list(
Part.objects.filter(stock_quantity__lte=F("reorder_level"))
.select_related("supplier")
.order_by("supplier__name", "sku")
)
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(["supplier", "sku", "part", "in stock", "reorder level", "order quantity"])
for part in parts:
writer.writerow([part.supplier.name, part.sku, part.name,
part.stock_quantity, part.reorder_level, part.reorder_quantity])
return buffer.getvalue().encode("utf-8"), len(parts)
@shared_task(acks_late=True, autoretry_for=(AnymailAPIError,), retry_backoff=60, max_retries=5)
def build_reorder_report(for_date_iso=None):
for_date = date.fromisoformat(for_date_iso) if for_date_iso else timezone.localdate()
report, _ = ReorderReport.objects.get_or_create(for_date=for_date)
if report.emailed_at:
return "already sent" # a second beat, a manual rerun: nothing happens
if not report.file: # a retry after a failed email reuses the saved file
content, count = _reorder_csv()
report.file.save(f"reorder-{for_date}.csv", ContentFile(content), save=False)
report.line_count = count
report.save(update_fields=["file", "line_count"])
with report.file.open("rb") as stored:
attachment = stored.read()
message = EmailMessage(
subject=f"Parts to reorder, {for_date:%A %d %B}: {report.line_count} lines",
body="The reorder list for all six workshops is attached.",
to=settings.REORDER_REPORT_TO,
)
message.attach(Path(report.file.name).name, attachment, "text/csv")
message.send()
report.emailed_at = timezone.now()
report.save(update_fields=["emailed_at"])
return f"sent {report.line_count} lines"
The schedule sits in settings, at 4.30am, well clear of the hour the clocks change:
# freewheel/settings.py
from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
"nightly-reorder-report": {
"task": "parts.tasks.build_reorder_report",
"schedule": crontab(hour=4, minute=30),
},
"requeue-stuck-notifications": {
"task": "notifications.tasks.requeue_stuck_notifications",
"schedule": crontab(minute="*/10"),
},
}
In production, Freewheel runs exactly one beat process, as its own service, never inside a web container that might be scaled to two. If a manager wants last Tuesday's report again, Cian deletes that night's row in the admin and runs build_reorder_report.delay("2024-04-23"). Because the task takes the date as an argument, a rerun for a past night is one line.
Files: FileField, ImageField and where uploads go
A FileField on a model stores a name in the database and the bytes in a storage backend. ImageField is a FileField that also validates the upload is an image, and it requires Pillow9. With the default FileSystemStorage, files land under the MEDIA_ROOT directory and are addressed through MEDIA_URL.
The upload_to argument decides the file's path. It can be a string, or a function that receives the model instance and the original filename and returns a path. The documentation warns that the instance is usually not saved yet, so its own primary key may not exist9. Use the ids of things that already exist, such as the parent job card.
The form in the template needs enctype="multipart/form-data". Without it the browser sends only the file name, request.FILES is empty, and the form complains that no file was submitted. It is the most common "uploads do not work" question there is.
Example: before and after photos on a job card
# repairs/models.py (the photo model)
import uuid
from pathlib import Path
from django.conf import settings
from django.core.validators import FileExtensionValidator
from django.db import models
def job_photo_path(instance, filename):
# job-cards/4812/before/1f0c....jpg: the card exists, the photo row does not yet.
suffix = Path(filename).suffix.lower()
return f"job-cards/{instance.job_card_id}/{instance.kind}/{uuid.uuid4().hex}{suffix}"
class JobPhoto(models.Model):
class Kind(models.TextChoices):
BEFORE = "before", "Before"
AFTER = "after", "After"
job_card = models.ForeignKey("repairs.JobCard", on_delete=models.CASCADE, related_name="photos")
kind = models.CharField(max_length=6, choices=Kind)
image = models.ImageField(
upload_to=job_photo_path,
validators=[FileExtensionValidator(["jpg", "jpeg", "png", "webp"])],
)
processed = models.BooleanField(default=False)
uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
uploaded_at = models.DateTimeField(auto_now_add=True)
A random name per file matters more than it looks. The original filename from a phone ("IMG_0001.jpg") repeats constantly, and the S3 backend of django storages overwrites a file with the same name by default22. A UUID in the path means two mechanics photographing two bikes can never overwrite each other's evidence.
Validating uploads before you trust them
Upload validation has more layers than most people expect, and the one people rely on, a Django setting, does not do what they think. DATA_UPLOAD_MAX_MEMORY_SIZE caps the size of a request body, but its documentation says it is calculated excluding any file upload data5. FILE_UPLOAD_MAX_MEMORY_SIZE is not a limit either: it is the size above which Django streams an upload to a temporary file instead of holding it in memory5. Django has no setting that rejects a large file.
So the layers are these:
- The web server rejects oversized requests before Django sees them, which the Django security documentation strongly advises23. In nginx the directive is
client_max_body_size, and its default is 1 megabyte24, smaller than almost any phone photo. A mechanic's upload that fails with "413 Request Entity Too Large" has never reached your code. - The form checks the size and extension of each file and returns a message a person can act on.
- The image library.
ImageFielduses Pillow to check that the file is an image9. Pillow also guards against decompression bombs, small files that expand into enormous images, with a warning above a pixel limit and an error above twice that25. - Where you serve it from. The Django security documentation warns that a file can pass Pillow's check as a PNG and still contain HTML, and recommends serving user uploads from a different domain, not merely a subdomain23.
Example: Freewheel's photo upload
nginx in front of Freewheel allows 20 megabytes per request, so the form can give a friendly message for anything between 15 and 20:
# repairs/forms.py
from django import forms
from .models import JobPhoto
MAX_PHOTO_BYTES = 15 * 1024 * 1024
class JobPhotoForm(forms.ModelForm):
class Meta:
model = JobPhoto
fields = ["kind", "image"]
widgets = {"image": forms.FileInput(attrs={"accept": "image/*"})}
def clean_image(self):
image = self.cleaned_data["image"]
if image.size > MAX_PHOTO_BYTES:
raise forms.ValidationError(
"That photo is larger than 15 MB. Please take it again at a lower resolution."
)
return image
# repairs/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
from .forms import JobPhotoForm
from .models import JobCard
from .tasks import process_job_photo
@login_required
@require_POST
def upload_photo(request, card_id):
card = get_object_or_404(JobCard, pk=card_id)
form = JobPhotoForm(request.POST, request.FILES)
if not form.is_valid():
return render(request, "repairs/job_card.html", {"card": card, "photo_form": form}, status=422)
photo = form.save(commit=False)
photo.job_card = card # set before save: job_photo_path needs the card id
photo.uploaded_by = request.user
photo.save() # the file is written to storage here
process_job_photo.delay_on_commit(photo.pk)
return redirect(card)
Model field validators run through the form, not on save(), as the ORM chapter explained, so the extension check above only protects you because the upload goes through JobPhotoForm. Who may upload to which card is a permission question, and it belongs to the authentication chapter later in this series.
Processing photos in the background
A photo from a phone is far larger than a job card needs, it may be stored sideways with an orientation tag, and it may carry the location where it was taken in its metadata. All three are reasons to process every upload once, in a task, rather than in the request where the mechanic waits.
Pillow's ImageOps.exif_transpose turns an image the right way up according to its orientation tag and removes the tag25. When Pillow saves a JPEG, it writes metadata only if you pass it in with the exif argument25. So a resized copy saved without that argument carries no location data. That is a privacy improvement for every customer whose bike was photographed in their own front garden on a mobile repair.
The storage saving is large enough to compute. For the size of one year of photos (Foundations: ratios and rates):
where is the storage needed per year, is bookings per week, is photos per booking, is weeks per year and is the average size of one photo.
Example: one year of Freewheel's photos
Freewheel has bookings a week and takes at least photos per repair, one before and one after, over weeks. The photo sizes are my assumptions for the illustration, not measurements: 4 MB for a photo straight from a phone, 0.3 MB after resizing to 1,600 pixels on the long side.
That is photos a year. At MB straight from the phone, measured in megabytes:
So GB a year. At MB after resizing:
So GB a year.
That is about a thirteenth of the storage, and every page that shows a photo loads a thirteenth of the bytes. The task:
# repairs/tasks.py
from io import BytesIO
from pathlib import Path
from celery import shared_task
from django.core.files.base import ContentFile
from PIL import Image, ImageOps
from .models import JobPhoto
LONG_SIDE = 1600
@shared_task(acks_late=True)
def process_job_photo(photo_id):
photo = JobPhoto.objects.filter(pk=photo_id, processed=False).first()
if photo is None:
return "nothing to do" # already processed, or deleted meanwhile
with photo.image.open("rb") as original:
image = Image.open(original)
image = ImageOps.exif_transpose(image) # right way up, orientation tag removed
image = image.convert("RGB") # JPEG has no transparency
image.thumbnail((LONG_SIDE, LONG_SIDE)) # keeps the proportions
buffer = BytesIO()
image.save(buffer, format="JPEG", quality=82) # no exif argument: no location data
old_name = photo.image.name
photo.image.save(f"{Path(old_name).stem}.jpg", ContentFile(buffer.getvalue()), save=False)
photo.processed = True
photo.save(update_fields=["image", "processed"])
if old_name != photo.image.name:
photo.image.storage.delete(old_name) # last step: if this fails, the sweep catches it
return "processed"
The order of the last lines is deliberate. The new file is written first, the row is pointed at it second, the old file is deleted last. A crash at any point leaves at worst an orphaned file, never a row pointing at nothing.
Storage backends and private files
Files on the web server's disk disappear when a container is replaced and cannot be shared between two servers. Production files belong in object storage. Since Django 4.2 you configure that in the STORAGES setting, which names a default storage for files and a staticfiles storage for static assets5. django storages provides the backends. Its S3 backend, storages.backends.s3.S3Storage, works with Amazon S3 and, through the endpoint_url option, with other providers that offer the same API22.
For private files, three of its options do the work. default_acl left at None keeps files private, as the provider's default. querystring_auth, on by default, makes every URL that photo.image.url returns a signed one. querystring_expire sets how long that signature is valid, 3,600 seconds by default22. A signed URL is a normal link with a signature in its query string; after it expires, the storage refuses it.
Signed URLs answer "who may fetch this file for the next few minutes". They do not answer "who may see this job card", which is your application's question. So the page decides, and the URL only carries that decision for a short while. That is also why the bike ready email above links to the job page and never straight to a photo: an email lives for years, a five minute signature does not.
Example: Freewheel's private photo storage
# freewheel/settings.py (production)
STORAGES = {
"default": {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS": {
"bucket_name": os.environ["MEDIA_BUCKET"],
"endpoint_url": os.environ.get("MEDIA_ENDPOINT_URL"), # for S3 compatible providers
"region_name": os.environ.get("MEDIA_REGION"),
"default_acl": None, # private: the provider's default
"querystring_auth": True, # every URL is signed
"querystring_expire": 300, # and valid for five minutes
"file_overwrite": False, # never replace an existing file silently
},
},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
In the job card template, {{ photo.image.url }} now produces a fresh five minute link every time the page renders, and only users who pass the view's permission check ever see the page. The photos are served from the storage provider's own domain, not from freewheelcycles.example, which happens to satisfy the Django documentation's advice to serve uploads from a separate domain23.
Rails' Active Storage can also upload straight from the browser to the storage service, so large files never pass through the web server26. Django has no built in equivalent. The usual route is a signed upload form generated with boto3's presigned POST27, plus a little JavaScript. At Freewheel, photos are a few megabytes each and the workshops have decent wifi, so Aisling and Cian left uploads going through Django. With video of a wheel wobble, I would revisit that.
Files the database forgot
The Django documentation is explicit: when a model instance is deleted, its files are not deleted, and cleaning up orphans is left to you, for example with a management command run periodically9. Orphans also come from the processing task above when it crashes before its last line, and from uploads whose transaction rolled back after the file was written.
The safe approach compares storage with the database, ignores anything recent (an upload may be halfway through its transaction), and by default only reports.
Example: the orphan sweep
# repairs/management/commands/sweep_orphan_photos.py
from datetime import timedelta
from django.core.files.storage import storages
from django.core.management.base import BaseCommand
from django.utils import timezone
from repairs.models import JobPhoto
def walk(storage, path):
"""Every file under a path, through the storage API, local or S3."""
directories, files = storage.listdir(path)
for name in files:
yield f"{path}/{name}"
for directory in directories:
yield from walk(storage, f"{path}/{directory}")
class Command(BaseCommand):
help = "Find stored job photos that no database row points to."
def add_arguments(self, parser):
parser.add_argument("--delete", action="store_true", help="Delete them, not just list them.")
def handle(self, *args, delete=False, **options):
storage = storages["default"]
known = set(JobPhoto.objects.values_list("image", flat=True))
grace = timezone.now() - timedelta(days=1)
orphans = [
name for name in walk(storage, "job-cards")
if name not in known and storage.get_modified_time(name) < grace
]
for name in orphans:
self.stdout.write(name)
if delete:
storage.delete(name)
self.stdout.write(f"{len(orphans)} orphaned files" + (" deleted" if delete else " found"))
Cian runs it weekly without --delete for the first month, reads the list, and only then lets the schedule delete. A sweep that deletes on its first run is a sweep nobody has checked.
Rails and Django side by side
The same three jobs, as each framework ships them at this date. The Rails column summarises the Rails chapter on jobs, email and files.
| Job | Rails 7.1 | Django 5.0 |
|---|---|---|
| Background work interface | Active Job, built in, :async adapter by default7 | None built in, a DEP under discussion6. Celery, Django Q2, Huey, Dramatiq or RQ |
| Production queue | Sidekiq, GoodJob, Delayed Job, Resque behind Active Job | The library itself, each with its own API |
| Queue after commit | An after_commit callback that calls perform_later | transaction.on_commit, or delay_on_commit in Celery 5.412 |
| Recurring work | The backend's scheduler or a gem | celery beat, or the library's scheduler |
| Writing email | Action Mailer classes and views | EmailMultiAlternatives plus render_to_string |
| Preview email in a browser | Mailer previews, built in | None built in |
| Development and tests | Delivery methods, test deliveries | Console backend, in memory outbox4 |
| Email providers | Delivery method gems | Anymail backends18 |
| Files on records | has_one_attached, has_many_attached | FileField, ImageField |
| Image variants | Built in, through image processing | None built in: Pillow, or django imagekit, sorl thumbnail |
| Direct uploads | Built in26 | None built in: boto3 presigned POST27 |
| Signed, expiring URLs | Built in, 5 minutes by default7 | django storages, 3,600 seconds by default22 |
| Files of deleted records | Purged in the background by default (dependent: :purge_later)28 | Kept. Orphans are yours to sweep9 |
Read the table as a description of two philosophies, not a scoreboard. Rails decides more for you: one interface, one attachment system that handles variants, uploads and deletion. Django decides less and lets libraries compete: you assemble more, and in return the pieces are often deeper than a common interface would allow. A senior developer from either side should recognise their own framework in that sentence.
Example: the same feature, counted
Aisling and Cian's two spikes ended up remarkably close: both have a letter table, enqueue after commit, lock and check before sending, and run a sweeper. The Django version needed more setup and had no mailer preview, so Cian wrote a small staff only view that renders the email for a given card. Neither design was safer. The safety came from the letter and the doorbell, which belongs to neither framework.
Testing the parts that reach outside
Two Django features make this testable without a real queue or provider. TestCase.captureOnCommitCallbacks collects the functions registered with on_commit during a block, so you can assert what would be queued, and whether a rollback discarded it1. And the email outbox collects every message19. The full workflow, with factories and pytest, comes in the chapter on test driven development in Django later in this series.
Example: proving a rollback sends nothing
# repairs/tests/test_mark_ready.py
from django.db import transaction
from django.test import TestCase
from notifications.models import Notification
from repairs.services import mark_ready
from .helpers import make_job_card # builds a customer with a mobile, bike, booking, card
class MarkReadyTests(TestCase):
def test_queues_one_email_and_one_sms(self):
card = make_job_card(status="in_repair")
with self.captureOnCommitCallbacks() as callbacks:
mark_ready(card.pk)
self.assertEqual(len(callbacks), 2)
self.assertEqual(card.notifications.count(), 2)
def test_a_rolled_back_change_queues_nothing(self):
card = make_job_card(status="in_repair")
with self.captureOnCommitCallbacks() as callbacks:
with self.assertRaises(RuntimeError):
with transaction.atomic():
mark_ready(card.pk)
raise RuntimeError("the parts step failed")
self.assertEqual(callbacks, [])
self.assertFalse(Notification.objects.filter(job_card=card).exists())
def test_marking_ready_twice_queues_nothing_new(self):
card = make_job_card(status="in_repair")
mark_ready(card.pk)
with self.captureOnCommitCallbacks() as callbacks:
mark_ready(card.pk)
self.assertEqual(callbacks, [])
The second test is the Saturday morning failure from the start of this chapter, written down so it can never come back.
For the person paying for this
If you are Niamh, commissioning an application like this, you do not need to read the code. You need five answers, and any developer should give them in plain words:
- "Where is the record of every email and text we sent?" The right answer is a table in the database, with the provider's id. "In the provider's dashboard" means you cannot answer a customer's complaint from your own system.
- "What happens if Redis restarts during the Saturday rush?" The right answer is "nothing is lost, the sweeper sends what was waiting". If the answer involves hope, the letter is missing.
- "Show me the nightly jobs and what happens when one fails." You want a list, a schedule outside the night the clocks change, and a place where failures show up for a person.
- "Are the repair photos private, and are they deleted when we delete the job?" Private means signed, short lived links behind a permission check. Deleted means someone wrote the sweep, because Django does not do it alone.
- "How many processes does this need in production?" For Freewheel it is four: web, worker, beat and Redis. That number is a running cost and a maintenance cost, and you should know it before launch.
These are the questions I would ask of any application, whatever it is built with. If you want help putting them to your own project, or want an application built this way, the free workshop is where we start, and you can see how I build web applications on Ruby on Rails.
Conclusion
Email, uploads and background work look like three topics. They are one: work that reaches outside the database, which is the only part of your system that can say "never mind". Each such effect is unsendable, orphanable or repeatable, and each needs its own defence: wait for the commit, sweep the storage, make the task safe to run twice.
The rule that holds it together is the letter and the doorbell. Write what you intend to do as a row, in the same transaction as the change that causes it. Let the queue carry only the id. Lock and check before acting, retry for a few minutes, and let a sweeper ring again when the doorbell was lost. In Django 5.0 that means transaction.on_commit or Celery 5.4's delay_on_commit, a unique constraint, select_for_update, bounded retries whose worst case you have actually calculated, one beat process, private storage with short signed links, and a sweep for orphaned files. None of it is exotic. All of it is the difference between a system that works in a demo and one that works on a Saturday morning.
