ContentsClose contents
Pre-release
Chapter 54 · Channels and real-time updatesCHAPTER 54

Complete six-part pre-release for review. One package: channels 4.3.2, which does not yet declare Django 6.1 support; the whole suite passes with it. The in-memory channel layer reaches one server process; Redis comes in Chapter 62. Two earlier tests change on purpose.

Milestone reached in this chapter: API and integrations. Another program can list published events through an API and receive signed notifications when an event changes. All milestones

CHAPTER FIFTY-FOUR

Channels and real-time updates

Stage 6: APIs and real-time updates (Chapters 47 to 54)

Prerequisites: Chapters 9 to 53, including the Chapter 53 project on Daphne’s ASGI runserver with its 789 passing tests, announcements (Chapters 43 and 44), the places-left partial and htmx panel (Chapter 45), the waitlist and the door’s check-in count (Chapter 46), and the model methods every change goes through (Chapters 48 to 52)

What you’ll build: a live app with Django Channels that keeps open pages up to date: places left for everyone, a banner for members holding a place when the organizers write, and the door’s count for organizers, each sent after commit to only the people allowed to see it, checked again when their access changes; htmx polling every 30 seconds when a WebSocket cannot connect; and the trace that closes the fourth milestone

Why This Matters

Registration opens for a popular workshop at nine. At one minute past, Sai opens the event’s page: “3 of 20 places left”. By the time she has read the description, the workshop is full, and her page still says 3. She presses Register and is told it is full. Nothing was wrong with the rules; the page was simply old the moment it arrived. On the day itself, Sam posts “We moved to Room 2” from the Announcements page. The email goes out, but people already in the building are looking at the event’s page, not their inbox. At the door, two organizers check people in on two phones, and each phone’s count shows only its own check-ins.

All three need the server to speak first. Over plain HTTP the browser always asks and the server only answers, so a page can only be as new as its last request. A WebSocket keeps a connection open in both directions, so Otahque can send a message the moment something changes. Chapter 53 put Otahque on an ASGI server, which can hold such connections; Django Channels adds what Django lacks for them: code that handles a connection, and a way for the request that took a place to reach every page that is showing the event.

The hard part is not the connection. It is sending each update only to people allowed to see it, and remembering that permission can end while the page stays open. Places left are public. An announcement is for members holding a place, and a member who cancels must stop receiving them. The door’s count is for the event’s organizers, and an organizer who is removed must stop seeing it. This chapter builds the updates, checks access when a page connects and again whenever it changes, and keeps the page useful when the connection cannot be made.

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

  • explain what a WebSocket adds to HTTP, and what a channel layer does;
  • route WebSockets beside HTTP in config/asgi.py, with an origin check and the session’s member;
  • write a consumer that joins groups by permission, and checks again when that permission changes;
  • send messages after commit from the model methods every change already goes through;
  • keep a page working with polling when the WebSocket cannot connect;
  • explain why the in-memory channel layer reaches one process only, and what replaces it.

Out of scope: a Redis channel layer and running several server processes (Chapter 62), a proxy in front of WebSockets (Chapter 62), measuring how many connections one server holds (Chapter 66), and live chat or any message that people write to each other, which Otahque does not have.

PAGE 001

What You Need to Know

Asking, and being told

Chapter 52 met this choice between servers: a partner can poll, asking again and again, or be pushed a webhook. A browser has the same choice. Polling is simple and works everywhere, but the page is as old as the interval, and most requests find nothing new. A server cannot send a browser a request, though; it can only keep a connection the browser opened.

New Concept: a WebSocke

What problem exists? HTTP answers requests; a server cannot speak until the browser asks.

What did people do before? Poll every few seconds, or hold a request open until something happens (long polling) and then start another.

What is it? A WebSocket starts as an HTTP request with an Upgrade: websocket header; if the server agrees (101 Switching Protocols), the same connection stays open and either side may send a message at any time, until one closes it. The address starts with ws:// or, over TLS, wss://.

Why use it? Updates arrive within a moment of the change, and nothing travels when nothing changes.

Now let’s use it. Steps 3 to 6 build Otahque’s side; Step 8 the browser’s.

Two zones. Left, polling: a browser asks every 30 seconds, and the server answers each time, usually with nothing new; the page can be 30 seconds old. Right, a WebSocket: one request that upgrades, 101 Switching Protocols, and then one open connection; the server sends places left as soon as a place is taken, and the browser can send too.
Figure 54.1 — Asking every 30 seconds, and one connection that stays open.

There is a third way, server-sent events: an HTTP response that never ends and carries one message after another, from the server only. It needs no new protocol, and an async streaming view like Chapter 53’s download could send it. Otahque uses WebSockets because Channels gives it, ready-made, the part server-sent events would leave to us: one request telling every open page.

Prefer server-sent events

Server-sent events suit one-way updates, pass through more proxies unchanged, and reconnect by themselves. Each open page is then a streaming response on the server, and something must still tell all of them that a place was taken in another request: a channel layer, a database notification, or a shared queue. If Otahque later needed only that, an async view with StreamingHttpResponse and Channels’ layer would serve. The decision is recorded as D54.2.

Channels: consumers, groups, and the channel layer

Django’s views answer requests. A WebSocket is not a request: it opens, carries messages both ways for minutes or hours, and closes. Django Channels adds a consumer, a class with a method for each of those moments, served by the same ASGI application as Otahque’s pages.

New Tool: Django Channels 4.3.

What problem exists? Django has no code for a connection that stays open, and no way for one request to reach the connections that other requests opened.

What did people do before? A separate real-time server in another language, fed by the Django application.

What is it? A library, maintained by the Django project, that adds consumers for WebSockets, routing by protocol in config/asgi.py, sign-in through the session, and a channel layer for sending messages between them.

Why Channels? It runs on Daphne, already Otahque’s server; it uses Django’s sessions, users, and permissions as they are; and it is the long-established choice for this in Django.

Now let’s use it. Step 2 installs it.

Each open WebSocket has a channel, a name the channel layer can deliver messages to. Channels gather in groups: a consumer adds its channel to a group, and anything sent to the group reaches every channel in it. So when Sai takes a place, register() does not need to know who is looking at the event. It sends one message to the event’s group, and the channel layer delivers it to every page in that group, whichever request opened it.

Otahque uses four kinds of group (D54.1):

Table 54.1 — Otahque’s groups, and who may join them
Group Who joins What it hears
event.<id>.public Anyone who may see the event Places left, as counts
event.<id>.holders Members holding a place New announcements
event.<id>.organizers Those who may check members in The door's count
member.<id> The signed-in member Access changed; signed out

No message names a member: places left and the door’s count are numbers, and an announcement goes only to the people it was written for. Figure 54.2 shows a place taken reaching each open page.

Five numbered cards in order. 1, Sai presses Register: register() saves her place in its transaction. 2, after commit: places_changed() sends to event 7’s public group and its organizers group, and access_changed() to Sai’s own group. 3, the channel layer delivers each message to every channel in the group. 4, each consumer passes it to its browser, as JSON. 5, live.js changes 3 of 20 to 2 of 20 on every open page, and the door’s count on the organizers’ pages.
Figure 54.2 — From a place taken to every open page.

Under the Hood: the channel layer is one process’s memory, for no

The channel layer is a mailbox that consumers and ordinary code share. InMemoryChannelLayer, which this chapter uses, keeps its groups and messages in a Python dictionary in the server’s process. That is all a single runserver needs, and all the tests need. But a production site runs several processes, and a message sent in one process never reaches a consumer in another: a page connected to the second process would never hear of a place taken through the first. Channels’ documentation says plainly not to use the in-memory layer in production. Chapter 62 runs Redis, and channels_redis keeps the groups there, where every process can reach them. Step 10 shows the limit with two servers on one computer.

Access, at connect and after

A consumer decides which groups to join when the page connects: the event must be visible to the viewer, as on its page; a holder joins the holders group; an organizer the organizers group. That is not enough. Access can end while the page stays open for hours: Sai cancels her place in another tab, an administrator removes an organizer, someone signs out on a shared computer. Each of those sends a message to the member’s own group, after commit, and the consumer checks again: it leaves the groups it may no longer hear, joins any new ones, and closes the connection on sign-out (N54.4).

Three columns. Visitor: joins the public group only. Sai, holding a place: joins public, holders, and her own group; when she cancels, her own group hears access changed, and she leaves holders. Sam, organizing: joins public, organizers, and his own group; if he is removed as an organizer, he leaves organizers; when he signs out, the connection closes.
Figure 54.3 — Groups joined at connect, and left when access ends.

Two more checks guard the connection itself. A WebSocket carries the browser’s cookies, including the session, so another site’s page could open one to Otahque as the signed-in member; AllowedHostsOriginValidator refuses any WebSocket whose Origin header names a host outside ALLOWED_HOSTS, and one with no Origin at all, which is why a script cannot connect and must use the API. And AuthMiddlewareStack reads the session cookie and sets scope['user'], as Django’s middleware sets request.user.

When the WebSocket cannot connect

Some networks and proxies block WebSockets, and a server restart drops every connection. The page must still work. Each live part of a page also asks for itself every 30 seconds with htmx, as Chapter 45’s partials can; while the WebSocket is open, live.js skips those requests, and when it closes, they carry on and the page says “Updating every 30 s” (D54.2). The script reconnects after 2, 4, 8 seconds and so on, up to a minute, each wait shortened by a random part so that hundreds of pages do not all return in the same second after a restart. Announcements still arrive by email, as since Chapter 44.

In practice: the door on the da

Situation. Two organizers check in 120 members at two doors of the library, each on a phone.

Application. Each phone’s count says “47 of 120” and changes when either of them checks someone in; when the library’s network drops one phone’s WebSocket, its count lags by up to 30 seconds and says so, and catches up when the socket returns.

Consideration. The count is a convenience; the check-in records are the truth, and each check-in is still saved once, under the place’s lock (Chapter 46), whatever the pages show.

