ContentsClose contents
Pre-release
Chapter 44 · Background tasks, scheduling, and retriesCHAPTER 44

Complete six-part pre-release for review. Three migrations (the queue, deliveries, reminders). Chapter 43's email tests run tasks immediately, and one earlier form test changes (declared). The scheduler steps are printed, not run.

Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones

CHAPTER FORTY-FOUR

Background tasks, scheduling, and retries

Stage 5: Growing the application (Chapters 35 to 46)

Prerequisites: Chapters 9 to 43, including the Chapter 43 project with its 528 passing tests, the five emails and their send() (Chapter 43), Mailpit running in a second terminal, transactions, row locks, and unique constraints (Chapters 31 and 33), and management commands (Chapter 41)

What you’ll build: ADR-007, “Background work with Django’s task interface”; django-tasks-db, pinned, keeping the queue in PostgreSQL, and its worker in a second terminal; a Delivery row for every email, written with the change it is about and sent by a task after commit, at most once; three retries, then “failed”; reminders that organizers choose, 7 days, 24 hours, or 2 hours before; a command that the operating system’s scheduler runs every ten minutes, on Windows, macOS, and Linux; and delivery counts on the announcements page

Why This Matters

Since Chapter 43, Otahque tells members what happens to their places. It does so inside the request: when Sai presses Register, her page waits while Otahque talks to the mail server. When the mail server is slow, the button spins. When it is down, the email is logged and lost. When Sam sends an announcement to forty members, his page waits for forty emails, and if the server stops answering halfway, nobody can say who got it.

And members have asked for something no request can do at all: a reminder the day before. Nobody presses a button at that moment; Otahque has to notice the time by itself.

Both needs have the same answer: work that happens outside the request. The request records what must be done and returns at once; another process does it, retries it when it fails, and never does it twice. This chapter builds that, with Django’s own task interface, and makes the record of each email the thing that keeps the whole design honest.

By the end of the chapter, you will be able to:

  • tell apart a task interface, a backend, a worker, and a scheduler, and say what each does;
  • define a task, enqueue it after commit, and run a worker;
  • design an email delivery that can be retried without ever being sent twice;
  • recover work whose enqueue was lost, with the database as an outbox;
  • schedule a command on Windows, macOS, and Linux;
  • compare Django’s tasks with Celery, and defend a choice.

Out of scope: running the worker and the scheduler on a server (Chapter 62), monitoring queue depth and failures (Chapter 65), webhooks as tasks (Chapter 52), and a runnable Celery lab, which follows Chapter 62, when Redis is available (D44.5).

PAGE 001

What You Need to Know

Four different things

New Concept: background tasks

What problem exists? Some work is slow, can fail and need another try, or must happen at a time nobody is on the site. None of it belongs in a request.

What did people do before? Did it in the request anyway, ran a cron job that scanned tables, or installed Celery and a message broker.

What is it? A task is a function marked with @task; calling send_delivery.enqueue(42) does not run it, but records that it should run, with the argument 42. A backend, configured in TASKS, decides where that record goes. A worker is a separate process that takes records from the backend and runs them. A scheduler starts a command at set times. Django 6.1 provides the task interface; it ships only an immediate backend, which runs the task at once, and a dummy one, which keeps it for tests.

Why use it? The request only writes; the slow, failing work happens elsewhere, as many times as needed.

Now let’s use it. Step 2 adds a real backend and its worker.

The four are side by side in Figure 44.1. Keeping them apart in your head is most of the chapter: the task interface is Django’s, the backend and worker come from django-tasks-db, and the scheduler is your operating system’s.

Five numbered cards joined by arrows. 1, the request: saves the change and a Delivery row in one transaction; returns at once. 2, the task interface: @task and enqueue(), Django’s own; after commit, the task is enqueued with the delivery’s id. 3, the backend, django-tasks-db: keeps the queue as rows in PostgreSQL. 4, the worker, manage.py db_worker: a second process; runs each task when it is due. 5, the scheduler: Task Scheduler, cron, or a systemd timer runs send_due_reminders every ten minutes.
Figure 44.1 — The request, the task interface, the backend, the worker, and the scheduler.

Tool: django-tasks-db

django-tasks-db is a backend for Django’s task interface that keeps the queue in a table of your own database, with a worker command, db_worker. It is written by the author of Django’s task framework. Version 0.13.0 declares support for Django 5.2 and 6.0, not 6.1; the plan review tried it on Django 6.1.2, and Step 7’s test runs its worker on every test run, which is why Otahque may pin it (N44.6). Check it again at the Django 6.2 upgrade.

A delivery is a record

A task that sends an email can fail after sending: the mail server accepts the message, then the worker dies before it records success, and the task runs again. Without a record, Sai gets the email twice. Figure 44.3, after Step 6, shows the difference a record makes.

Otahque’s record is a Delivery row: one email, to one member, with a unique key made of the kind of email, what it is about, and the member. Queuing the same email twice finds the first row. The task locks the row, sends only if the row still says “queued”, and marks it “sent” in the same transaction. Figure 44.2 shows the states.

Five cards. Left, queued: written with the change; due now, or after a retry’s wait. An arrow labelled send_delivery leads right to three cards: sent, a mail server accepted it; skipped, no longer wanted, the place or event is gone; failed, a fourth failure, given up, logged. Below queued, retry: after 1, then 5, then 25 minutes, with arrows labelled fails between queued and retry.
Figure 44.2 — A delivery’s states.

Under the Hood: the outbox, and why it is needed here

Chapter 43 sent after commit with on_commit(). A task should be enqueued after commit too: enqueued inside a transaction that then rolls back, it would send an email about nothing, or, with a database queue, vanish with the rollback. But on_commit() has a gap: if the process dies between the commit and the enqueue, the work is lost. Django 6.1’s task interface has no enqueue-on-commit of its own. The outbox pattern closes the gap: the Delivery row is written inside the transaction, so it commits with the change; the task is enqueued after commit; and a scheduled command enqueues again any delivery still queued well past its time (N44.7). The row is the truth; the task is only a prompt.

Retries, and when to stop

A mail server that refuses a message now may accept it in a minute. Otahque retries a failed delivery three times, after 1, 5, and 25 minutes, waiting longer each time so a struggling server is not hammered, and then marks it “failed” (N44.8). Each retry is a new task with run_after, the earliest time it may run. Before every attempt, the task asks whether the email is still wanted: a reminder for a place that was cancelled is skipped, not sent.

Reminders, chosen by the organizer

Each event has reminders, chosen from 7 days, 24 hours, and 2 hours before the start; new events have the 24-hour one (D44.4). No request happens at those moments, so a command, send_due_reminders, runs every ten minutes from the operating system’s scheduler and queues each reminder whose time has passed. Its key has no time in it: when an organizer moves the event, an unsent reminder simply falls due at the new time, and a sent one is never sent again; the “event changed” email has told members already.

Table 44.1 — Who does what
Part Otahque's Runs where
Task interface events/tasks.py, @task Imported by the web app and the worker
Backend django-tasks-db A table in PostgreSQL
Worker manage.py db_worker A second terminal; a service on a server
Scheduler send_due_reminders Task Scheduler, cron, or a systemd timer
PAGE 002

How We Build It

Start from Chapter 43, in the folder containing manage.py, with Otahque on PostgreSQL 18, 528 passing tests, the work committed (the last commit is “Email members about their places and events”), and Mailpit running in a second terminal. One package is new, django-tasks-db 0.13.0, so Step 2 needs an internet connection once. Three migrations are new: the package’s own, and two in events. The new files are events/tasks.py, a send_due_reminders command, three test modules, ADR-007, and a scheduling runbook. The settings, the events models, emails, forms, and views, the registrations views, the test helpers, four of Chapter 43’s test modules and one earlier one, the event form and announcements templates, the stylesheet, and the email design note change. The visible result: pages answer without waiting for a mail server, a worker sends the emails, organizers choose reminders, and the announcements page counts what was sent. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

