django-pgpubsub
django-pgpubsub copied to clipboard
Fixes potential races during LISTEN initiation
While working on a https://github.com/PaulGilmartin/django-pgpubsub/pull/81 I've noticed that the LISTEN initiation does not follow the guidelines from the https://www.postgresql.org/docs/current/sql-listen.html.
Here's the quote:
There is a race condition when first setting up a listening session: if concurrently-committing transactions are sending notify events, exactly which of those will the newly listening session receive? The answer is that the session will receive all events committed after an instant during the transaction's commit step. But that is slightly later than any database state that the transaction could have observed in queries. This leads to the following rule for using LISTEN: first execute (and commit!) that command, then in a new transaction inspect the database state as needed by the application logic, then rely on notifications to find out about subsequent changes to the database state. The first few received notifications might refer to updates already observed in the initial database inspection, but this is usually harmless.
So this MR wraps LISTEN
into a transaction to avoid races namely lost notifications while the listener is starging.