How many pages

How many open pages must one server hold? The book sets a working target, as a labelled assumption rather than a measurement: one popular event’s page open in up to 300 browsers at once, on one server process (N54.6). A community report of about 200 connections on a small virtual server is an anecdote, useful only as a sign that the number matters. Chapter 66 measures it under load.

PAGE 002

How We Build It

Start from Chapter 53, in the folder containing manage.py, with Otahque on PostgreSQL 18, Daphne’s runserver, 789 passing tests, and the work committed (the last commit is “Serve Otahque over ASGI; send a test webhook”). One package is added, channels 4.3.2. A new app, live, holds the groups, the consumer, its address, and three test modules. config/asgi.py routes WebSockets beside HTTP. The events and registrations models send after commit; the event page, its places, the door page, and the base template gain their live parts; the two views answer htmx’s polling; static/live/live.js is new; two earlier tests, the stylesheet, the settings, pyproject.toml, and the acceptance test change; ADR-010, a design note, and the fourth milestone’s trace are new. No migration. The visible result: an event’s page says Live and follows places as they are taken; members holding a place see a banner when the organizers write; two door pages share one count; and without a WebSocket, the page says “Updating every 30 s” and still catches up. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.

The Custom Way

The quickest live page asks the server again and again:

setInterval(async () => {
  const answer = await fetch(location.href);
  document.body.innerHTML = await answer.text();
}, 2000);

Three hundred people on a popular event’s page make 150 requests a second, each rendering the whole page, almost all for nothing. Replacing the body throws away whatever a person was typing. And innerHTML with whatever came back is exactly how a page runs someone else’s script. Polling has its place, as the fallback in Step 6, at 30 seconds and for one small part of a page. This illustration is not added to the project.

The Django Way

The Django Way adds Channels to the ASGI application of Chapter 53: one consumer per open event page, groups decided by the same rules as the pages, and messages sent after commit from the model methods that every change already goes through, so no view has to remember to send them.

Step 1: Check the starting point

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

OK
git status --short
git log --oneline -1
... Serve Otahque over ASGI; send a test webhook

Step 2: Channels

uv add channels==4.3.2
Resolved 83 packages in ...
Installed 1 package in ...
 + channels==4.3.2

A caveat comes with it (N54.5). Channels 4.3.2, released on 20 November 2025, declares support for Django up to 6.0; no release yet names 6.1, though its development branch has been tested against 6.1 since July 2026. The book’s plan review tried it on Django 6.1 and Python 3.14, and this chapter’s whole suite is the check: if it ever fails because of Channels, the book stops and says so. One part is avoided on purpose: ChannelsLiveServerTestCase, which runs a real server for browser tests, has an open issue on Python 3.14, and the browser checks in Step 8 use the real runserver instead. The pin is checked again at Channels’ next release, or at Chapter 62.

Step 3: The live app

uv run python manage.py startapp live

As for the API and the integrations, the tests go in a package. Replace the file startapp made:

Remove-Item live\tests.py
New-Item -ItemType Directory live\tests | Out-Null
New-Item live\tests\__init__.py | Out-Null
rm live/tests.py
mkdir live/tests
touch live/tests/__init__.py

The app has no models; its other startapp files stay as they were made. In config/settings.py, add the app and the channel layer; the end of INSTALLED_APPS becomes:

    # Chapter 52: webhooks to partners' servers.
    'integrations.apps.IntegrationsConfig',
    # Chapter 54: live updates to open pages.
    'live.apps.LiveConfig',
]

# Chapter 54: how consumers in one process reach each other.
# The in-memory layer works only within one process, which
# is enough for runserver and tests; Chapter 62 runs Redis.
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels.layers.InMemoryChannelLayer',
    },
}

channels itself needs no entry in INSTALLED_APPS: Daphne already provides runserver. In pyproject.toml, coverage measures the new app too, so it is not missed as integrations was:

source = ["accounts", "api", "audit", "config", "events",
          "integrations", "live", "registrations"]

Step 4: Groups, and sending after commit

The tests come first. Each change runs inside captureOnCommitCallbacks(execute=True), Chapter 44’s way to run what waits for a commit, and send() is replaced by a mock that records which group heard what. Create live/tests/test_messages.py:

"""What each change tells open pages, after commit (54)."""
from unittest import mock

from django.db import transaction
from django.test import TestCase
from django.utils import timezone

from config.helpers import in_group
from registrations.models import CheckIn
from registrations.tests.test_checkin import tonight
from registrations.tests.test_registrations import (
    soon, verified,
)


class MessageTests(TestCase):
    """Every path that changes places, access, or news."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event = soon(capacity=1)
        cls.event.add_organizer(cls.sam)
        cls.sai = verified('sai@example.org')
        cls.raj = verified('raj@example.org')

    def sent(self, action):
        """Run action; return (group, type) sent after commit."""
        with mock.patch('live.groups.send') as send:
            with self.captureOnCommitCallbacks(execute=True):
                action()
        return [(group, message['type'])
                for (group, message), _ in send.call_args_list]

    def test_a_place_taken(self):
        event, sai = self.event, self.sai
        sent = self.sent(
            lambda: event.register(sai, timezone.now()))
        self.assertEqual(sent, [
            (f'event.{event.pk}.public', 'places'),
            (f'event.{event.pk}.organizers', 'door'),
            (f'member.{sai.pk}', 'access.changed'),
        ])

    def test_a_rollback_tells_nobody(self):
        def taken_then_undone():
            with transaction.atomic():
                self.event.register(self.sai, timezone.now())
                transaction.set_rollback(True)
        self.assertEqual(self.sent(taken_then_undone), [])

    def test_the_public_message_holds_counts_only(self):
        with mock.patch('live.groups.send') as send:
            with self.captureOnCommitCallbacks(execute=True):
                self.event.register(self.sai, timezone.now())
        message = send.call_args_list[0].args[1]
        self.assertEqual(message, {
            'type': 'places', 'left': 0, 'capacity': 1,
            'status': 'published'})

    def test_a_cancel_promotes_and_tells_both(self):
        place = self.event.register(self.sai, timezone.now())
        self.event.waitlist.create(member=self.raj)
        sent = self.sent(lambda: place.cancel(timezone.now()))
        self.assertIn((f'member.{self.sai.pk}',
                       'access.changed'), sent)
        self.assertIn((f'member.{self.raj.pk}',
                       'access.changed'), sent)
        self.assertIn((f'event.{self.event.pk}.public',
                       'places'), sent)

    def test_an_edit_and_a_cancelled_event(self):
        event = self.event

        def bigger(locked):
            locked.capacity = 5
            return []
        sent = self.sent(lambda: event.edit(
            self.sam, event.version, bigger))
        self.assertIn((f'event.{event.pk}.public', 'places'),
                      sent)
        event.refresh_from_db()
        sent = self.sent(lambda: event.cancel_by(self.sam))
        self.assertIn((f'event.{event.pk}.public', 'places'),
                      sent)

    def test_an_announcement_goes_to_holders(self):
        sent = self.sent(lambda: self.event.announce(
            self.sam, 'We moved to Room 2.', public=False))
        self.assertEqual(sent, [
            (f'event.{self.event.pk}.holders', 'announcement'),
        ])

    def test_losing_the_organizer_role(self):
        sai = in_group('sai2@example.org', 'Organizers')
        assignment = self.event.add_organizer(sai)
        sent = self.sent(lambda: assignment.revoke(self.sam))
        self.assertEqual(sent, [(f'member.{sai.pk}',
                                 'access.changed')])

    def test_a_check_in_and_its_undo(self):
        event = tonight()
        place = event.register(self.sai, timezone.now())
        door = (f'event.{event.pk}.organizers', 'door')
        sent = self.sent(lambda: place.check_in(
            self.sam, CheckIn.Method.NAME, timezone.now()))
        self.assertEqual(sent, [door])
        checkin = place.checkin
        sent = self.sent(lambda: checkin.undo(self.sam,
                                              timezone.now()))
        self.assertEqual(sent, [door])

    def test_signing_out_closes_the_pages(self):
        self.client.force_login(self.sai)
        with mock.patch('live.groups.send') as send:
            self.client.post('/accounts/logout/')
        send.assert_called_once_with(
            f'member.{self.sai.pk}', {'type': 'signed.out'})
uv run python manage.py test live.tests.test_messages
Found 9 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancel_promotes_and_tells_both
AttributeError: module 'live' has no attribute 'groups'
ERROR: test_a_check_in_and_its_undo
AttributeError: module 'live' has no attribute 'groups'
ERROR: test_a_place_taken
AttributeError: module 'live' has no attribute 'groups'
... (6 more like these)
Ran 9 tests in ...s

FAILED (errors=9)

Create live/groups.py, the one place that names groups and sends to them:

"""Who hears what, and sending it after commit (Chapter 54).

Each open event page joins groups in the channel layer:
everyone joins the event's public group; members holding
a place, its holders group; its organizers, its organizers
group; and every signed-in member, a group of their own.
A change sends a message to a group once its transaction
commits, so a rolled-back change tells nobody. Messages
carry counts and announcements, never a member's name.
"""
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import transaction


def public(event_id):
    """Return the group every viewer of an event joins."""
    return f'event.{event_id}.public'


def holders(event_id):
    """Return the group of members holding a place."""
    return f'event.{event_id}.holders'


def organizers(event_id):
    """Return the group of the event's organizers."""
    return f'event.{event_id}.organizers'


def member(member_id):
    """Return one member's own group, for access changes."""
    return f'member.{member_id}'


def send(group, message):
    """Send message to group now, from sync code."""
    async_to_sync(get_channel_layer().group_send)(group,
                                                  message)


def after_commit(group, make):
    """Send make()'s message to group once committed.

    make() runs after the commit, so the counts it reads
    include the change.
    """
    transaction.on_commit(lambda: send(group, make()))