Without a task interface, a common answer is a table of “emails to send” and a cron job that reads it every minute. It works, and it is close to what this chapter builds; but each project writes its own loop, its own locking, and its own retry rules, and a second kind of background work means a second loop. Django’s task interface gives every kind of work one way in, enqueue(), and leaves the loop to a backend. Otahque keeps the table idea, as Delivery, for the part that is about email: what was sent, to whom, and how it went.

The Django Way

Step 1: Check the starting point

uv run python manage.py test --parallel
Found 528 test(s).
Creating test database for alias 'default'...
...
Ran 528 tests in ...s

OK
git status --short
git log --oneline -1
... Email members about their places and events

Step 2: A queue in PostgreSQL, and its worker

Add the backend, pinned; this is the one command in the chapter that needs the internet:

uv add django-tasks-db==0.13.0
Resolved 31 packages in ...
Installed 3 packages in ...
 + django-stubs-ext==6.1.2
 + django-tasks-db==0.13.0
 + typing-extensions==4.16.0

In config/settings.py, add 'django_tasks_db', as the last line of INSTALLED_APPS, and below the list:

# Background work (Chapter 44): Django's task interface, with
# django-tasks-db keeping the queue in PostgreSQL. A second
# process, manage.py db_worker, runs what is queued.
TASKS = {
    'default': {
        'BACKEND': 'django_tasks_db.DatabaseBackend',
    },
}

The package brings a table for the queue:

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying django_tasks_database.0001_initial... OK
  ...
  Applying django_tasks_database.0021_conditional_...... OK

The worker is a command. Normally you start it in another terminal and leave it running; with --batch it runs whatever is due and stops, which is handy now:

uv run python manage.py db_worker --batch --no-startup-delay
Warning: --reload and --batch cannot be specified together.
    Disabling autoreload.
Starting worker worker_id=... queues=default
No more tasks to run for worker_id=... - exiting gracefully.

The warning is worth reading. --reload restarts the worker when code changes, and it defaults to DEBUG, which is on for you; it cannot be combined with --batch. On a server, with DEBUG off, the worker runs the code it started with until it is restarted.

Step 3: The Delivery model

In events/models.py, above class OrganizerAssignment:

class Delivery(models.Model):
    """One email to one member, and what became of it.

    Written in the same transaction as the change it is
    about (Chapter 44); a task sends it after commit. key
    is unique, so the same email is never queued twice.
    """

    class Status(models.TextChoices):
        """Where a delivery is."""

        QUEUED = 'queued', 'Queued'
        SENT = 'sent', 'Sent'
        FAILED = 'failed', 'Failed'
        SKIPPED = 'skipped', 'Not needed any more'

    key = models.CharField(max_length=120, unique=True)
    member = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
        related_name='+',
    )
    event = models.ForeignKey(
        Event, on_delete=models.CASCADE,
        related_name='deliveries',
    )
    announcement = models.ForeignKey(
        Announcement, on_delete=models.CASCADE, null=True,
        blank=True, related_name='deliveries',
    )
    # What the email says, fixed when it is queued.
    subject = models.CharField(max_length=200)
    lines = models.JSONField(default=list)
    path = models.CharField(max_length=200)
    # Whether it must still be sent: 'place' checks the
    # member still holds a place in a published event.
    needs = models.CharField(max_length=20, blank=True)
    status = models.CharField(max_length=10, choices=Status,
                              default=Status.QUEUED)
    attempts = models.PositiveSmallIntegerField(default=0)
    last_error = models.CharField(max_length=200, blank=True)
    # When it should next be tried: now, or after a retry's
    # wait; send_due_reminders queues it again if it is
    # still queued ten minutes later.
    due_at = models.DateTimeField(default=timezone.now)
    sent_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['due_at', 'pk']
        verbose_name_plural = 'deliveries'

    def __str__(self):
        return self.key

    def still_wanted(self):
        """Return whether the email should still be sent."""
        if self.needs != 'place':
            return True
        return (self.event.status == Event.Status.PUBLISHED
                and self.event.holders().filter(
                    pk=self.member_id).exists())

The subject, lines, and link are fixed when the delivery is queued: the email says what was true at that moment, even if a retry sends it later. needs names the one check that can make an email unwanted before it is sent: 'place' for messages that only make sense while the member holds a place in a published event. skipped is the fourth state, for those. due_at is when the delivery should next be tried.

uv run python manage.py makemigrations -n deliveries events
uv run python manage.py migrate
Migrations for 'events':
  events\migrations\0012_deliveries.py
    + Create model Delivery
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying events.0012_deliveries... OK

Step 4: The task

The whole of Otahque’s background work, in a new file events/tasks.py:

"""Otahque's background work (Chapter 44).

Every email is a Delivery row, written in the transaction
of the change it is about, and a task, enqueued after
commit, that sends it. If the process dies between the
commit and the enqueue, send_due_reminders finds the row
still queued and enqueues it again: the row is the outbox.
"""
from datetime import timedelta

from django.db import transaction
from django.tasks import task
from django.utils import timezone

from . import emails
from .models import Delivery

# Minutes to wait before each retry: after the first,
# second, and third failure. A fourth failure is final.
RETRIES = [1, 5, 25]
# How long a queued delivery may wait past its time before
# it is enqueued again.
STALE = timedelta(minutes=10)


def queue(member, event, kind, about, subject, lines,
          needs='', announcement=None):
    """Queue one email to member, once; return (row, new).

    The key is the kind, what it is about, and the member,
    so the same email is never queued twice. Call it inside
    the transaction of the change: the row commits with the
    change, and the task is enqueued after.
    """
    delivery, new = Delivery.objects.get_or_create(
        key=f'{kind}:{about}:{member.pk}',
        defaults={
            'member': member, 'event': event,
            'announcement': announcement,
            'subject': subject, 'lines': lines,
            'path': event.get_absolute_url(), 'needs': needs,
        },
    )
    if new:
        emails.after_commit(enqueue, delivery.pk)
    return delivery, new


def enqueue(delivery_id, run_after=None):
    """Enqueue the task that sends a delivery.

    A backend that cannot wait, such as the immediate one
    tests use, runs a retry at once.
    """
    send = send_delivery
    if run_after and send.get_backend().supports_defer:
        send = send.using(run_after=run_after)
    send.enqueue(delivery_id)


@task
def send_delivery(delivery_id):
    """Send one queued email, at most once.

    The row stays locked while the email is sent, so two
    workers given the same delivery cannot both send it. A
    delivery no longer queued is left alone; one no longer
    wanted, such as a reminder for a cancelled place, is
    skipped. A failure is retried after RETRIES minutes.
    """
    with transaction.atomic():
        delivery = Delivery.objects.select_for_update(
            of=('self',),
        ).select_related('member', 'event').get(pk=delivery_id)
        if delivery.status != Delivery.Status.QUEUED:
            return delivery.status
        if not delivery.still_wanted():
            delivery.status = Delivery.Status.SKIPPED
        elif emails.send(delivery.member, delivery.subject,
                         delivery.lines, delivery.path):
            delivery.status = Delivery.Status.SENT
            delivery.sent_at = timezone.now()
        else:
            retry(delivery)
        delivery.save()
    return delivery.status


def retry(delivery):
    """Count a failure; enqueue a retry, or give up."""
    delivery.attempts += 1
    delivery.last_error = ('The mail server refused the email '
                           'or did not answer.')
    if delivery.attempts > len(RETRIES):
        delivery.status = Delivery.Status.FAILED
        return
    wait = timedelta(minutes=RETRIES[delivery.attempts - 1])
    delivery.due_at = timezone.now() + wait
    emails.after_commit(enqueue, delivery.pk, delivery.due_at)


def requeue_stale(now):
    """Enqueue deliveries still queued long after their time.

    Return how many. Each one's time moves to now, so it is
    not enqueued again for another STALE.
    """
    stale = Delivery.objects.filter(
        status=Delivery.Status.QUEUED, due_at__lt=now - STALE,
    )
    count = 0
    for delivery_id in stale.values_list('pk', flat=True):
        with transaction.atomic():
            Delivery.objects.filter(pk=delivery_id).update(
                due_at=now)
            emails.after_commit(enqueue, delivery_id)
        count += 1
    return count

