Skip to main content

django-pg-sse

Documentation: https://django-pg-sse.readthedocs.io/, with the settings, a deployment guide and an API reference.

Server-sent events for Django over PostgreSQL LISTEN/NOTIFY. Push HTML from any process to the open browsers of a topic, with replay after a reconnect. No Redis, no message broker.

Built for htmx 4 and its hx-sse extension, but any SSE client works.

Requirements

  • Python 3.12 or newer, Django 5.2 or newer
  • PostgreSQL and psycopg 3.3.9 or newer
  • Middleware that sets request.user, such as AuthenticationMiddleware; the check pg_sse.W001 warns without it. A session is optional: without one, close_streams(session=...) reaches no stream.
  • An ASGI server such as granian, uvicorn or daphne. runserver speaks WSGI and cannot stream an async response.

Installation

uv add django-pg-sse
INSTALLED_APPS = [
    # ...
    "django_pg_sse",
]
# urls.py
urlpatterns = [
    # ...
    path("events/", include("django_pg_sse.urls")),
]

Run manage.py migrate to create the event table.

Usage

Send HTML to a topic. The event goes out when the current transaction commits; a rollback sends nothing. A topic has at most 200 characters and an event name at most 100; broadcast() raises ValueError for longer ones.

from django_pg_sse import broadcast

html = '<ul id="news" hx-swap-oob="beforeend"><li id="news-7">Hi</li></ul>'
broadcast("public:news", html)

A page opens one stream for all its topics:

<ul id="news"></ul>
<div hx-sse:connect="{% url 'pg_sse:stream' %}?topic=public:news{% if user.is_authenticated %}&topic=user:{{ user.pk }}{% endif %}"></div>

The default policy opens public: topics to everyone and user:<pk> to that user. Other kinds, such as room:, need a policy of their own; see Who may read a topic.

htmx swaps each message. Elements with hx-swap-oob or <hx-partial> update the page anywhere. Give list items stable ids, so an event delivered twice replaces its element instead of adding one.

From async code

broadcast(), broadcast_json() and close_streams() register with transaction.on_commit(). Django allows that only in sync code; async code gets SynchronousOnlyOperation. Async code awaits abroadcast(), abroadcast_json() and aclose_streams() instead.

from django_pg_sse import abroadcast


async def post_message(request, room_pk):
    message = await Message.objects.acreate(room_id=room_pk, text=request.POST["text"])
    await abroadcast(f"room:{room_pk}", render_to_string("chat.html#message", {"message": message}))

JSON for client code

broadcast_json() sends a value as JSON, encoded with DjangoJSONEncoder. It needs an event name.

from django_pg_sse import broadcast_json

broadcast_json(f"room:{room.pk}", {"online": 12}, event="presence")

htmx dispatches a named event as a DOM event on the element with hx-sse:connect. The event bubbles, and event.detail.data holds the text. broadcast() refuses the event names closed and hx:release, which end or release the stream.

document.body.addEventListener("presence", (event) => {
  const { online } = JSON.parse(event.detail.data);
});

Without htmx, EventSource.addEventListener("presence", ...) receives the same event.

Who may read a topic

PG_SSE["CAN_SUBSCRIBE"] names a function (request, topic) -> bool. The default opens public: topics to everyone and user:<pk> to that user, and closes every other kind. Topics starting with _ are reserved for the package, such as the topics close_streams() writes to. The view answers a request for them with a 403, before it calls CAN_SUBSCRIBE. broadcast() raises ValueError for them.

PG_SSE = {"CAN_SUBSCRIBE": "myproject.events.can_subscribe"}
from django_pg_sse.permissions import can_subscribe as default


def can_subscribe(request, topic):
    kind, _, key = topic.partition(":")
    if kind == "room":
        return request.user.is_authenticated and Membership.objects.filter(room=key, user=request.user).exists()
    return default(request, topic)

The check runs when a stream opens. After taking access away, call close_streams():

from django_pg_sse import close_streams

close_streams(user=user)  # every stream of the user
close_streams(session=request.session)  # the streams of one session

Each stream receives an event named closed and ends. htmx reconnects, and the check runs again. Add hx-sse:close="closed" to a stream element that should stop instead. Logging out closes the streams of that session, so other tabs lose the user's topics.

Replay

Every event is stored. A reconnecting browser sends Last-Event-ID and receives what it missed. Event ids are signed with SECRET_KEY for the user, the session and the topics of the stream. An unsigned id, or one signed for another stream, replays nothing; the stream starts with live events. A close_streams() for the owner after the id also skips the replay. The events from the time without access then stay unread. Run manage.py prune_stream_events regularly, for example hourly; it deletes events older than PG_SSE["RETENTION_HOURS"] (default 24).

Signals

django_pg_sse.signals sends stream_opened when a stream's subscription is in place. It sends stream_closed when that stream ends, also after a disconnect during stream_opened. A process that is killed sends no stream_closed, so presence built on it needs a timeout. Both signals pass sender=StreamInfo and a stream argument, a StreamInfo with these fields:

  • id: a new random id for each connection
  • user_pk: the user's primary key as a string, or None for an anonymous stream
  • session: the SHA-256 digest of the session key, or None for an anonymous stream
  • topics: the topics of the stream
from django.dispatch import receiver
from django_pg_sse.signals import stream_opened