def places_changed(event):
    """Tell the event's pages how many places are left.

    Called by every change to places: register() (and so a
    promotion from the waitlist), a place's cancel(),
    Event.edit(), and cancel_by(). The organizers also get
    the door's count, which counts places held.
    """
    after_commit(public(event.pk), lambda: places(event.pk))
    after_commit(organizers(event.pk), lambda: door(event.pk))


def door_changed(event):
    """Tell the organizers' pages the door's new count."""
    after_commit(organizers(event.pk), lambda: door(event.pk))


def announced(announcement):
    """Show a new announcement to members holding places."""
    after_commit(holders(announcement.event_id), lambda: {
        'type': 'announcement',
        'body': announcement.body,
        'sent_at': announcement.sent_at.isoformat(),
    })


def access_changed(member_id):
    """Ask the member's open pages to check access again."""
    after_commit(member(member_id),
                 lambda: {'type': 'access.changed'})


def signed_out(sender, request, user, **kwargs):
    """Close the member's open pages' live updates."""
    if user is not None:
        send(member(user.pk), {'type': 'signed.out'})


def places(event_id):
    """Return the places message: counts and status only."""
    from events.models import Event

    event = Event.objects.with_places().get(pk=event_id)
    return {'type': 'places', 'left': event.places_left,
            'capacity': event.capacity,
            'status': event.status}


def door(event_id):
    """Return the door's count: places held, and came."""
    from registrations.models import Registration

    counts = Registration.objects.filter(
        event_id=event_id).attendance()
    return {'type': 'door', **counts}

Now that groups.py exists, give live/apps.py its docstrings and a ready() that connects signed_out() to Django’s sign-out signal:

"""The live app: updates sent to open pages (Chapter 54)."""
from django.apps import AppConfig


class LiveConfig(AppConfig):
    """Live updates over WebSockets, with Channels."""

    name = 'live'

    def ready(self):
        """Connect the sign-out signal to the member's group."""
        from django.contrib.auth.signals import user_logged_out

        from .groups import signed_out
        user_logged_out.connect(signed_out,
                                dispatch_uid='live.signed_out')

Importing groups inside ready(), not at the top of the file, waits until every app is loaded, as Chapter 40’s checks did.

async_to_sync() is the other half of Chapter 53’s sync_to_async(): it lets sync code, such as a model method, await the channel layer’s group_send(). The message is made by make() after the commit, so its counts include the change. Group names use only letters, digits, hyphens, and periods, which is all the channel layer accepts.

Now call it from the model methods. In events/models.py, import it beside the audit module:

from audit.models import AuditEvent, record
from live import groups as live

A new organizer’s pages check their access again:

    def add_organizer(self, member):
        """Make member a current organizer of this event.

        Since Chapter 54, the member's open pages check
        their access again once this commits.
        """
        assignment = self.organizer_assignments.create(
            member=member
        )
        live.access_changed(member.pk)
        return assignment

edit() ends, after the webhook is queued:

            announce(event, 'event.changed')
            live.places_changed(event)
            if dry_run:
                transaction.set_rollback(True)

cancel_by() the same way:

            announce(self, 'event.cancelled')
            live.places_changed(self)
            if dry_run:
                transaction.set_rollback(True)

announce() tells the holders:

            made = event.announcements.create(
                author=author, body=body, public=public,
            )
            live.announced(made)
            return made

and register(), which every place goes through, a waitlist promotion included, ends:

            try:
                with transaction.atomic():
                    place = event.registrations.create(
                        member=member, registered_at=now,
                        answers=answers or {}, source=source,
                    )
            except IntegrityError:
                # Only the one-active-place rule means a
                # repeat; any other failure is re-raised.
                if event.place_of(member) is None:
                    raise
            else:
                # Chapter 54: open pages hear of it after
                # commit; the member's own pages check again.
                live.places_changed(event)
                live.access_changed(member.pk)
                return place
            raise refusal(['already_registered'])

In OrganizerAssignment.revoke(), the removed organizer’s pages check again:

            record(by, REMOVED, event, member=self.member_id)
            live.access_changed(self.member_id)

In registrations/models.py, the import:

from events import emails
from live import groups as live

a place’s cancel():

            if changed:
                event.fill_from_waitlist(now)
                # Chapter 54: after commit, the count on open
                # pages, and this member's access.
                live.places_changed(event)
                live.access_changed(self.member_id)
        return changed == 1

and the door’s count after a check-in, at the end of check_in():

            record(by, Action.CHECK_IN, place, method=method)
            live.door_changed(place.event)
        return checkin

and of undo():

            record(by, Action.UNDO_CHECK_IN,
                   checkin.registration)
            live.door_changed(checkin.registration.event)
        return checkin
uv run python manage.py test live.tests.test_messages
Found 9 test(s).
Creating test database for alias 'default'...
...
Ran 9 tests in ...s

OK

Common Error: sending inside the transactio

Calling send() straight from register() would tell every page about a place that a later step of the same transaction may still roll back, as Chapter 52’s webhooks would have announced a change that never happened. Worse, a page that reacted by asking for the count would read the old one. after_commit() sends only once the change is in the database, and test_a_rollback_tells_nobody keeps it that way.

One earlier test counted what waits for the commit after a registration: one email, since Chapter 44. Three live updates now wait with it. Run it:

uv run python manage.py test events.tests.test_emails
Found 4 test(s).
Creating test database for alias 'default'...
FAIL: test_nothing_is_sent_before_commit
AssertionError: 4 != 1
Ran 4 tests in ...s

FAILED (failures=1)

In events/tests/test_emails.py, test_nothing_is_sent_before_commit ends:

        self.assertEqual(mail.outbox, [])
        # The email, then three live updates (Chapter 54).
        self.assertEqual(len(waiting), 4)
uv run python manage.py test events.tests.test_emails
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK

Step 5: The consumer

The consumer’s tests open real WebSockets to Otahque’s ASGI application with Channels’ WebsocketCommunicator, through the origin check and the session, as a browser would. They change data and expect messages, so they need real commits: a TransactionTestCase, with serialized_rollback to put back the groups the migrations made. Create live/tests/test_consumers.py:

"""The event page's WebSocket, end to end (Chapter 54).

Each test opens a real WebSocket to Otahque's ASGI
application with Channels' WebsocketCommunicator: the
origin check, the session's member, and the groups. A
TransactionTestCase, so changes really commit and their
messages are really sent; serialized_rollback puts the
groups of the migrations back afterwards.
"""
from functools import wraps

from asgiref.sync import sync_to_async
from channels.testing import WebsocketCommunicator
from django.contrib.auth import logout
from django.test import (
    Client, RequestFactory, TransactionTestCase,
)
from django.utils import timezone

from config.asgi import application
from config.helpers import in_group
from events.models import Event
from registrations.tests.test_registrations import (
    soon, verified,
)

ORIGIN = (b'origin', b'http://testserver')


def closing(test):
    """Close every socket a test opened, even if it fails."""
    @wraps(test)
    async def run(self):
        self.sockets = []
        try:
            await test(self)
        finally:
            for socket in self.sockets:
                await socket.disconnect()
    return run


def cookie_for(user):
    """Return a Cookie header that signs in as user."""
    client = Client()
    client.force_login(user)
    return (b'cookie', f'sessionid='
            f'{client.cookies["sessionid"].value}'.encode())


class ConsumerTests(TransactionTestCase):
    """Who may listen to an event, and what each hears."""

    serialized_rollback = True

    def setUp(self):
        self.sam = in_group('sam@example.org', 'Organizers')
        self.event = soon(capacity=2)
        self.event.add_organizer(self.sam)
        self.sai = verified('sai@example.org')

    async def open(self, user=None, event=None, origin=ORIGIN):
        """Connect to an event's socket; return (ok, socket)."""
        headers = [origin] if origin else []
        if user is not None:
            headers.append(await sync_to_async(cookie_for)(user))
        path = f'/ws/events/{(event or self.event).pk}/'
        socket = WebsocketCommunicator(application, path,
                                       headers=headers)
        connected, _ = await socket.connect()
        self.sockets.append(socket)
        return connected, socket

    async def register(self, member):
        """Give member a place, committed; return it."""
        return await sync_to_async(self.event.register)(
            member, timezone.now())

    @closing
    async def test_a_visitor_hears_places_left(self):
        connected, socket = await self.open()
        self.assertTrue(connected)
        await self.register(self.sai)
        self.assertEqual(await socket.receive_json_from(), {
            'type': 'places', 'left': 1, 'capacity': 2,
            'status': 'published'})

    @closing
    async def test_another_site_or_no_origin_is_refused(self):
        for origin in ((b'origin', b'https://evil.example'),
                       None):
            with self.subTest(origin):
                connected, _ = await self.open(origin=origin)
                self.assertFalse(connected)

    @closing
    async def test_a_hidden_draft_is_refused(self):
        draft = await sync_to_async(soon)(
            status=Event.Status.DRAFT)
        connected, _ = await self.open(self.sai, draft)
        self.assertFalse(connected)

    @closing
    async def test_only_holders_hear_announcements(self):
        _, holder = await self.open(self.sai)
        await holder.receive_nothing()
        await self.register(self.sai)
        raj = await sync_to_async(verified)('raj@example.org')
        _, other = await self.open(raj)
        await holder.receive_json_from()    # places
        self.assertEqual(await holder.receive_json_from(),
                         {'type': 'access'})
        await sync_to_async(self.event.announce)(
            self.sam, 'We moved to Room 2.', public=False)
        news = await holder.receive_json_from()
        self.assertEqual(news['body'], 'We moved to Room 2.')
        self.assertTrue(await other.receive_nothing())

    @closing
    async def test_a_cancelled_place_stops_the_news(self):
        place = await self.register(self.sai)
        _, socket = await self.open(self.sai)
        await sync_to_async(place.cancel)(timezone.now())
        await socket.receive_json_from()    # places
        self.assertEqual(await socket.receive_json_from(),
                         {'type': 'access'})
        await sync_to_async(self.event.announce)(
            self.sam, 'Bring a laptop.', public=False)
        self.assertTrue(await socket.receive_nothing())

    @closing
    async def test_only_organizers_hear_the_door(self):
        _, organizer = await self.open(self.sam)
        _, member = await self.open(self.sai)
        await self.register(self.sai)
        await organizer.receive_json_from()   # places
        door = await organizer.receive_json_from()
        self.assertEqual(door, {'type': 'door', 'held': 1,
                                'came': 0})
        await member.receive_json_from()      # places
        await member.receive_json_from()      # access
        self.assertTrue(await member.receive_nothing())

    @closing
    async def test_signing_out_closes_the_socket(self):
        _, socket = await self.open(self.sai)

        def sign_out():
            request = RequestFactory().get('/')
            request.user = self.sai
            request.session = Client().session
            logout(request)
        await sync_to_async(sign_out)()
        self.assertEqual(await socket.receive_output(),
                         {'type': 'websocket.close'})