Read it in the order an email lives:

  • queue() writes the row with get_or_create() on the key, so a second call for the same email finds the first and enqueues nothing. It schedules the enqueue with Chapter 43’s after_commit(): the task is enqueued only once the row is committed.
  • @task turns send_delivery() into a task. Its only argument is the row’s id: a task’s arguments are stored, so they must be simple values, and the row is read fresh when the task runs.
  • send_delivery() locks the row with select_for_update(of=('self',)), locking only the delivery, not the member and event it reads with it. Everything after the lock, the checks, the send, and the new status, happens in one transaction: a second worker given the same id waits, then finds the row no longer queued.
  • retry() counts the failure and enqueues the next attempt with using(run_after=...). A backend that cannot defer, such as the immediate one, runs it at once.
  • requeue_stale() is the outbox’s recovery: deliveries still queued ten minutes past their time are enqueued again, and their time moves on, so the next run does not enqueue them a third time.

emails and tasks import each other. That works because each uses the other’s functions only when they run, by the module name, never by importing a function at the top.

Step 5: Emails become deliveries

In events/emails.py, the docstring becomes:

"""Otahque's emails to members (Chapters 43 and 44).

One function per message. Each queues one email to each
member, so nobody sees another member's address. Since
Chapter 44 the functions are called inside the change's
transaction: they write Delivery rows, and a task sends
each one after commit (events/tasks.py).
"""

add from . import tasks below the Django imports, and replace everything from place_confirmed() to the end with:

def place_confirmed(registration):
    """Queue the email that tells a member they have a place."""
    event = registration.event
    tasks.queue(
        registration.member, event, 'confirmed', registration.pk,
        f'You have a place: {event}', [
            f'You have a place at {event}, {when(event)}, '
            f'at {event.location}.',
            'If you cannot come, cancel your place on the '
            'event page, so someone else can have it.',
        ])


def place_cancelled(registration):
    """Queue the email that confirms a cancelled place."""
    event = registration.event
    tasks.queue(
        registration.member, event, 'cancelled', registration.pk,
        f'Place cancelled: {event}', [
            f'Your place at {event} is cancelled.',
            'If that was a mistake, register again while '
            'places are left.',
        ])


def event_changed(event, fields):
    """Queue an email to every holder: the time or place moved.

    Each saved version of the event is its own email, so a
    second change is told too.
    """
    lines = [
        f'{event} has changed. It now starts {when(event)}, '
        f'at {event.location}.',
        'Your place is kept. If you can no longer come, '
        'cancel it on the event page.',
    ]
    for member in event.holders():
        tasks.queue(member, event, 'changed',
                    f'{event.pk}v{event.version}',
                    f'Changed: {event}', lines, needs='place')


def event_cancelled(event):
    """Queue an email to every holder: the event is off."""
    lines = [f'{event}, on {when(event)}, is cancelled. '
             'The organizers are sorry.']
    for member in event.holders():
        tasks.queue(member, event, 'event_cancelled', event.pk,
                    f'Cancelled: {event}', lines)


def announced(announcement):
    """Queue an announcement for each holder who wants them."""
    event = announcement.event
    lines = announcement.body.splitlines() + [
        f'From the organizers of {event}. You can stop '
        'announcements on your profile page.',
    ]
    for member in event.announcement_recipients():
        tasks.queue(member, event, 'announcement',
                    announcement.pk,
                    f'From the organizers: {event}', lines,
                    needs='place', announcement=announcement)


# How each reminder speaks of the time left (Chapter 44).
LEFT = {168: 'in a week', 24: 'tomorrow', 2: 'in two hours'}


def reminder(event, member, hours):
    """Queue a reminder; return (delivery, whether new).

    Its key has no time in it, so moving the event does not
    send a reminder twice.
    """
    return tasks.queue(
        member, event, 'reminder', f'{event.pk}h{hours}',
        f'Reminder: {event} is {LEFT[hours]}', [
            f'{event} starts {when(event)}, at '
            f'{event.location}.',
            'If you cannot come, cancel your place, so '
            'someone else can have it.',
        ], needs='place')

Each function now queues rather than sends, and a sixth, reminder(), is ready for Step 10. Each has a key: the registration for a place, the event and its version for a change, so that a second change is told too, the event for a cancellation, and the announcement. The callers change accordingly: the functions are now called inside the change’s transaction, not after it. In registrations/views.py, remove from events.emails import after_commit, and call emails.place_confirmed(place) and emails.place_cancelled(registration) directly. In events/views.py, remove the same import; in event_cancel() and event_announcements(), call emails.event_cancelled(event) and emails.announced(sent) directly; and in save_edit():

        # Chapter 43: tell members holding places if the time
        # or the place changed; since Chapter 44, queued in
        # this transaction and sent by a task after commit.
        told = [name for name in changed if name in emails.TOLD]
        if told and event.status == Event.Status.PUBLISHED:
            emails.event_changed(event, told)

Now run the events app’s tests, which include Chapter 43’s email tests:

uv run python manage.py test events
Found 263 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancelled_place_is_confirmed
ValueError: not enough values to unpack (expected 1, got 0)
ERROR: test_a_new_place_is_confirmed
ValueError: not enough values to unpack (expected 1, got 0)
ERROR: test_each_wanting_holder_gets_one_copy
ValueError: not enough values to unpack (expected 1, got 0)
... (6 more like these)
Ran 263 tests in ...s

FAILED (failures=4, errors=5)

Every test that reads mail.outbox finds it empty, and they are right to: the emails are queued in the database backend, and no worker runs during tests. Those tests are about what an email says, not about the queue, so they should run each task as soon as it is enqueued. Django’s immediate backend does exactly that. At the end of config/helpers.py:

# Chapter 44: tests that check what an email says run each
# task as soon as it is enqueued, instead of queueing it.
RUN_TASKS_NOW = {'default': {
    'BACKEND': (
        'django.tasks.backends.immediate.ImmediateBackend'
    ),
}}

and in each of the four modules, import RUN_TASKS_NOW from config.helpers, add override_settings to the import from django.test, and put above the test class:

# Chapter 44: emails are sent by tasks; run them at once.
@override_settings(TASKS=RUN_TASKS_NOW)

One test, test_names_are_escaped_in_html, called place_confirmed() and read the outbox straight away; now it wraps the call in captureOnCommitCallbacks(execute=True), so the enqueue happens. These are declared changes to Chapter 43’s tests.

uv run python manage.py test events
Found 263 test(s).
Creating test database for alias 'default'...
...
Ran 263 tests in ...s

OK

Step 6: Test the queue

The tests of the queue itself use Django’s dummy backend, which keeps what is enqueued and runs nothing, in events/tests/test_tasks.py:

"""Emails as deliveries, sent by a task (Chapter 44)."""
from datetime import timedelta

from django.core import mail
from django.db import transaction
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone

from events.emails import place_confirmed, reminder
from events.models import Delivery
from events.tasks import RETRIES, requeue_stale, send_delivery
from events.tests.test_email_failures import BROKEN
from registrations.tests.test_registrations import (
    soon, verified,
)

# The dummy backend keeps what is enqueued, and runs nothing.
QUEUE_ONLY = {'default': {
    'BACKEND': 'django.tasks.backends.dummy.DummyBackend',
}}


def enqueued():
    """Return the tasks the dummy backend was given."""
    return send_delivery.get_backend().results