@receiver(stream_opened)
def count_stream(sender, stream, **kwargs):
    metrics.increment("sse.streams", tags={"user": stream.user_pk is not None})

The stream waits for its receivers, so keep them short. A receiver that raises is logged to django.dispatch, and the stream goes on.

Database connections

The deployment guide covers sizing, timeouts, proxies and shutdown in more detail.

The hub's connections use the alias in PG_SSE["DATABASE"] (default "default"), outside Django's connection pool. Each ASGI worker holds one for LISTEN, one for live delivery and a pool for opening streams. PG_SSE["STREAM_CONNECTIONS"] (default 4) caps that pool. A worker therefore holds up to 2 + STREAM_CONNECTIONS connections.

  • They take its host, port, user, password and the libpq OPTIONS, such as sslmode, service, passfile, application_name and prepare_threshold.
  • They apply OPTIONS["assume_role"] with SET ROLE.
  • pool, isolation_level and server_side_binding do not apply. The hub runs in autocommit.
  • LISTEN needs a session. A PgBouncer in transaction mode cannot carry it. With such a PgBouncer, give the hub an alias that reaches PostgreSQL directly. The alias must reach the same database as default, which broadcast() writes to.
  • They add libpq defaults for connect_timeout, keepalives and tcp_user_timeout. Settings lists them; a key in OPTIONS replaces its default.

How it works

  • broadcast() writes the event after the commit, in a short transaction that holds an advisory lock. Event ids therefore become visible in order, which keeps the replay exact.
  • NOTIFY carries only the id and the topic, so the 8000-byte payload limit does not apply.
  • The number of connections per ASGI worker does not grow with the number of open streams. Open streams hold no connection from Django's pool.
  • A listener that loses its connection reconnects and loads the events it missed from the table.
  • After 30 seconds without a NOTIFY, the listener sends SELECT 1 and waits up to 10 seconds. Without an answer, it reconnects; psycopg can add up to 10 seconds while it cancels the query. This replaces a half-open LISTEN connection, such as after a failover, within about a minute.
  • A query on the other connections gives up after PG_SSE["QUERY_TIMEOUT"] (default 30) seconds. psycopg can add up to 10 seconds while it cancels the query. If the server does not answer, the query runs once more on a new connection, with the same limits.
  • A query on a connection that a database restart ended runs once more on a new connection.
  • The view opts out of ATOMIC_REQUESTS, which Django does not allow for async views.
  • close_streams() stores an event on a close topic of the user or the session. Only a process with a stream of that owner acts on it, and it needs no query.
  • A close topic holds a SHA-256 digest of the user's primary key or the session key.

Compared to django-eventstream

django-eventstream also serves server-sent events from Django. It shares no code or API with this package. This comparison refers to its release 5.3.4.

django-pg-sse supports PostgreSQL only and ASGI only. In return it needs no other service.

django-pg-sse django-eventstream
Delivery across processes PostgreSQL LISTEN/NOTIFY Redis pub/sub or a GRIP proxy such as Pushpin; otherwise the sending process only
Sending After the transaction commits; a rollback sends nothing At once, without on_commit
Storage Every event Optional, per channel
Event ids One sequence, in commit order across all topics One counter per channel
Last-Event-ID Signed for the user, the session and the topics Chosen by the client
Stream lifecycle stream_opened and stream_closed signals None
Revoking access close_streams() for a user or a session, in every process channel_permission_changed() for a user and a channel, in the calling process and at a GRIP proxy
Payload HTML for htmx, JSON for client code, or any text JSON by default, or any text
Servers ASGI ASGI, or WSGI behind a GRIP proxy

django-eventstream with Pushpin or Fanout holds the open connections outside Django. That scales to more concurrent connections than an ASGI worker holds. Without such a proxy, both packages hold each open stream in an ASGI worker.

django-pg-sse serialises broadcast() through an advisory lock, so the events per second have a lower ceiling than with Redis.

License

MIT

Metadata

Release files for django-pg-sse 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-pg-sse 0.1.0
File Size Uploaded Provenance Actions
django_pg_sse-0.1.0.tar.gz 74.0 kB With provenance Details for django_pg_sse-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-pg-sse 0.1.0
File Interpreter ABI Platform Actions
django_pg_sse-0.1.0-py3-none-any.whl Python 3 none any Details for django_pg_sse-0.1.0-py3-none-any.whl

Total release size: 103.0 kB

Release files / django_pg_sse-0.1.0.tar.gz

Download URL django_pg_sse-0.1.0.tar.gz
Size 74.0 kB
Tags Source
SHA-256 checksum
How to use checksums
8dc4f85013cce190c756c277f0f09202a7d591f2fb023ee024d8c7c6c8369970
BLAKE2b-256 checksum
How to use checksums
57d7cce46c88978562a58b4f38237d0e72dd031cc3ee1878c4d72ae250aaae36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / django_pg_sse-0.1.0-py3-none-any.whl

Download URL django_pg_sse-0.1.0-py3-none-any.whl
Size 29.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3ae40307ab349a9ed21f784bc078260b4ceeb81cb732e6d77c0c18c25c732e47
BLAKE2b-256 checksum
How to use checksums
0d4104a1d3cead4c92d731b7e5111f7d5695f2d6849edc29ae07a9b8d7357bdc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for django-pg-sse 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_pg_sse-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page