closing() disconnects every socket a test opened, even when an assertion fails, so no consumer is left running into the next test. Each WebSocket sends Origin: http://testserver, the host Django’s tests run as; receive_nothing() waits a moment and returns whether nothing came.

uv run python manage.py test live.tests.test_consumers
Found 7 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancelled_place_stops_the_news
ValueError: Django can only handle ASGI/HTTP connections, not
    websocket.
ERROR: test_a_hidden_draft_is_refused
ValueError: Django can only handle ASGI/HTTP connections, not
    websocket.
ERROR: test_a_visitor_hears_places_left
ValueError: Django can only handle ASGI/HTTP connections, not
    websocket.
... (5 more like these)
Ran 7 tests in ...s

FAILED (errors=8)

Every test fails: config/asgi.py still knows only HTTP, so no WebSocket can connect. Create live/consumers.py:

"""The WebSocket an event's pages keep open (Chapter 54)."""
from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer

from events.models import Event

from . import groups


@database_sync_to_async
def allowed_groups(event_id, user):
    """Return the groups user may join for an event, or None.

    None if the event does not exist or user may not see
    it. Everyone who may see it joins the public group; a
    member holding a place, the holders group; one who may
    check people in, the organizers group; and a signed-in
    member, their own group, which tells them when this
    changes.
    """
    event = Event.objects.filter(pk=event_id).first()
    if event is None or not event.is_visible_to(user):
        return None
    allowed = {groups.public(event_id)}
    if user.is_authenticated:
        allowed.add(groups.member(user.pk))
        if event.place_of(user) is not None:
            allowed.add(groups.holders(event_id))
        if event.can_check_in(user):
            allowed.add(groups.organizers(event_id))
    return allowed


class EventConsumer(AsyncJsonWebsocketConsumer):
    """Pass an event's live updates to one open page.

    Access is checked when the page connects, and again
    whenever the member's access may have changed: a place
    taken or cancelled, an organizer added or removed. A
    member who signs out is disconnected.
    """

    async def connect(self):
        """Join the groups this viewer may hear, or refuse."""
        self.event_id = self.scope['url_route']['kwargs'][
            'event_id']
        self.joined = set()
        wanted = await allowed_groups(self.event_id,
                                      self.scope['user'])
        if wanted is None:
            await self.close()
            return
        await self.accept()
        await self.join(wanted)

    async def join(self, wanted):
        """Leave groups no longer allowed; join new ones."""
        for group in self.joined - wanted:
            await self.channel_layer.group_discard(
                group, self.channel_name)
        for group in wanted - self.joined:
            await self.channel_layer.group_add(
                group, self.channel_name)
        self.joined = wanted

    async def disconnect(self, code):
        """Leave every group when the page goes away."""
        await self.join(set())

    async def places(self, message):
        """Pass on the places left (public)."""
        await self.send_json(message)

    async def announcement(self, message):
        """Pass on an announcement (holders only)."""
        await self.send_json(message)

    async def door(self, message):
        """Pass on the door's count (organizers only)."""
        await self.send_json(message)

    async def access_changed(self, message):
        """Check access again; join or leave groups."""
        wanted = await allowed_groups(self.event_id,
                                      self.scope['user'])
        if wanted is None:
            await self.close()
            return
        await self.join(wanted)
        await self.send_json({'type': 'access'})

    async def signed_out(self, message):
        """Stop: the member signed out of this browser."""
        await self.join(set())
        await self.close()

A message’s type names the method that handles it: places calls places(), and the dot in access.changed becomes an underscore. database_sync_to_async() is Channels’ sync_to_async() for the ORM: it also closes database connections that have gone stale, as Django does between requests. The consumer never sends the browser anything it was not sent by a group it may hear. Create live/routing.py, the WebSocket’s address:

"""Addresses of Otahque's WebSockets (Chapter 54)."""
from django.urls import path

from .consumers import EventConsumer

websocket_urlpatterns = [
    path('ws/events/<int:event_id>/', EventConsumer.as_asgi()),
]

and route WebSockets beside HTTP in config/asgi.py:

"""
ASGI config for config project.

It exposes the ASGI callable as a module-level variable named
``application``.

For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE', 'config.settings'
)

# Chapter 54: load Django first, so the apps are ready
# before the consumers import their models.
django_application = get_asgi_application()

from channels.auth import AuthMiddlewareStack  # noqa: E402
from channels.routing import (  # noqa: E402
    ProtocolTypeRouter, URLRouter,
)
from channels.security.websocket import (  # noqa: E402
    AllowedHostsOriginValidator,
)

from live.routing import websocket_urlpatterns  # noqa: E402

# Pages over HTTP go to Django as before. A WebSocket must
# come from one of ALLOWED_HOSTS (its Origin header), and
# carries the signed-in member from the session cookie.
application = ProtocolTypeRouter({
    'http': django_application,
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
    ),
})

get_asgi_application() runs first: it sets Django up, so the consumers can import models. That is why the other imports come after it, marked for the linter.

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

OK

Common Error: a WebSocket that connects and hears nothin

If the browser’s console shows the socket open but no update ever arrives, check the group names first: a typo in one place sends to a group nobody joined, and the channel layer does not complain. Every name in Otahque comes from one of the four functions in live/groups.py for that reason. Then check that the change committed: a message waits for the commit, and a dry run never commits.

Step 6: The pages, and their fallback

The tests: the page names its socket and script, members get the hidden banner, and htmx’s polling gets just the part it asked for. Create live/tests/test_pages.py:

"""The pages' live parts, and their fallback (Chapter 54)."""
from django.test import TestCase
from django.utils import timezone

from config.helpers import in_group
from registrations.tests.test_checkin import tonight
from registrations.tests.test_registrations import (
    soon, url, verified,
)

POLL = {'HX-Request': 'true', 'HX-Target': 'places-left'}


class LivePageTests(TestCase):
    """What live.js connects to, and what htmx polls."""

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

    def test_the_page_names_its_socket_and_script(self):
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(
            page, f'data-live="/ws/events/{self.event.pk}/"')
        self.assertContains(page, '/static/live/live.js')
        self.assertNotContains(page, 'id="live-banner"')

    def test_members_get_the_banner_hidden(self):
        self.client.force_login(self.sai)
        page = self.client.get(self.event.get_absolute_url())
        self.assertContains(page, 'id="live-banner"')

    def test_polling_gets_the_places_alone(self):
        self.event.register(self.sai, timezone.now())
        page = self.client.get(self.event.get_absolute_url(),
                               headers=POLL)
        html = page.content.decode().strip()
        self.assertTrue(
            html.startswith('<span id="places-left"'))
        self.assertIn('2 of 3 places left', html)
        self.assertNotIn('<html', html)


class DoorPollTests(TestCase):
    """The door's count, polled by organizers."""

    @classmethod
    def setUpTestData(cls):
        cls.event = tonight()
        cls.sam = in_group('sam@example.org', 'Organizers')
        cls.event.add_organizer(cls.sam)
        cls.event.register(verified('sai@example.org'),
                           timezone.now())

    def test_polling_gets_the_count_alone(self):
        self.client.force_login(self.sam)
        page = self.client.get(
            url('door', self.event.pk),
            headers={'HX-Request': 'true',
                     'HX-Target': 'door-count'})
        html = page.content.decode().strip()
        self.assertTrue(html.startswith('<p id="door-count"'))
        self.assertIn('0 of 1', html)
uv run python manage.py test live.tests.test_pages
Found 4 test(s).
Creating test database for alias 'default'...
FAIL: test_members_get_the_banner_hidden
AssertionError: False is not true : Couldn't find
    'id="live-banner"' in the following response
FAIL: test_polling_gets_the_count_alone
AssertionError: False is not true
FAIL: test_polling_gets_the_places_alone
AssertionError: False is not true
... (1 more like these)
Ran 4 tests in ...s

FAILED (failures=4)