@override_settings(TASKS=QUEUE_ONLY)
class QueueTests(TestCase):
    """A change writes a delivery; the request sends nothing."""

    @classmethod
    def setUpTestData(cls):
        cls.sai = verified('sai@example.org')
        cls.event = soon()

    def setUp(self):
        self.client.force_login(self.sai)
        enqueued().clear()

    def test_registering_queues_and_sends_nothing(self):
        with self.captureOnCommitCallbacks(execute=True):
            self.client.post(reverse('registrations:register',
                                     args=[self.event.pk]))
        delivery = Delivery.objects.get()
        self.assertEqual(delivery.status, 'queued')
        place = self.event.registrations.get()
        self.assertEqual(delivery.key,
                         f'confirmed:{place.pk}:{self.sai.pk}')
        self.assertEqual([r.args for r in enqueued()],
                         [[delivery.pk]])
        self.assertEqual(mail.outbox, [])

    def test_a_rolled_back_change_queues_nothing(self):
        with self.captureOnCommitCallbacks(execute=True):
            with transaction.atomic():
                place = self.event.register(self.sai,
                                            timezone.now())
                place_confirmed(place)
                transaction.set_rollback(True)
        self.assertFalse(Delivery.objects.exists())
        self.assertEqual(enqueued(), [])


@override_settings(TASKS=QUEUE_ONLY)
class SendTests(TestCase):
    """The task sends a delivery once, or retries it."""

    @classmethod
    def setUpTestData(cls):
        cls.sai = verified('sai@example.org')
        cls.event = soon()
        cls.place = cls.event.register(cls.sai, timezone.now())

    def setUp(self):
        enqueued().clear()
        self.delivery, _ = reminder(self.event, self.sai, 24)

    def test_running_twice_sends_once(self):
        send_delivery.call(self.delivery.pk)
        send_delivery.call(self.delivery.pk)
        self.assertEqual(len(mail.outbox), 1)
        self.delivery.refresh_from_db()
        self.assertEqual(self.delivery.status, 'sent')

    def test_a_cancelled_place_is_not_reminded(self):
        self.place.cancel(timezone.now())
        self.assertEqual(send_delivery.call(self.delivery.pk),
                         'skipped')
        self.assertEqual(mail.outbox, [])

    @override_settings(MAILERS=BROKEN)
    def test_a_failure_is_retried_then_given_up(self):
        with self.assertLogs('otahque.email', 'ERROR'):
            with self.captureOnCommitCallbacks(execute=True):
                send_delivery.call(self.delivery.pk)
        self.delivery.refresh_from_db()
        self.assertEqual(self.delivery.status, 'queued')
        self.assertEqual(self.delivery.attempts, 1)
        wait = enqueued()[-1].task.run_after - timezone.now()
        self.assertAlmostEqual(wait.total_seconds(), 60, delta=5)
        with self.assertLogs('otahque.email', 'ERROR'):
            for _ in RETRIES:
                send_delivery.call(self.delivery.pk)
        self.delivery.refresh_from_db()
        self.assertEqual(self.delivery.status, 'failed')
        self.assertEqual(self.delivery.attempts, 4)


@override_settings(TASKS=QUEUE_ONLY)
class StaleTests(TestCase):
    """A delivery whose task was lost is enqueued again."""

    def test_an_old_queued_delivery_is_enqueued_again(self):
        sai = verified('sai@example.org')
        event = soon()
        delivery, _ = reminder(event, sai, 24)
        enqueued().clear()
        Delivery.objects.update(
            due_at=timezone.now() - timedelta(minutes=20))
        with self.captureOnCommitCallbacks(execute=True):
            self.assertEqual(requeue_stale(timezone.now()), 1)
        self.assertEqual([r.args for r in enqueued()],
                         [[delivery.pk]])
        self.assertEqual(requeue_stale(timezone.now()), 0)
uv run python manage.py test events.tests.test_tasks
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK

send_delivery.call() runs the task function directly, as a worker would. Running it twice sends once; a cancelled place is skipped; a refused email is retried after a minute, and after the fourth failure it is failed, with four errors in the log. Figure 44.3 shows what the record prevents.

Two groups. Left, in red, without a delivery record: the task sends Sai’s email, the provider accepts it; the worker dies before it reports, the queue still holds the task; the task runs again, Sai gets the email twice. Right, in green, with Delivery: one row per email, unique key, queuing it twice finds the first; the task locks the row and sends only if queued; marked sent in the same transaction, a rerun finds sent, and stops.
Figure 44.3 — Why a retry can send twice, and how Delivery stops it.

Step 7: The real worker, in a test

The dummy backend proves Otahque’s logic. One test must prove the real backend and worker, on Otahque’s Django: this is the evidence for pinning a package that does not declare Django 6.1. In events/tests/test_worker.py:

"""The database queue and its worker (Chapter 44).

django-tasks-db 0.13.0 declares Django 5.2 and 6.0 only;
Otahque pins it on 6.1 (N44.6), and this test is the
evidence that it works: a queued email, the real worker,
one message out. It is a TransactionTestCase because the
worker takes its own transactions, as it does in use.
"""
import io

from django.core import mail
from django.core.management import call_command
from django.test import TransactionTestCase
from django.utils import timezone

from events.emails import place_confirmed
from events.models import Delivery
from registrations.tests.test_registrations import (
    soon, verified,
)


class WorkerTests(TransactionTestCase):
    """db_worker --batch runs what is queued, then stops."""

    # Put back the rows migrations made, such as the groups,
    # for the tests that run after this one (Chapter 41).
    serialized_rollback = True

    def test_the_worker_sends_a_queued_email(self):
        sai = verified('sai@example.org')
        event = soon()
        place = event.register(sai, timezone.now())
        place_confirmed(place)
        self.assertEqual(mail.outbox, [])
        call_command('db_worker', '--batch',
                     '--no-startup-delay',
                     stdout=io.StringIO(), stderr=io.StringIO())
        [email] = mail.outbox
        self.assertEqual(email.to, ['sai@example.org'])
        self.assertEqual(Delivery.objects.get().status, 'sent')
uv run python manage.py test events.tests.test_worker
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Step 8: The worker down, then back

Stop nothing yet; just do not start a worker. Queue one email in your own database with a practice file, queue_it.py, run in the Django shell and then deleted:

from events.emails import place_confirmed
from events.models import Delivery
from registrations.models import Registration

place = Registration.objects.filter(
    status='active',
).select_related('event', 'member').order_by('pk').first()
place_confirmed(place)
print('queued:', Delivery.objects.filter(
    status='queued').count())
uv run manage.py shell -v 0 -c "exec(open('queue_it.py').read())"
queued: 1

The member’s page answered at once; Mailpit has nothing new. Now start the worker, as you would after a restart:

uv run python manage.py db_worker --batch --no-startup-delay
Warning: --reload and --batch cannot be specified together.
    Disabling autoreload.
Starting worker worker_id=... queues=default
Task id=... path=events.tasks.send_delivery state=RUNNING
Task id=... path=events.tasks.send_delivery state=SUCCESSFUL
No more tasks to run for worker_id=... - exiting gracefully.

The email is in Mailpit. Nothing was lost while the worker was down: the task waited in its table. From here on, keep uv run python manage.py db_worker running in a third terminal while you use the site.

Step 9: Reminders that organizers choose

In events/models.py, below GALLERY_FULL:

# Reminders an organizer may choose, in hours before the
# start (Chapter 44); new events have one, a day before.
REMINDER_CHOICES = [(168, '7 days before'),
                    (24, '24 hours before'),
                    (2, '2 hours before')]


def default_reminders():
    """Return the reminders a new event starts with."""
    return [24]

and in Event, above the cover:

    # Chapter 44: hours before the start when holders are
    # reminded, from REMINDER_CHOICES.
    reminders = models.JSONField(default=default_reminders,
                                 blank=True)

The default is a function, not [24]: a list written in the field would be one list shared by every event. A JSONField holds the chosen hours as a list. In events/forms.py, add REMINDER_CHOICES to the import from .models, add 'reminders' to EventForm.Meta.fields, and in EventForm, below timezone:

    # Chapter 44: when members holding places are reminded.
    reminders = forms.TypedMultipleChoiceField(
        choices=REMINDER_CHOICES, coerce=int, required=False,
        widget=forms.CheckboxSelectMultiple,
        label='Remind members holding places',
        help_text='By email. A reminder whose time has passed '
                  'when someone registers is not sent.',
    )