Pages need a place for their own scripts. In templates/base.html, after site.js:

  <script src="{% static 'otahque/site.js' %}"
          defer></script>
  {# Chapter 54: a page's own scripts, such as live.js. #}
  {% block scripts %}{% endblock %}
</head>
{# htmx sends the CSRF token with requests that are not #}
{# forms; a form sends its own field.                   #}

In events/templates/events/detail.html, load the static tag and add the script, at the top:

{% extends "base.html" %}
{% load static %}

{% block title %}{{ event.title }} | Otahque{% endblock %}

{% block scripts %}
  <script src="{% static 'live/live.js' %}" defer></script>
{% endblock %}

the status line under the title:

    <header class="space-y-1">
      <h1>{{ event.title }}</h1>
      {# Chapter 54: live.js connects here, and says how #}
      {# the page is kept up to date.                     #}
      <p class="live-status" data-live-status hidden
         data-live="/ws/events/{{ event.pk }}/"
         aria-live="polite"></p>

and the banner after the facts:

        {% include "events/facts.html" %}
        {% if user.is_authenticated %}
          {# Filled by live.js when the organizers write to #}
          {# members holding places (Chapter 54).          #}
          <div id="live-banner" class="live-banner"
               role="status" aria-live="polite" hidden></div>
        {% endif %}
        {% include "events/announcement_cards.html" %}

The places, in events/templates/events/facts.html, ask for themselves every 30 seconds:

      <dd>{% partialdef places-left inline %}
        {# Chapter 45: replaced out of band after a swap.  #}
        {# Chapter 54: live.js updates it; if the socket   #}
        {# fails, htmx asks for it again every 30 seconds. #}
        <span id="places-left" data-poll
              hx-get="{{ event.get_absolute_url }}"
              hx-trigger="every 30s" hx-swap="outerHTML"
              {% if swapped %}hx-swap-oob="true"{% endif %}>
          {% include "events/places.html" %}</span>
        {% endpartialdef %}

data-poll marks it as something live.js may skip. htmx sends HX-Target: places-left with that request, so the event’s view returns only the partial. In events/views.py, after get_queryset():

    def get_queryset(self):
        """Events with places_left, as the page shows it."""
        return Event.objects.with_places()

    def get_template_names(self):
        """Return the places alone when htmx polls for them.

        Chapter 54: the fallback when live updates fail.
        """
        if self.request.htmx.target == 'places-left':
            return ['events/facts.html#places-left']
        return super().get_template_names()

The door page does the same for its count. In registrations/templates/registrations/door.html, the top becomes:

{% extends "base.html" %}
{% load static %}

{% block title %}Check-in: {{ event.title }} |
  Otahque{% endblock %}

{% block scripts %}
  <script src="{% static 'live/live.js' %}" defer></script>
{% endblock %}

{% block content %}
  <div class="door">
    <h1>Check-in: {{ event.title }}</h1>
    <p class="live-status" data-live-status hidden
       data-live="/ws/events/{{ event.pk }}/"
       aria-live="polite"></p>
    {# Chapter 54: the count follows other organizers' #}
    {# check-ins live, or every 30 seconds.             #}
    {% url 'registrations:door' event.pk as door %}
    {% partialdef door-count inline %}
    <p id="door-count" class="door-count" role="status"
       data-poll hx-get="{{ door }}" hx-trigger="every 30s"
       hx-swap="outerHTML"
       {% if swapped %}hx-swap-oob="true"{% endif %}>

and, because the address door is now set above the count, the line that set it before the search form goes:

    {# Chapter 46: the list follows the search as you #}
    {# type; without JavaScript, press Search.         #}

In registrations/views.py, DoorView.get_template_names() becomes:

        htmx = self.request.htmx
        if (htmx and htmx.target == 'door-list'
                and not htmx.history_restore_request):
            return [f'{self.template_name}#door-list']
        # Chapter 54: the count alone, when polled.
        if htmx and htmx.target == 'door-count':
            return [f'{self.template_name}#door-count']
        return super().get_template_names()
uv run python manage.py test live.tests.test_pages
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK

Chapter 45’s panel test checked the places’ markup exactly, line break included; the markup changed. Run it:

uv run python manage.py test registrations.tests.test_panel
Found 9 test(s).
Creating test database for alias 'default'...
FAIL: test_the_count_is_swapped_out_of_band
AssertionError: False is not true : Couldn't find
    'id="places-left"
Ran 9 tests in ...s

FAILED (failures=1)

In registrations/tests/test_panel.py, test_the_count_is_swapped_out_of_band checks the two attributes that matter, wherever the line breaks fall:

        self.assertContains(response,
                            'id="places-left" data-poll')
        self.assertContains(response, 'hx-swap-oob="true"')
uv run python manage.py test registrations.tests.test_panel
Found 9 test(s).
Creating test database for alias 'default'...
...
Ran 9 tests in ...s

OK

Step 7: The browser’s side

Static files belong to their app’s folder in static/ (Chapter 14). Create static/live/live.js:

// Chapter 54: live updates for an event's pages. One
// WebSocket per page: places left for everyone, the
// announcement banner for members holding a place, the
// door's count for organizers. While it is open, htmx's
// 30-second polling is skipped; when it fails, polling
// carries on, and the label says so.
const root = document.querySelector('[data-live]');
const FALLBACK = 'Updating every 30 s';
let failures = 0;

function say(text, mode) {
  root.hidden = false;
  root.dataset.mode = mode;
  root.textContent = text;
}

// Places left, drawn as events/places.html draws them.
function places(message) {
  const target = document.getElementById('places-left');
  if (!target) {
    return;
  }
  const shown = document.createElement('span');
  if (message.status === 'cancelled') {
    shown.className = 'places badge badge-error';
    shown.textContent = 'Cancelled';
  } else if (message.left > 0) {
    shown.className = 'places inline-flex items-center gap-2'
      + ' text-sm';
    const bar = document.createElement('progress');
    bar.className = 'progress progress-primary w-20';
    bar.value = message.left;
    bar.max = message.capacity;
    bar.setAttribute('aria-hidden', 'true');
    shown.append(bar, `${message.left} of `
      + `${message.capacity} places left`);
  } else {
    shown.className = 'places badge badge-warning';
    shown.textContent = 'Full';
  }
  target.replaceChildren(shown);
  changed(target);
}

// A new announcement, for members holding a place.
function announcement(message) {
  const banner = document.getElementById('live-banner');
  if (!banner) {
    return;
  }
  const title = document.createElement('strong');
  title.textContent = 'New from the organizers';
  const body = document.createElement('p');
  body.textContent = message.body;
  banner.replaceChildren(title, body);
  banner.hidden = false;
  changed(banner);
}

// The door's count, for organizers.
function door(message) {
  const count = document.querySelector('#door-count strong');
  if (!count) {
    return;
  }
  count.textContent = `${message.came} of ${message.held}`;
  changed(count);
}

// A brief highlight; CSS skips it for reduced motion.
function changed(element) {
  element.classList.remove('live-changed');
  void element.offsetWidth;
  element.classList.add('live-changed');
}

const handlers = {places, announcement, door};

function connect() {
  const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
  const socket = new WebSocket(
    `${scheme}://${location.host}${root.dataset.live}`);
  socket.addEventListener('open', () => {
    failures = 0;
    document.body.dataset.live = 'on';
    say('Live', 'live');
  });
  socket.addEventListener('message', (event) => {
    const message = JSON.parse(event.data);
    const handle = handlers[message.type];
    if (handle) {
      handle(message);
    }
  });
  socket.addEventListener('close', () => {
    delete document.body.dataset.live;
    failures += 1;
    say(FALLBACK, 'poll');
    // Wait longer after each failure, up to a minute,
    // with jitter, so pages do not all return at once.
    const wait = Math.min(60000, 1000 * 2 ** failures);
    setTimeout(connect, wait / 2 + Math.random() * wait / 2);
  });
}

// While the socket is open, skip htmx's polling.
document.addEventListener('htmx:beforeRequest', (event) => {
  const polling = event.detail.elt.hasAttribute('data-poll');
  if (polling && document.body.dataset.live === 'on') {
    event.preventDefault();
  }
});

if (root && 'WebSocket' in window) {
  connect();
}

Everything the script puts on the page is made with createElement() and textContent, never innerHTML, so an announcement’s text can never run as code; and there is no script inside the templates, ready for Chapter 59’s content security policy, which will allow the site’s own ws: and wss: addresses. htmx:beforeRequest is the event htmx fires before each request; cancelling it for a data-poll element while the socket is open is how polling steps aside. htmx’s trigger filters, such as every 30s [condition], would be shorter, but they run as JavaScript that htmx evaluates itself, which Otahque’s htmx settings switched off in Chapter 45 for the same reason.

In static/otahque/source.css, before .form-actions:

  /* Chapter 54: how the page is kept up to date, the
     holders' banner, and a change shown without a jump. */
  .live-status {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    font-size: 0.875rem;
    color: color-mix(in oklab, var(--color-base-content)
                     75%, transparent);
  }
  .live-status::before {
    content: "";
    width: 0.5rem;
    height: 0.5rem;
    border-radius: 50%;
    background-color: var(--color-success);
  }
  .live-status[data-mode="poll"]::before {
    background-color: var(--color-warning);
  }
  .live-banner {
    display: grid;
    gap: 0.25rem;
    padding: 0.75rem 1rem;
    border: 1px solid var(--color-base-300);
    border-left: 6px solid var(--color-warning);
    border-radius: var(--radius-box);
    background-color: var(--color-base-100);
  }
  @media (prefers-reduced-motion: no-preference) {
    .live-changed {
      animation: live-changed 1.5s ease-out;
    }
  }
  @keyframes live-changed {
    from {
      background-color: color-mix(in oklab,
        var(--color-warning) 35%, transparent);
    }
  }

The dot beside the status is green for Live and amber while polling, and the words say the same, so colour is never the only signal. The brief highlight of a changed count is skipped for anyone whose system asks for reduced motion.

npm run build

Step 8: Watch it

Start the server:

uv run python manage.py runserver

As Sam, create and publish an event with three places that starts within two hours, so its check-in is open. Open its page in one window, signed out, and in a second window, a private one, sign in as Sai. Both pages say Live beside the title. As Sai, press Register: the first window changes from 3 of 3 to 2 of 3 places left without reloading. As Sam, in a third window, send an announcement from the event’s Announcements page: Sai’s page shows it in a banner at once; the signed-out page shows nothing. Open Check-in twice as Sam and check Sai in on one: the other’s count changes to 1 of 1. Only the count is live: the other page’s row for Sai still offers Check in until its list is searched or reloaded, and pressing it is refused as already done, under Chapter 46’s lock. Figure 54.4 shows the three.

Three screenshots. Left, at 1280 pixels, the Live clinic’s page signed out: the title with a green dot and the word Live beneath it, and Places, 2 of 3 places left, with a progress bar. Middle, on a phone, 390 pixels wide, Sai’s page: Live, and a banner with an amber edge, New from the organizers: We moved to Room 2, first floor; below it her panel says You have a place. Right, on a phone, Sam’s Check-in page: Live, and the dark count bar reading 1 of 1 checked in, above the search box and Sai’s row.
Figure 54.4 — Places, the holders’ banner, and the door’s count, as they change.

Now stop the server with Ctrl+C, with the pages still open. Each says “Updating every 30 s” and its dot turns amber. Start the server again: within a minute, each page reconnects and says Live. While it said “Updating”, its places were still asked for every 30 seconds; the browser check in Verify Your Work blocks WebSockets altogether and sees a new place appear that way, within 30 seconds.

Step 9: Access that ends

Go back to Sai’s page and, in another tab, cancel her place. Ask Sam to send another announcement: Sai’s page no longer shows it, because her own group heard “access changed” and her consumer left the holders group, as test_a_cancelled_place_stops_the_news checks. Sign out in the other tab: the WebSocket closes, and the page reconnects as a visitor, with places left only.

Step 10: Two processes

Production runs more than one server process. Keep the first server running and start a second, on another port, in a second terminal:

uv run python manage.py runserver 8001

Open the event’s page at http://127.0.0.1:8000/ in one window and at http://127.0.0.1:8001/ in another; both say Live. Take a place through the first: its window changes, and the second does not, though both show the same event from the same database. The second process’s consumers are in another process’s memory, which the first process’s in-memory channel layer cannot reach. Reload the second window and it is right again; waiting would not have helped, because its socket is open, so its polling is skipped. That is the limit Channels’ documentation warns of, and the reason Chapter 62 runs Redis: one channel layer that every process shares. Stop the second server.

Two zones, two runserver processes on ports 8000 and 8001, each with its own in-memory channel layer and an open page. A place taken through 8000 reaches the page on 8000; a red cross marks the page on 8001, which hears nothing. Below, a grey card: Chapter 62, one Redis channel layer shared by every process.
Figure 54.5 — One in-memory layer per process.

Step 11: The records

Record the design in docs/design/live.md:

# Live updates

Status: Drafted in Chapter 54, for review. Not approved.
Decision: ADR-010.

## What goes live, and to whom

- `event.<id>.public`: anyone who may see the event
  hears the places left, as counts.
- `event.<id>.holders`: members holding a place hear new
  announcements.
- `event.<id>.organizers`: those who may check people in
  hear the door's count.
- `member.<id>`: the signed-in member hears that their
  access changed, or that they signed out.

Messages are sent after the change commits, from the
model methods: `register()` (a waitlist promotion
included), a place's `cancel()`, `Event.edit()` (admin
edits included), `cancel_by()`, `announce()`, check-in
and its undo, and organizer assignments. No message names
a member.

## Fallback

If the WebSocket fails, the page says "Updating every
30 s" and htmx polls the places and the door's count
every 30 seconds. Announcements still arrive by email.

## Capacity target (an assumption, not a measurement)

One event page open in up to 300 browsers at once, on
one server process. A community report of about 200
connections on a small server is an anecdote, not
evidence. Chapter 66 measures it.

## Topology, now and at Chapter 62

Now: one process, Daphne's `runserver`, and the
in-memory channel layer, which reaches only consumers in
the same process; a second process does not hear the
first's messages.

Chapter 62: more than one server process, all using a
Redis channel layer (`channels_redis`), behind a proxy
that passes WebSocket upgrades through.

the decision as docs/adr/ADR-010-live-updates.md:

# ADR-010: Live updates on open pages

## Status

Proposed, December 2026 (Chapter 54). The choices follow
the user's decisions of 1 December 2026 (D54.1-D54.3,
N54.4-N54.6); this record is not yet reviewed or accepted.

## Context

Places left, announcements on the day, and the door's
count change while people are looking at them. A page
that shows "3 places left" when there are none sends
members to a refusal; two organizers at one door cannot
see each other's check-ins. Each update must reach only
the people allowed to see it, and stop when that changes.

## Options

- A: WebSockets with Django Channels, on the ASGI server
  of Chapter 53, with htmx polling as a fallback.
- B: server-sent events from an async streaming view;
  one-way, and simpler, but each needs its own way to
  hear about changes from other requests.
- C: polling only, every 30 seconds.

## Decision

A, in the live app: one consumer per open event page,
four kinds of group (public, holders, organizers, and
one per member), messages sent after commit from the
model methods, and the in-memory channel layer until
Chapter 62 runs Redis. Channels 4.3.2 does not yet
declare Django 6.1; the suite passes with it, and it is
checked again at its next release or at Chapter 62.

## Consequences

- Access is checked on connect and again whenever a
  member's place or role changes; signing out closes the
  socket.
- A WebSocket must come from one of `ALLOWED_HOSTS`;
  scripts use the API instead.
- One process only until Redis: two `runserver`s do not
  hear each other.
- Chapter 59's CSP allows `connect-src` for the site's
  own `ws:` and `wss:` addresses.
- Revisit if the 300-page target (docs/design/live.md)
  is not met at Chapter 66.

and close the fourth milestone with its trace, docs/acceptance/M4.md, which names the tests that prove each of its acceptance checks from Chapters 47 to 54:

# M4 acceptance trace: API integration

Chapters 47 to 54. The milestone's scenario: a partner's
script lists Otahque's published events and is told by a
webhook when one changes; open pages follow changes live.
Each acceptance check, the cases that prove it, and the
tests that check each case. Names are `Class.test_name`;
the app is in brackets. `TraceTests` (config) fails if a
named test is missing.

Evidence: `check.py` passes on PostgreSQL. Not reached
until the author's review: drafted in Chapter 54.

## Unpublished events never appear

- A draft is answered as an unknown id, and no member
  data is shown (api):
  `DetailTests.test_a_draft_is_like_an_unknown_id`,
  `DetailTests.test_no_member_data`
- Another organizer's draft is hidden from writes too
  (api):
  `AccessTests.test_another_organizers_draft_is_404`
- Drafts and dry runs send no webhook (integrations):
  `MessageTests.test_drafts_and_dry_runs_send_nothing`
- A hidden draft's live updates are refused (live):
  `ConsumerTests.test_a_hidden_draft_is_refused`

## Pagination is bounded

- Twenty to a page, then the rest; nothing repeated when
  an event is added meanwhile; a made-up cursor is 404
  (api):
  `PageTests.test_twenty_then_five`,
  `PageTests.test_an_event_added_meanwhile_repeats_nothing`,
  `PageTests.test_a_made_up_cursor_is_404`

## Access and limits

- Writes need a token or a session, each action its scope
  (api):
  `AccessTests.test_a_visitor_gets_401`,
  `BearerTests.test_a_token_in_the_address_is_400_unchecked`,
  `ScopeTests.test_each_action_needs_its_scope`
- Each caller has a rate, answered with 429 (api):
  `ThrottleTests.test_a_visitor_gets_60_a_minute`,
  `ThrottleTests.test_each_token_has_its_own_count`

## The client handles timeouts and retries safely

- Timeouts and 503 are tried again, 429 waits as told,
  other errors are not retried, and a write is sent once
  (api):
  `ClientTests.test_timeouts_and_503_are_tried_four_times`,
  `ClientTests.test_429_waits_as_told`,
  `ClientTests.test_other_errors_are_not_retried`,
  `ClientTests.test_a_write_is_sent_once`

## Invalid and replayed webhooks are rejected

- A wrong secret, a changed body, or an old timestamp is
  refused; the same message twice is applied once
  (integrations):
  `ReceiverTests.test_a_wrong_secret_is_refused`,
  `SigningTests.test_a_changed_body_is_refused`,
  `ReceiverTests.test_an_old_message_is_refused`,
  `ReceiverTests.test_the_same_message_twice_is_applied_once`
- Messages are sent after commit, never for a rollback
  (integrations):
  `MessageTests.test_sending_waits_for_the_commit`

## Webhooks never reach inside the network

- Inner addresses are refused at save and before every
  send, redirects are not followed, Send test included
  (integrations):
  `AddressTests.test_inner_addresses_are_refused`,
  `SendingTests.test_an_inner_address_now_is_never_called`,
  `SendingTests.test_a_redirect_is_a_failure_not_followed`,
  `TrialTests.test_an_inner_address_is_never_called`

## Live updates reach only those allowed

- Places left for everyone, counts only; news for members
  holding places; the door's count for organizers (live):
  `ConsumerTests.test_a_visitor_hears_places_left`,
  `MessageTests.test_the_public_message_holds_counts_only`,
  `ConsumerTests.test_only_holders_hear_announcements`,
  `ConsumerTests.test_only_organizers_hear_the_door`
- Another site's page cannot connect (live):
  `ConsumerTests.test_another_site_or_no_origin_is_refused`
- Access that ends while connected ends the updates; a
  rollback tells nobody (live):
  `ConsumerTests.test_a_cancelled_place_stops_the_news`,
  `ConsumerTests.test_signing_out_closes_the_socket`,
  `MessageTests.test_a_rollback_tells_nobody`

## Demonstration

With `runserver` and `db_worker` running:

1. Page through the published events with
   `uv run python examples/otahque_client.py` (Chapter
   51): twenty, then the rest.
2. Start `examples/receiver.py` with the library
   endpoint's secret and press Send test (Chapter 53):
   Sent, 200.
3. Edit a published event: the receiver prints
   `event.changed`; replaying the same message is
   answered "seen before; ignored" (Chapter 52).
4. Open the event in two windows and take a place in
   one: the other's places left changes without a reload
   (Chapter 54).

## Known limitations

No production deployment. Throttling is not
denial-of-service protection. The in-memory channel
layer reaches one process only (Redis at Chapter 62).
Channels 4.3.2 does not yet declare Django 6.1 support;
the suite passes with it.

config/tests/test_acceptance.py checks that every test a trace names exists. Its top now searches the API’s apps too:

# Chapter 46: the trace for the third milestone.
M3 = settings.BASE_DIR / 'docs/acceptance/M3.md'
# Chapter 54: the fourth, across the API's apps.
M4 = settings.BASE_DIR / 'docs/acceptance/M4.md'
APPS = ['accounts', 'api', 'audit', 'config', 'events',
        'integrations', 'live', 'registrations']

and its last test checks the new trace:

    def test_every_m3_test_exists(self):
        count, absent = missing(M3)
        self.assertGreater(count, 20)
        self.assertEqual(absent, [])

    def test_every_m4_test_exists(self):
        count, absent = missing(M4)
        self.assertGreater(count, 30)
        self.assertEqual(absent, [])

Chapter 45 promised to look at htmx 4 again by this chapter. npm’s default is still htmx 2.0.11, with 4.0.2 only under its next tag, and django-htmx has not moved, so Otahque stays on 2.0.11 until the Django 6.2 upgrade. In docs/design/htmx.md, the note ends:

- htmx 4 is out (August 2026) but npm's default is still
  2.x, which the htmx project supports. Revisit when npm's
  default or django-htmx's moves to 4, at the latest at
  the Django 6.2 upgrade. Checked in Chapter 54: npm's
  default was still 2.0.11 (4.0.2 under `next`).
uv run python manage.py test config.tests.test_acceptance
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK

Step 12: The checks, and the commit

uv run python check.py
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 810 test(s).
System check identified no issues (0 silenced).
Ran 810 tests in ...s
OK
== all checks passed
git add .
git status --short
git commit -m "Keep open pages up to date over WebSockets"
M  config/asgi.py
M  config/settings.py
M  config/tests/test_acceptance.py
A  docs/acceptance/M4.md
A  docs/adr/ADR-010-live-updates.md
M  docs/design/htmx.md
A  docs/design/live.md
M  events/models.py
M  events/templates/events/detail.html
M  events/templates/events/facts.html
M  events/tests/test_emails.py
M  events/views.py
A  live/__init__.py
A  live/admin.py
A  live/apps.py
A  live/consumers.py
A  live/groups.py
A  live/migrations/__init__.py
A  live/models.py
A  live/routing.py
A  live/tests/__init__.py
A  live/tests/test_consumers.py
A  live/tests/test_messages.py
A  live/tests/test_pages.py
A  live/views.py
M  pyproject.toml
M  registrations/models.py
M  registrations/templates/registrations/door.html
M  registrations/tests/test_panel.py
M  registrations/views.py
A  static/live/live.js
M  static/otahque/site.css
M  static/otahque/source.css
M  templates/base.html
M  uv.lock
[main 1a2b3c4] Keep open pages up to date over WebSockets
 35 files changed, 1144 insertions(+), 34 deletions(-)
 create mode 100644 docs/acceptance/M4.md
 create mode 100644 docs/adr/ADR-010-live-updates.md
 create mode 100644 docs/design/live.md
 create mode 100644 live/__init__.py
 create mode 100644 live/admin.py
 create mode 100644 live/apps.py
 create mode 100644 live/consumers.py
 create mode 100644 live/groups.py
 create mode 100644 live/migrations/__init__.py
 create mode 100644 live/models.py
 create mode 100644 live/routing.py
 create mode 100644 live/tests/__init__.py
 create mode 100644 live/tests/test_consumers.py
 create mode 100644 live/tests/test_messages.py
 create mode 100644 live/tests/test_pages.py
 create mode 100644 live/views.py
 create mode 100644 static/live/live.js

If something goes wrong

Table 54.2 — Recovery for Chapter 54
What you see Likely cause What to do
The page says Updating every 30 s and never Live No WebSocket route, or Daphne is not the server Check config/asgi.py; runserver must say ASGI/Daphne
The socket closes at once; WSREJECT in the server log Origin not in ALLOWED_HOSTS Open the page by a host in ALLOWED_HOSTS, such as 127.0.0.1
Connected, but no updates A misspelled group, or the change did not commit Use live/groups.py's functions; check the commit
Updates reach one window, not another Two server processes, in-memory layer Use one runserver; Redis at Chapter 62
AppRegistryNotReady in config/asgi.py Imports before get_asgi_application() Call it first, as in Step 5
Consumer tests hang A socket left open Use the closing() decorator
A Python 3.14 error from ChannelsLiveServerTestCase Channels issue 2240 Use runserver and a real browser instead
PAGE 003

Verify Your Work

Work through Table 54.3 from the folder that holds manage.py, with Otahque on PostgreSQL.

Table 54.3 — Verification checklist for Chapter 54
Check Command or action Expected result
Starting point test --parallel Found 789 test(s); OK
Channels uv add channels==4.3.2 channels 4.3.2 installed
After commit test live.tests.test_messages Errors first; then 9 tests OK
The earlier email test test events.tests.test_emails 4 != 1 first; then OK
The consumer test live.tests.test_consumers Errors first; then 7 tests OK
The pages test live.tests.test_pages; test_panel Errors first; then 4 tests OK; OK
Live in a browser runserver; three windows 2 of 3 without a reload; the banner for Sai only; the door's count shared
Fallback WebSocket blocked; server stopped and started Updating every 30 s; a new place within 30 s; Live again
Two processes runserver and runserver 8001 Only the first server's page changes
The trace test config.tests.test_acceptance 3 tests OK
All checks uv run python check.py == all checks passed; Ran 810 tests
Commit git log --oneline -1 Keep open pages up to date over WebSockets
Not verified Several server processes on Redis; a proxy in front; 300 open pages; macOS and Linux shells Chapters 62 and 66

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 53 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once. Steps 8 to 10 ran for real in Microsoft Edge against Daphne’s runserver, with a new event, “Live clinic”, made for them and kept in the reader’s database: a signed-out page at 1280 pixels followed Sai’s registration from 3 of 3 to 2 of 3 without a reload; Sam’s announcement from the Announcements page reached Sai’s banner at 390 pixels and not the signed-out page; a check-in on one door page changed the other’s count; a page whose WebSocket was blocked said “Updating every 30 s” and showed Raj’s new place by polling; and with a second runserver on another port, Raj’s cancellation reached the page on the first server only, and the second after a reload. No page scrolled sideways, and every control was named.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 What does a WebSocket let Otahque do that a page over plain HTTP cannot?

Flip to check your answerFold answer back

Answer. Send the browser a message when something changes, without the browser asking: the connection stays open in both directions until one side closes it.

Que. 2 Why is places_changed() sent with on_commit(), and what does a rolled-back registration send?

Flip to check your answerFold answer back

Answer. So pages hear only of changes that happened, and read counts that include them. A rolled-back registration sends nothing: its callbacks are discarded with the transaction.

Que. 3 Sai cancels her place in one tab while her event page is open in another. What does that page stop receiving, and how?

Flip to check your answerFold answer back

Answer. Announcements. cancel() sends “access changed” to Sai’s own group after commit; her consumer checks again, finds no place, and leaves the holders group.

Que. 4 Why can a script not open Otahque’s WebSocket, and what should it use instead?

Flip to check your answerFold answer back

Answer. AllowedHostsOriginValidator refuses a connection whose Origin header is missing or names a host outside ALLOWED_HOSTS, as a script’s is. Scripts use the API (Chapters 47 to 51).

Que. 5 Two server processes share one database. Why does a place taken through one not update a page connected to the other?

Flip to check your answerFold answer back

Answer. The in-memory channel layer lives in one process’s memory, so the other process’s consumers never hear the message. A shared layer, Redis in Chapter 62, reaches every process.

Mini-Challenge

An organizer who is removed from an event must stop seeing its door count at once, not when the page closes. Write a test, in live/tests/test_removed.py, in which a second organizer’s page is connected, the administrator revokes their assignment, Sai then registers, and the removed organizer’s page hears the places but not the door.

Hint: reuse ConsumerTests’ open() and register() by subclassing it, and remember that the subclass runs every inherited test too, so run only yours with -k and part of its name; assignment.revoke(by) needs another organizer still in place.

Model answer:

"""A removed organizer stops hearing the door (54 challenge)."""
from asgiref.sync import sync_to_async

from config.helpers import in_group
from live.tests.test_consumers import ConsumerTests, closing


class RemovedTests(ConsumerTests):
    """Losing the role while connected ends the door's count."""

    @closing
    async def test_a_removed_organizer_hears_no_door(self):
        raj = await sync_to_async(in_group)(
            'raj@example.org', 'Organizers')
        assignment = await sync_to_async(
            self.event.add_organizer)(raj)
        _, socket = await self.open(raj)
        await sync_to_async(assignment.revoke)(self.sam)
        self.assertEqual(await socket.receive_json_from(),
                         {'type': 'access'})
        await self.register(self.sai)
        places = await socket.receive_json_from()
        self.assertEqual(places['type'], 'places')
        self.assertTrue(await socket.receive_nothing())
uv run python manage.py test live.tests.test_removed -k hears_no
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK

revoke() sends “access changed” to the removed organizer’s own group; the consumer checks again, can_check_in() now answers no, and it leaves the organizers group before Sai’s registration is sent. The model answer was run and then removed; the chapter’s checkpoint does not include it.

What We Learned

  • A WebSocket keeps a connection open both ways, so the server can speak first; polling every 30 seconds is the fallback.
  • Channels adds consumers for connections, routes WebSockets beside HTTP in config/asgi.py, and reads the member from the session.
  • Groups gather open pages; one message to a group reaches them all, through the channel layer.
  • Send after commit, from the model methods every change goes through, with counts, never names.
  • Check access when a page connects and again whenever it changes; close on sign-out; refuse other sites’ pages by their Origin.
  • The in-memory channel layer reaches one process; production needs a shared layer.
  • The fourth milestone is traced: every acceptance check names the tests that prove it.

Key terms

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

Table 54.4 — Key terms from Chapter 54
Term Meaning
WebSocket A connection that stays open, with messages both ways.
Consumer Channels' class for one connection: connect, messages, disconnect.
Channel The name a single consumer receives messages at.
Group A set of channels that one message reaches.
Channel layer The shared mailbox that carries messages to channels and groups.
Origin check Refusing a WebSocket opened from another site's page.
Polling Asking again on a timer; here, every 30 seconds as a fallback.
Backoff with jitter Waiting longer after each failure, by a random part, before reconnecting.
Server-sent events A response that stays open and carries messages from the server only.
Acceptance trace Each milestone check, with the tests that prove it.

Readiness checkpoint: you are ready for Chapter 55 when uv run python check.py ends with “all checks passed” and 810 tests, an event’s page says Live and follows a registration in another window, and git log --oneline -1 shows this chapter’s commit. The fourth milestone, API integration, is drafted with its trace in docs/acceptance/M4.md; it is reached when the author’s review accepts it.

Git Commit

Your Chapter 54 work was committed once, in Step 12, as “Keep open pages up to date over WebSockets”: the live app with its groups, consumer, routing, and tests; config/asgi.py and the settings; the events and registrations models, views, and templates; the base template; static/live/live.js, the stylesheet, and the compiled CSS; the two earlier tests and the acceptance test; pyproject.toml and uv.lock; the design note, ADR-010, and the trace. If you kept the Mini-Challenge, commit it on its own:

git add live/tests/test_removed.py
git commit -m "Check a removed organizer stops hearing the door"
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 updates that reach only half the users once there are two servers, and to defending polling as part of the design. They are extension questions, not a gate to the next chapter. Each code proof is a run from this chapter’s steps.

L1 (Junior): Why use a WebSocket for live updates instead of polling?

What the interviewer is testing: Can you compare the two honestly, cost and benefit?

Flip to check your answerFold answer back

Perfect answer: Polling asks on a timer, so a page is as old as the interval, and most requests find nothing new; at 300 pages and every 2 seconds, that is 150 requests a second for an event that changes a few times a minute. A WebSocket keeps one connection open per page, and the server sends a message only when something changes, within a moment. It costs an ASGI server that holds connections, a channel layer, and care over who hears what. Otahque uses both: WebSockets for places, announcements, and the door’s count, and polling every 30 seconds when a WebSocket cannot connect.

Table 54.5 — Polling and a WebSocket
Question Polling WebSocket
Who speaks first The browser Either side
How late Up to one interval A moment
Cost when nothing changes Every request An idle connection
Needs Any server ASGI and a channel layer

Behind the scenes:

GET /ws/events/7/  Upgrade: websocket   -> 101
server -> {"type": "places", "left": 2, ...}

Code proof: the consumer’s tests, from Step 5:

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

OK

Common mistakes:

  • Polling every second to look live, and calling the load “traffic”.
  • Dropping the fallback, so a blocked WebSocket leaves a page silently stale.

Follow-up the interviewer might ask:

  • When would server-sent events be enough? (One-way updates, with some other way to tell every open response about a change.)

L2 (Mid-Level): A registration sends its message, then the transaction rolls back. Predict what pages show

What the interviewer is testing: Do you know why messages wait for the commit?

Flip to check your answerFold answer back

Perfect answer: If the message were sent inside the transaction, every page would show one place fewer for a place that never existed, and any page that then asked for the count would read the old number, so pages would disagree with each other and with the database. In Otahque that cannot happen: places_changed() registers the send with transaction.on_commit(), so a rollback discards it, and the message is made after the commit, so its count includes the change. The proof is test_a_rollback_tells_nobody, which takes a place inside a transaction that rolls back and records no message at all.

A numbered flow of five cards. 1, register() saves a place inside a transaction. 2, places_changed() waits for the commit. 3, the transaction rolls back. 4, the waiting send is discarded. 5, pages keep the right count.
Figure 54.6 — A message that waits for the commit.

Behind the scenes:

atomic:  register()   on_commit(send)  rollback
         -> callbacks discarded: nothing sent

Code proof: the message tests, from Step 4:

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

OK

Common mistakes:

  • Sending from the view after save(), inside the request’s transaction.
  • Putting the count in the message before the commit, so it is one behind.

Follow-up the interviewer might ask:

  • How do you test it in a TestCase, which never commits? (captureOnCommitCallbacks(execute=True) runs what was waiting; a TransactionTestCase commits for real.)

L3 (Senior): Defend checking access again after a WebSocket connects

What the interviewer is testing: Can you reason about authorization over a long-lived connection?

Flip to check your answerFold answer back

Perfect answer: A page can stay open for hours, and access is not fixed for that long. A member cancels in another tab, an organizer is removed by the administrator, someone signs out on a shared computer. Checking only on connect would keep sending them what they no longer may see: announcements meant for holders, or a door count meant for organizers. So every change to access sends “access changed” to the member’s own group after commit; the consumer runs the same check as on connect, leaves the groups it may no longer hear, and joins any new ones; sign-out closes the connection. Messages carry counts, never names, so even the public group leaks nothing about members. The tests open real sockets through the origin check and session and prove each case.

A numbered flow of five cards. 1, need: access can end while a page is open. 2, check on connect, by the page’s rules. 3, a change sends access changed to member.id. 4, the consumer checks again and leaves groups. 5, sign-out closes the socket.
Figure 54.7 — Access checked again while connected.

Behind the scenes:

cancel()    -> member.12: access.changed
consumer    -> allowed_groups(): no holders
group_discard('event.7.holders', channel)

Code proof: the same consumer tests, including a cancelled place and a sign-out:

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

OK

Common mistakes:

  • Checking once on connect and trusting the connection for its lifetime.
  • Putting names or emails in a public group’s messages because “only the page shows it”.

Follow-up the interviewer might ask:

  • What if the access check itself is slow? (It runs once per change for that member’s pages only, through database_sync_to_async, off the event loop.)

L4 (Staff): After a deploy with two servers, live updates reach only some users. Diagnose it

What the interviewer is testing: Can you connect a partial failure to where state lives?

Flip to check your answerFold answer back

Perfect answer: “Some users” with two servers points at state held per process. The first thing I would check is the channel layer: with InMemoryChannelLayer, each process has its own groups, so a message sent while handling a request on server A reaches only pages connected to server A; users on B see updates only when their page reloads. I would confirm by opening the same event through each server directly, as Step 10 did with two ports, and taking a place through one. The fix is a shared layer: channels_redis, where every process’s groups live in Redis, which Chapter 62 sets up with the production servers. Until then the honest setting is one process, and the design note says so.

A numbered flow of five cards. 1, symptom: some pages update, some do not. 2, two server processes since the deploy. 3, an in-memory layer per process. 4, confirm: one event through each server. 5, fix: one Redis layer for all, Chapter 62.
Figure 54.8 — Diagnosing updates that reach half the users.

Behind the scenes:

process A: groups {event.7.public: [a1, a2]}
process B: groups {event.7.public: [b1]}
place taken on A -> a1, a2; b1 hears nothing

Code proof: Step 10’s two servers, in the browser:

1280 same process: 2 of 3
1280 other process: still 1 of 3 after 5 s
1280 other process after a reload: 2 of 3

Common mistakes:

  • Blaming the browser or the proxy first, because the failure looks random.
  • Using sticky sessions to hide it, which still splits one event’s pages across servers.

Follow-up the interviewer might ask:

  • What else is kept per process in Otahque? (Chapter 51’s throttling counts, in the local-memory cache, until Chapter 57’s shared cache.)

L5 (Lead): Defend polling as part of the real-time design

What the interviewer is testing: Can you design for failure, and defend a less exciting choice?

Flip to check your answerFold answer back

Perfect answer: WebSockets fail for ordinary reasons: a network or proxy that blocks them, a server restart that drops every connection, a laptop waking from sleep. A design without a fallback turns each of those into a page that is silently wrong. Otahque’s fallback is deliberately plain: each live part of a page asks for itself every 30 seconds with htmx, using the same partial the page renders, and the label says “Updating every 30 s”, so nobody mistakes it for live. While the socket is open, the polling is skipped, so it costs nothing. Reconnection backs off with jitter, so a restart does not bring every page back in the same second. And the things that must be right, a place, a check-in, are decided by the server under its locks whatever a page shows. I would keep the fallback even after Redis and proxies are in place, and measure both paths at Chapter 66.

A numbered flow of five cards. 1, need: pages stay right when sockets fail. 2, the same partial, asked for every 30 s. 3, the label says Updating every 30 s. 4, reconnect with backoff and jitter. 5, the server’s locks decide; pages only show.
Figure 54.9 — Polling as the fallback.

Behind the scenes:

socket open    htmx:beforeRequest on [data-poll] -> cancelled
closed  GET /events/7/, HX-Target places-left, every 30 s
reconnect      after 1-2 s, 2-4 s, ... up to 60 s

Code proof: the browser checks, a blocked WebSocket included:

1280 the visitor page says Live, 3 of 3
1280 without a reload, the visitor sees 2 of 3
390 Sai sees the banner
1280 the visitor sees no banner
390 the door starts at 0 of 1
390 the other door page shows 1 of 1 without a reload
1280 without a socket: Updating every 30 s
1280 polling shows 1 of 3 within 40 s

Common mistakes:

  • Reconnecting immediately and forever, so a restart is met by every page at once.
  • A fallback that renders the page differently from the live path, so the two drift.

Follow-up the interviewer might ask:

  • Why does the fallback not cover announcements? (They also arrive by email, since Chapter 44; a banner is a convenience on top.)

Next: Chapter 55, Advanced ORM and database expressions, opens the stage on performance, security, and production, starting with the queries Otahque asks its database.

PAGE 006