TypedMultipleChoiceField turns the ticked boxes into a list of numbers. In events/templates/events/event_fields.html, below {{ form.asks_website.as_field_group }}, add {{ form.reminders.as_field_group }}.

uv run python manage.py makemigrations -n reminders events
uv run python manage.py migrate
Migrations for 'events':
  events\migrations\0013_reminders.py
    + Add field reminders to event
Operations to perform:
  Apply all migrations: account, accounts, admin, audit,
    auth, contenttypes, django_tasks_database, events, mfa,
    registrations, sessions, socialaccount
Running migrations:
  Applying events.0013_reminders... OK

Existing events get the default, a reminder 24 hours before. An earlier test counts the event form’s fields:

uv run python manage.py test events.tests.test_events
Found 189 test(s).
Creating test database for alias 'default'...
FAIL: test_fields_use_otahque_styles_and_script
AssertionError: 15 != 14 : Found 15 instances of
    'class="fieldset"' (expected 14) in the following
    response
Ran 189 tests in ...s

FAILED (failures=1)

The count is the test’s point, so it changes on purpose, in test_fields_use_otahque_styles_and_script:

        # Chapter 44: the reminders field makes 15.
        for text, count in (('class="fieldset"', 15),
uv run python manage.py test events.tests.test_events
Found 189 test(s).
Creating test database for alias 'default'...
...
Ran 189 tests in ...s

OK

Step 10: send_due_reminders

emails.reminder(), from Step 5, words the email; its key has no time in it, so a moved event is not reminded twice. The command, events/management/commands/send_due_reminders.py:

"""Queue the reminders that are due, and stale deliveries.

Run every ten minutes by the operating system's scheduler
(Chapter 44): Task Scheduler on Windows, cron or a systemd
timer elsewhere. It only queues; db_worker sends.
"""
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

from events import emails
from events.models import Event
from events.tasks import requeue_stale

# The earliest reminder: 7 days before the start.
FURTHEST = timedelta(hours=168)


def due_reminders(now):
    """Queue each reminder whose time has come; return how many.

    A reminder is due once now is past its time. It goes to
    each member who held their place before that time;
    someone who registers later already knows the date. A
    reminder already queued is not queued again.
    """
    count = 0
    events = Event.objects.filter(
        status=Event.Status.PUBLISHED,
        starts_at__gt=now, starts_at__lte=now + FURTHEST,
    )
    for event in events:
        for hours in event.reminders:
            due = event.starts_at - timedelta(hours=hours)
            if due > now:
                continue
            places = event.registrations.filter(
                status='active', registered_at__lt=due,
            ).select_related('member')
            with transaction.atomic():
                for place in places:
                    _, new = emails.reminder(event, place.member,
                                             hours)
                    count += new
    return count


class Command(BaseCommand):
    """Queue due reminders; enqueue stale deliveries again."""

    help = 'Queue the reminders that are due.'

    def handle(self, *args, **options):
        """Queue, then report both counts."""
        now = timezone.now()
        queued = due_reminders(now)
        again = requeue_stale(now)
        self.stdout.write(f'Queued {queued} reminders; '
                          f'enqueued {again} stale deliveries '
                          'again.')

It only queues. A reminder goes to members who held their place before the reminder’s time, so someone who registers an hour before the start gets the confirmation, not a reminder too. The tests, in events/tests/test_reminders.py:

"""Reminders chosen by organizers (Chapter 44)."""
import io
from datetime import timedelta

from django.core.management import call_command
from django.test import TestCase, override_settings
from django.utils import timezone

from events.models import Delivery
from events.tests.test_tasks import QUEUE_ONLY
from registrations.models import Registration
from registrations.tests.test_registrations import (
    soon, verified,
)


def reminders_now():
    """Run send_due_reminders; return what it printed."""
    out = io.StringIO()
    call_command('send_due_reminders', stdout=out)
    return out.getvalue().strip()


@override_settings(TASKS=QUEUE_ONLY)
class ReminderTests(TestCase):
    """A reminder is queued once, when it is due."""

    @classmethod
    def setUpTestData(cls):
        start = timezone.now() + timedelta(hours=20)
        cls.event = soon(starts_at=start,
                         ends_at=start + timedelta(hours=2),
                         registration_closes_at=start,
                         cancellation_deadline=start)
        cls.sai = verified('sai@example.org')
        cls.raj = verified('raj@example.org')
        now = timezone.now()
        for member in (cls.sai, cls.raj):
            cls.event.register(member, now)
        # Sai registered two days ago; Raj only just now,
        # after the 24-hour reminder's time had passed.
        Registration.objects.filter(member=cls.sai).update(
            registered_at=now - timedelta(days=2))

    def test_the_due_reminder_is_queued_once(self):
        self.assertEqual(reminders_now(),
                         'Queued 1 reminders; enqueued 0 stale '
                         'deliveries again.')
        delivery = Delivery.objects.get()
        self.assertEqual(delivery.member, self.sai)
        self.assertEqual(delivery.subject,
                         'Reminder: Django clinic is tomorrow')
        self.assertTrue(reminders_now().startswith('Queued 0'))

    def test_no_reminders_chosen_sends_none(self):
        self.event.reminders = []
        self.event.save()
        reminders_now()
        self.assertFalse(Delivery.objects.exists())

    def test_a_reminder_not_yet_due_waits(self):
        self.event.reminders = [2]
        self.event.save()
        reminders_now()
        self.assertFalse(Delivery.objects.exists())

    def test_a_moved_event_is_not_reminded_twice(self):
        reminders_now()
        self.event.starts_at += timedelta(hours=1)
        self.event.ends_at += timedelta(hours=1)
        self.event.save()
        reminders_now()
        self.assertEqual(Delivery.objects.count(), 1)


class ReminderFormTests(TestCase):
    """New events start with a reminder a day before."""

    def test_the_default(self):
        self.assertEqual(soon().reminders, [24])
uv run python manage.py test events.tests.test_reminders
uv run python manage.py send_due_reminders
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK
Queued 0 reminders; enqueued 0 stale deliveries again.

Step 11: Every ten minutes, on Windows

The command must run without you. On Windows, Task Scheduler does it; in PowerShell, in the folder that holds manage.py, once:

$run = "Set-Location '$PWD'; uv run python " +
       "manage.py send_due_reminders"
schtasks /Create /TN "Otahque reminders" /SC MINUTE `
  /MO 10 /TR "powershell -NoProfile -Command $run"

/SC MINUTE /MO 10 means every ten minutes; $PWD puts your project folder into the command. Task Scheduler’s library shows “Otahque reminders” with its next run time and last result. Remove it with schtasks /Delete /TN "Otahque reminders" when you stop working on Otahque, or the command keeps running on your laptop.

Step 12: Every ten minutes, with cron or systemd

On macOS and Linux, cron runs commands on a timetable. Run crontab -e and add one line, with your own folder:

*/10 * * * * cd ~/otahque && uv run manage.py send_due_reminders

*/10 in the first column means every ten minutes; uv run manage.py runs the file with the project’s Python. Many Linux systems prefer systemd timers, which log each run and catch up after the computer was asleep (Persistent=true). Two files in ~/.config/systemd/user/:

[Service]
Type=oneshot
WorkingDirectory=%h/otahque
ExecStart=/usr/bin/env uv run manage.py send_due_reminders
[Timer]
OnCalendar=*:0/10
Persistent=true

[Install]
WantedBy=timers.target

then systemctl --user enable --now otahque-reminders.timer, and systemctl --user list-timers shows the next run. The runbook in Step 14 keeps all three. Chapter 62 runs the worker and the scheduler on a server.

Step 13: What happened to an announcement

Organizers see what became of their emails. In events/views.py, above event_announcements():

def with_counts(announcements):
    """Add how many of each one's emails are in each state.

    "Sent" means a mail server accepted it, not that the
    member received it (Chapter 43).
    """
    def count(status):
        return models.Count('deliveries', filter=models.Q(
            deliveries__status=status))
    return announcements.annotate(
        sent=count('sent'), queued=count('queued'),
        failed=count('failed'),
    )

and in event_announcements(), pass with_counts(event.announcements) as announcements. In events/templates/events/announcements.html, below each announcement’s text:

          {# Chapter 44: what became of its emails. #}
          <p class="delivery-badges">
            <span class="badge badge-success">
              {{ item.sent }} sent</span>
            <span class="badge badge-ghost">
              {{ item.queued }} queued</span>
            {% if item.failed %}
              <span class="badge badge-error">
                {{ item.failed }} failed</span>
            {% endif %}
          </p>

The styles, which also space the reminder boxes, in static/otahque/source.css, above .form-actions:

  /* Delivery counts and reminder choices (Chapter 44). */
  .delivery-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  #id_reminders {
    display: grid;
    gap: 0.5rem;
  }
  #id_reminders label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
npm run build

A test, at the end of AnnouncementTests in events/tests/test_announcements.py:

    def test_the_list_counts_deliveries(self):
        self.send()
        reply = self.client.get(page(self.event))
        self.assertContains(reply, '1 sent')
        self.assertContains(reply, '0 queued')
        self.assertNotContains(reply, 'failed</span>')
uv run python manage.py test events.tests.test_announcements
Found 8 test(s).
Creating test database for alias 'default'...
...
Ran 8 tests in ...s

OK

The result is in Figure 44.4.

Two screenshots. Left, the announcements page for Sample clinic at 390 pixels: the notice, the message form, and under Sent, the announcement We meet in Room 2 this week, with three badges, 1 sent in green, 0 queued in grey, 1 failed in red. Right, part of the edit page at 1280 pixels: Remind members holding places, with the help text and three checkboxes, 7 days before, 24 hours before ticked, and 2 hours before.
Figure 44.4 — Delivery counts, and the reminder choices.

Step 14: Records

The decision, docs/adr/ADR-007-background-work.md:

# ADR-007: Background work with Django's task interface

## Status

Proposed, November 2026 (Chapter 44). The choices follow
the user's decisions of 25 November 2026 (D44.1-D44.5,
N44.6-N44.9); this record is not yet reviewed or accepted.

## Context

Since Chapter 43 Otahque sends five kinds of email in the
request, after commit. A slow mail server slows the page;
a failure is logged and lost; an announcement to many
members holds one request for all of them. Members also
want reminders, which no request triggers. Django 6.1 has
a task interface (@task, enqueue) but ships only the
immediate and dummy backends, with no worker, no retries,
and no enqueue after commit.

## Options

- A: Django's task interface with django-tasks-db, which
  keeps the queue in PostgreSQL, and its db_worker.
- B: Celery with Redis: mature, but a broker to install
  and run on every reader's computer, and its own API.
- C: cron only: no queue; every email still sent in the
  request.

## Decision

A, pinned at django-tasks-db==0.13.0. It declares Django
5.2 and 6.0 only; a test runs its worker on Otahque's
Django 6.1 (events/tests/test_worker.py). Revisit at the
Django 6.2 upgrade, or at the package's next release.

- Each email is a Delivery row with a unique key, written
  in the change's transaction; a task sends it after
  commit. A command run every ten minutes enqueues any
  delivery still queued ten minutes past its time (an
  outbox: no email lost, whatever the backend).
- The task locks the row while sending: at most one send.
- Three retries, after 1, 5, and 25 minutes; then failed.
- Reminders: organizers choose 7 days, 24 hours, and 2
  hours before; send_due_reminders queues them.
- Scheduling: Windows Task Scheduler, cron, or a systemd
  timer runs send_due_reminders. Celery and Beat are
  compared; a runnable Celery lab follows Chapter 62.

## Consequences

- Two processes besides the web server: db_worker, and
  the scheduler's command. Chapter 62 runs both in
  containers; Chapter 65 watches queue depth and failures.
- "Sent" means a mail server accepted the email.
- Task rows accumulate; prune_db_task_results removes old
  ones (Chapter 65 sets how long they are kept).

The runbook, docs/runbooks/scheduling.md:

# Runbook: the worker and the scheduled command

Chapter 44. Two things run beside the web server.

## The worker

    uv run python manage.py db_worker

Runs queued tasks until stopped (Ctrl+C). With DEBUG on it
reloads when code changes; with DEBUG off, restart it
after every deployment, or it runs the old code.

    uv run python manage.py db_worker --batch

Runs everything due now, then stops: for checks.

## The scheduled command, every ten minutes

    uv run python manage.py send_due_reminders

Queues reminders that are due, and enqueues deliveries
stuck in the queue. Run it from the folder with manage.py.

Windows (Task Scheduler), once, in PowerShell:

    $run = "Set-Location '$PWD'; uv run python " +
           "manage.py send_due_reminders"
    schtasks /Create /TN "Otahque reminders" /SC MINUTE `
      /MO 10 /TR "powershell -NoProfile -Command $run"

Remove it with schtasks /Delete /TN "Otahque reminders".

cron (macOS, Linux), with crontab -e; one line, with the
folder that holds manage.py (uv run runs a .py file with
the project's Python):

*/10 * * * * cd ~/otahque && uv run manage.py send_due_reminders


systemd (Linux): two files in ~/.config/systemd/user/,
then systemctl --user enable --now otahque-reminders.timer

# otahque-reminders.service [Service] Type=oneshot WorkingDirectory=%h/otahque ExecStart=/usr/bin/env uv run manage.py send_due_reminders

# otahque-reminders.timer [Timer] OnCalendar=*:0/10 Persistent=true

[Install] WantedBy=timers.target


## When something is wrong

- Emails stay queued: is db_worker running?
- Reminders never queue: is the scheduled task running?
  Run send_due_reminders by hand and read its counts.
- Failed deliveries: the log has each failure, with the
  member's id; the announcements page shows the counts.

In docs/design/email.md, the failure rule becomes:

- A failed send is logged with the member's id, not their
  address, and undoes nothing. Since Chapter 44 it is
  retried after 1, 5, and 25 minutes, then marked failed.

and above “Not yet”, where the retries line is removed:

## Deliveries and reminders (Chapter 44)

- Each email is a Delivery: one member, a unique key, its
  words fixed when queued, and a status (queued, sent,
  failed, or skipped when no longer wanted). See
  docs/adr/ADR-007-background-work.md.
- Reminders, chosen per event: 7 days, 24 hours, 2 hours
  before; new events have 24 hours. Only members who held
  their place before a reminder's time get it, once.

Step 15: Celery and Beat, compared

Most Django projects you will meet run background work with Celery, and its scheduler, Celery Beat. Table 44.2 compares it with what Otahque now has. Celery is the better tool for many workers, high volume, task routing, and rich monitoring; it costs a message broker, usually Redis or RabbitMQ, to install, run, and watch, and its own API. For one community’s emails, the database queue is enough, and PostgreSQL is already there. A runnable Celery lab follows Chapter 62, when Redis is part of the deployment (D44.5).

Table 44.2 — Django tasks with django-tasks-db, and Celery
Question Otahque now Celery and Beat
Interface Django's @task and enqueue() Celery's own @shared_task and delay()
Queue A PostgreSQL table A broker: Redis or RabbitMQ
Worker manage.py db_worker celery worker
Schedule The OS scheduler runs a command Celery Beat, a process of its own
Retries Otahque's code, with Delivery Built in, per task
Enqueue after commit after_commit() and the outbox on_commit(), or a library
When to move Many workers, high volume, routing Already right for those

The Delivery row would stay with Celery too: it records what was sent, which no queue does.

Step 16: Check and commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 541 test(s).
System check identified no issues (0 silenced).
Ran 541 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Send emails from a worker; add reminders"
M  config/helpers.py
M  config/settings.py
A  docs/adr/ADR-007-background-work.md
M  docs/design/email.md
A  docs/runbooks/scheduling.md
M  events/emails.py
M  events/forms.py
A  events/management/commands/send_due_reminders.py
A  events/migrations/0012_deliveries.py
A  events/migrations/0013_reminders.py
M  events/models.py
A  events/tasks.py
M  events/templates/events/announcements.html
M  events/templates/events/event_fields.html
M  events/tests/test_announcements.py
M  events/tests/test_email_failures.py
M  events/tests/test_emails.py
M  events/tests/test_event_emails.py
M  events/tests/test_events.py
A  events/tests/test_reminders.py
A  events/tests/test_tasks.py
A  events/tests/test_worker.py
M  events/views.py
M  pyproject.toml
M  registrations/views.py
M  static/otahque/site.css
M  static/otahque/source.css
M  uv.lock
[main 1a2b3c4] Send emails from a worker; add reminders
 28 files changed, 927 insertions(+), 48 deletions(-)
 create mode 100644 docs/adr/ADR-007-background-work.md
 create mode 100644 docs/runbooks/scheduling.md
 create mode 100644
    events/management/commands/send_due_reminders.py
 create mode 100644 events/migrations/0012_deliveries.py
 create mode 100644 events/migrations/0013_reminders.py
 create mode 100644 events/tasks.py
 create mode 100644 events/tests/test_reminders.py
 create mode 100644 events/tests/test_tasks.py
 create mode 100644 events/tests/test_worker.py

If something goes wrong

Table 44.3 — Recovery for Chapter 44
What you see Likely cause What to do
Emails stay queued No worker is running Start uv run python manage.py db_worker
relation django_tasks_database_dbtaskresult does not exist The package's migration has not run uv run python manage.py migrate
A test finds mail.outbox empty Tasks are queued, not run, in tests Add @override_settings(TASKS=RUN_TASKS_NOW)
The worker runs old code DEBUG is off, so it does not reload Restart it after every change
Reminders never arrive The scheduled task is not running, or no reminder is ticked Run send_due_reminders by hand; check the event's choices
The same email twice Something sends without a Delivery Send only through queue() and send_delivery()
PAGE 003

Verify Your Work

Work through Table 44.4 from the folder that holds manage.py, with Mailpit running.

Table 44.4 — Verification checklist for Chapter 44
Check Command or action Expected result
Starting point test --parallel Found 528 test(s); OK
The queue uv add django-tasks-db==0.13.0; migrate; db_worker --batch The package; its table; No more tasks to run
Delivery makemigrations, then migrate events 0012 applied
Emails as deliveries test events Red; then OK after the declared change
The queue's tests test events.tests.test_tasks Found 6 test(s); OK
The real worker test events.tests.test_worker Found 1 test(s); OK
Worker down, then back queue_it.py; db_worker --batch queued: 1; nothing in Mailpit; then the email arrives
Reminders migrate; test events.tests.test_events; test events.tests.test_reminders; send_due_reminders events 0013; red once, changed on purpose; 5 tests OK; Queued ...
Counts test events.tests.test_announcements Found 8 test(s); OK
UI Announcements page and edit page at 390 and 1280 px Badges; three reminder boxes; no sideways scroll
All checks uv run python check.py == all checks passed; Ran 541 tests
Commit git log --oneline -1 Send emails from a worker; add reminders
Not verified Task Scheduler, cron, and systemd timers; macOS and Linux shells Creating a scheduled task changes the computer, so the steps were reviewed, not run

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 43 checkpoint with a reader’s data, against PostgreSQL 18, with Mailpit running; commands that write files ran once. The project folder is shortened to ..., and the worker’s random ids to id=..., in printed output. The screenshots were taken in Microsoft Edge, with one sample event, two places, one announcement, and its deliveries added for the screenshots only and deleted afterwards.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 What are the task interface, the backend, the worker, and the scheduler, in Otahque?

Flip to check your answerFold answer back

Answer. The interface is Django’s @task and enqueue(). The backend is django-tasks-db, a table in PostgreSQL. The worker is manage.py db_worker, a second process that runs queued tasks. The scheduler is the operating system’s, running send_due_reminders every ten minutes.

Que. 2 Why does the task take a delivery’s id, not the delivery itself?

Flip to check your answerFold answer back

Answer. A task’s arguments are stored until a worker runs it, so they must be simple values. The id also makes the task read the row fresh, as it is when the task runs, not as it was when it was enqueued.

Que. 3 A worker sends Sai’s email and dies before it records success. What stops a second send?

Flip to check your answerFold answer back

Answer. The Delivery row. The task locks it and marks it “sent” in the same transaction as the send. If the worker dies before the commit, the row is still “queued” and the email may go again, at most once more; once the commit happens, any rerun finds “sent” and stops. The unique key stops the same email from being queued twice at all.

Que. 4 What happens to a delivery whose task was never enqueued, because the process died just after the commit?

Flip to check your answerFold answer back

Answer. It stays “queued”. send_due_reminders runs every ten minutes and enqueues any delivery still queued ten minutes past its time: the row is the outbox.

Que. 5 Why are reminders queued by a scheduled command, not by a task enqueued at registration with run_after?

Flip to check your answerFold answer back

Answer. A task enqueued for a fixed time would not follow a moved event or a cancelled place, and a long wait in the queue is fragile. The command looks at the events as they are now, every ten minutes, and the key makes queuing idempotent.

Mini-Challenge

An organizer ticks both 7 days and 24 hours. Write a test, in events/tests/test_week.py, that when both times have passed, Sai, if she registered ten days before the start, gets both reminders queued, and they are two different deliveries. In ReminderTests she registered two days before, after the week’s reminder time, so she would rightly get only one.

Hint: inherit from ReminderTests to reuse its event and members, and read each delivery’s key.

Model answer:

"""The week's reminder (Chapter 44 challenge)."""
from datetime import timedelta

from django.test import override_settings
from django.utils import timezone

from events.models import Delivery
from events.tests import test_reminders
from events.tests.test_reminders import reminders_now
from registrations.models import Registration


# Through the module: a class imported by name would be
# collected and run here too.
@override_settings(TASKS={'default': {
    'BACKEND': 'django.tasks.backends.dummy.DummyBackend'}})
class WeekTests(test_reminders.ReminderTests):
    """With 7 days chosen, Sai gets both due reminders."""

    def test_both_due_reminders_are_queued(self):
        self.event.reminders = [168, 24]
        self.event.save()
        # Before the week's reminder time, so both apply.
        Registration.objects.filter(member=self.sai).update(
            registered_at=timezone.now() - timedelta(days=10))
        reminders_now()
        self.assertEqual(
            sorted(d.key.split(':')[1] for d in
                   Delivery.objects.filter(member=self.sai)),
            [f'{self.event.pk}h168', f'{self.event.pk}h24'])
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK

Inheriting runs the parent’s four tests again, which is why five tests ran. The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A task interface, a backend, a worker, and a scheduler are four different things; Django 6.1 provides only the first.
  • A task takes simple arguments, such as an id, and reads the rest when it runs.
  • Write the record of the work in the change’s transaction, enqueue after commit, and enqueue again whatever is stuck: an outbox.
  • A unique key and a locked row make a retried task send at most once.
  • Retry with growing waits, a limit, and a final state; say “sent”, never “received”.
  • Scheduled work is a command the operating system runs: Task Scheduler, cron, or a systemd timer.
  • Tests choose a backend: immediate to see what a task does, dummy to see what was enqueued, the real one once to prove the worker.

Key terms

Use Table 44.5 to explain this chapter’s ideas in your own words.

Table 44.5 — Key terms from Chapter 44
Term Meaning
Task A function marked @task, run later by a worker.
Task backend Where enqueued tasks are kept; set in TASKS.
Worker A process that runs queued tasks.
run_after The earliest time a task may run.
Idempotent Safe to run twice: the second run changes nothing.
Outbox Work recorded in the same transaction as the change.
Backoff Waiting longer before each retry.
Scheduler Starts a command at set times: cron, Task Scheduler, systemd.
Celery A widely used task system with its own broker and API.
Delivery Otahque's record of one email to one member.

Readiness checkpoint: you are ready for Chapter 45 when uv run python check.py ends with “all checks passed” and 541 tests, registering answers at once and the confirmation reaches Mailpit through db_worker, an event’s reminder choices save, send_due_reminders reports its counts, and git log --oneline -1 shows this chapter’s commit.

Git Commit

Your Chapter 44 work was committed once, in Step 16, as “Send emails from a worker; add reminders”: the package and its settings, the Delivery model and both migrations, the tasks module, the emails changed to queue, the reminder choices and the command, the delivery counts, the tests and Chapter 43’s declared test changes, ADR-007, the runbook, and the design note. Scheduled tasks live in your operating system, not in Git. If you kept the Mini-Challenge, commit it on its own:

git add events/tests/test_week.py
git commit -m "Check both reminders for a long-planned event"
PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a production incident and to what “sent” can promise. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.

L1 (Junior): Why does sending email leave the request?

What the interviewer is testing: Do you know what belongs in a request?

Flip to check your answerFold answer back

Perfect answer: A request should do the member’s work and answer quickly. Sending an email means talking to another server, which can be slow, down, or refuse, and none of that should decide how long Sai waits or whether her registration page fails. So the request writes a record, “send this email”, and returns; a worker sends it, and tries again later if it fails. The same move lets Otahque do work nobody triggers, such as reminders.

A numbered flow of five cards. 1, a register button that spins. 2, the request waits for the mail server. 3, queue the work, return at once. 4, a worker does it, outside the request. 5, the page answers in milliseconds.
Figure 44.5 — Why work leaves the request.

Behind the scenes:

Chapter 43: save, commit, SMTP ... answer
Chapter 44: save + Delivery, commit, answer
            worker: SMTP

Code proof: the queue’s tests:

Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK

Common mistakes:

  • Moving the send into a task but enqueuing it inside the transaction.
  • Passing a model instance to a task instead of its id.

Follow-up the interviewer might ask:

  • What else would you move out of requests? (Re-encoding large uploads, imports, reports, webhooks.)
  • What should stay? (Anything the member must see the result of before the page answers.)

L2 (Mid-Level): Predict what queuing the same confirmation twice does

What the interviewer is testing: Can you reason about idempotence?

Flip to check your answerFold answer back

Perfect answer: The key is confirmed, the registration’s id, and the member’s id, the same both times. The first call creates the row and schedules one enqueue; the second finds the row with get_or_create() and does nothing, so there is one delivery, one task, and one email. If the second call came after the first was sent, it would still find the row, now “sent”, and still do nothing. That is idempotence: a repeated request, a retried view, or a double click cannot send twice.

A numbered flow of five cards. 1, a retry with no delivery record. 2, the first try had already sent. 3, the member gets it twice. 4, a unique key and a locked row. 5, running twice sends once.
Figure 44.6 — Retries without, and with, a record.

Behind the scenes:

first:  INSERT ... key='confirmed:41:7'  -> new
second: SELECT ... key='confirmed:41:7'  -> found

Code proof: two calls for one place, with the dummy backend:

rows added by two calls: 1

Common mistakes:

  • Making the key from the time, so every call is “new”.
  • Checking “already sent?” without a lock, so two workers both see “no”.

Follow-up the interviewer might ask:

  • What if two requests call it at the same moment? (The unique constraint lets one insert; the other’s get_or_create() retries the read and finds it.)
  • When should the same kind of email go twice? (When it is about something new: each saved version of an event, so the key includes the version.)

L3 (Senior): Defend the database worker over Celery for Otahque now

What the interviewer is testing: Can you choose infrastructure for the problem in front of you?

Flip to check your answerFold answer back

Perfect answer: Otahque’s background work is one community’s emails: a few thousand a day at most, with no need for routing, priorities across many queues, or many workers. PostgreSQL is already there and backed up; a queue in it adds one table and one process, and keeps the queue inside the same transactions as the data. Celery would add a broker to install, secure, and watch on every reader’s computer and every server, and its own task API. The price of my choice is an undeclared dependency, which a test of the real worker covers, and throughput that a database queue limits. I would revisit when volume or worker count grows, or at Chapter 62’s lab, with the Delivery design unchanged.

A numbered flow of five cards. 1, need: reliable email for one community. 2, PostgreSQL is already there. 3, Celery adds a broker to run. 4, database queue now; Celery lab after Chapter 62. 5, revisit at many workers or high volume.
Figure 44.7 — Choosing the database worker.

Behind the scenes:

Database queue: web, db_worker, scheduler
Celery:         web, celery worker, celery beat, Redis

Code proof: the real worker, on Otahque’s Django:

Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Common mistakes:

  • Choosing by popularity rather than by the work.
  • Forgetting that the scheduler and the worker are separate processes to deploy and watch.

Follow-up the interviewer might ask:

  • What would make you switch? (Sustained volume the table cannot handle, or work that needs routing and rate limits per queue.)
  • What would you keep? (The task functions’ bodies and Delivery.)

L4 (Staff): Members got emails about places that do not exist. Diagnose it

What the interviewer is testing: Can you trace a consistency bug across a transaction boundary?

Flip to check your answerFold answer back

Perfect answer: An email about a place that does not exist means something was sent, or enqueued, before the place’s transaction committed, and the transaction then rolled back. With a queue outside the database, such as a Redis broker, an enqueue inside the transaction escapes the rollback; the worker then reads a row that was never committed, or sends from stale data. I would look for any enqueue() or send not behind on_commit(), and for code that bypasses queue(). Otahque’s design makes this hard: the Delivery row and the change commit or roll back together, and the enqueue happens only after commit. The regression test rolls back a registration and checks that no delivery and no task exist.

A numbered flow of five cards. 1, emails for a place that was rolled back. 2, enqueued inside the transaction. 3, a broker outside the database kept it. 4, write the row; enqueue after commit. 5, a test rolls back and finds nothing.
Figure 44.8 — Diagnosing emails for a rolled-back place.

Behind the scenes:

atomic: save place, Delivery, on_commit(enqueue)
ROLLBACK -> no place, no Delivery, no task
COMMIT   -> enqueue(delivery_id)

Code proof: the rollback test:

Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

Common mistakes:

  • Fixing it with a delay (“wait two seconds before sending”), which only makes it rarer.
  • Trusting a database queue to roll back with the change, then moving to another backend.

Follow-up the interviewer might ask:

  • Could the task check that the place exists? (It does, for reminders and announcements; still_wanted(). For a confirmation, the row itself would be missing.)
  • What about the opposite, committed but never enqueued? (The outbox: requeue_stale().)

L5 (Lead): Defend “sent” not meaning “received”

What the interviewer is testing: Can you keep a product honest about what a system knows?

Flip to check your answerFold answer back

Perfect answer: Otahque knows one fact: a mail server accepted the message. After that, the provider may delay it, the member’s server may filter or reject it, and the member may never open it. Showing “received” or “delivered” would promise what Otahque cannot see, and organizers would act on it, for example assuming everyone knows about a room change. So the counts say “sent”, “queued”, and “failed”, and the design note says what each means. Providers can report bounces and complaints through webhooks; Chapter 52 receives webhooks, and Chapter 63 chooses a provider, which is when “bounced” could become a fourth word, backed by evidence.

Table 44.6 — What each word can promise
Word Otahque knows Otahque does not know
Queued The email is waiting When it will go
Sent A mail server accepted it That the member got it
Failed Four tries were refused Why, beyond the log
Skipped It was no longer wanted —

Behind the scenes:

send() returns -> "sent"
provider -> member's server -> inbox -> read: unknown

Code proof: this computer’s deliveries, by status:

queued 0
sent 1
failed 0

Common mistakes:

  • Treating “no error” as delivery, and building features on it.
  • Retrying “sent” emails because a member says they never got it, which spams everyone else.

Follow-up the interviewer might ask:

  • How would you learn about bounces? (A provider webhook, Chapter 52, updating the delivery.)
  • Should organizers see who did not get an announcement? (Failed ones, yes, as counts; addresses stay private.)
PAGE 006