simplebroker-pg
Postgres backend plugin for SimpleBroker.
This package is intentionally separate from simplebroker itself. SimpleBroker
remains SQLite-first. This package adds a Postgres backend through the public
backend plugin hook.
Requirements
- Python 3.11+
- PostgreSQL
- A dedicated schema for SimpleBroker tables
Standard, GIL-enabled CPython 3.15 is supported, with native PostgreSQL CI coverage on Linux. This qualification does not cover free-threaded Python 3.15t or JIT-specific behavior.
public is intentionally rejected.
Exact-target broadcast requires backend API v5: SimpleBroker 5.6.1 or newer
and simplebroker-pg 3.3.1 or newer. Default selection intersects requested
names with existing queues. Python create_missing=True instead inserts into
the complete requested set, intentionally recreating a queue deleted before
the broadcast lock is acquired. Selection and insertion occur in one
PostgreSQL transaction.
SimpleBroker 7.1.0 and simplebroker-pg 3.6.0 are the first coordinated
backend API v6 set, which adds terminal activity-waiter close. Package
dependency floors are minimums; the exact runtime handshake remains
authoritative for every installed pair.
SimpleBroker 7.3.0 and simplebroker-pg 3.8.0 are the first coordinated
backend API v7 set. It adds the required monotone durable high-water advance
used by persistence restore. Package dependency floors remain minimums; the
exact runtime handshake remains authoritative for every installed pair.
SimpleBroker 8.0.0 and simplebroker-pg 4.0.0 are the first coordinated
backend API v8 set. It adds bounded public-ID selection order and SQL storage
schema v6. Package dependency floors remain minimums; the exact runtime
handshake remains authoritative for every installed pair.
SimpleBroker 8.1.0 and simplebroker-pg 4.1.0 are the first coordinated
backend API v9 set. It adds the atomic write-time keep_newest pending window.
PostgreSQL locks the high-water metadata row and then takes a transaction-
scoped SHARE ROW EXCLUSIVE lock on messages before insert and trim. A large
first trim therefore stalls row mutations on unrelated queues; measured
100k/220k displaced rows took about 425/1000 ms on PostgreSQL 18. Cost is
linear in displaced rows and has no bounded-time guarantee.
An ordinary generated write (no keep_newest) is one pipelined PostgreSQL
transaction: it locks the high-water metadata row, allocates the larger of the
client's candidate and last_ts + 1, inserts, notifies, and commits, without
waiting on the client in between. The row lock therefore covers only server
execution and the commit, and a stale candidate never retries. Generated rows
still commit in message-ID order, and an exhausted logical counter still
refuses allocation until the clock catches up. This requires a SimpleBroker
core that probes the optional write_generated_message backend hook;
libpq 14 or newer provides pipeline mode, and older libpq runs the same
statements in an explicit transaction.
Persistent Queues for one process-session target share one bounded connection
pool. Each operation borrows a checkout and returns it when the operation
finishes. A transaction or suspended iterator retains its checkout until it
commits, rolls back, or closes; an idle thread-local core consumes no pool slot.
Normal Queue operations and BrokerSession.connection() manage this
automatically. Applications do not check physical connections in or out and do
not need cleanup_connections() or BrokerSession.recycle_thread() to free a
completed PostgreSQL operation's pool slot.
The default pool maximum is 3 and checkout timeout is 30 seconds. The activity
listener uses one separate connection, so one active process-session target
uses at most four PostgreSQL connections by default. Pooled connections are not
held forever: every 10 seconds the pool closes one connection that stayed idle
for the whole interval, so a quiet process returns its last data connection
10-20 seconds after its last operation, and the next operation reconnects.
PostgreSQL activity waiters ask watchers for a quiet safety recheck every
30-60 seconds instead of every 1-2 seconds, so a process that is only waiting
on a healthy waiter holds its listener connection plus, briefly after each
recheck, one data connection. Size a deployment from
its database-wide connection budget and maximum broker process count, with
capacity reserved for other clients. Checkout exhaustion is reported to the
caller. Separate checkouts allow
unrelated threads to make progress independently, but PostgreSQL row and
advisory locks can still serialize conflicting transactions.
With the default bound, a fourth simultaneous command operation waits until a
slot returns and raises SimpleBroker OperationalError after the checkout
timeout if none does. Close or exhaust iterators promptly: a suspended iterator
intentionally keeps its transaction and checkout until settlement.
Use Queue.sidecar() or the broker connection's sidecar() context for
caller-owned tables. Sidecars from a persistent Queue or BrokerSession share
that process session's bounded pool. Keep transaction=True blocks short and
always exit them: an open sidecar transaction retains one checkout until commit
or rollback. Enough retained transactions can exhaust the pool, making later
operations on that session wait and, if no slot returns, fail at the checkout
timeout. Non-transactional sidecar statements return their checkouts
automatically. An ephemeral Queue owns a separate runner for its sidecar
session and is outside another session's three-checkout ceiling.
Timestamp resynchronization uses a guarded compare-and-advance update. If a
concurrent allocator publishes a higher durable last_ts after repair begins,
the repair preserves that winner and refreshes its local cache from the
surviving value; it never moves PostgreSQL high-water backward.
Core Compatibility
This first-party extension declares a minimum supported SimpleBroker core version and its backend API version independently. SimpleBroker checks the exact API handshake when it resolves the plugin. An incompatible pair fails at backend resolution with upgrade-or-pin guidance instead of running against an unknown interface. Core and extension package version numbers do not match. The backend API version is separate from the PostgreSQL storage schema version and is not stored in the database. A breaking private-seam change requires a backend API version bump.
The package dependency is an install-time minimum; the runtime handshake is
the authoritative interface check. Install the extension through the core
release's pg extra. See the
backend authoring guide
for the handshake boundary.
Installation
# Fresh install through SimpleBroker's convenience extra
pipx install "simplebroker[pg]"
# Add to an existing pipx-installed simplebroker (recommended)
pipx inject simplebroker simplebroker-pg
# Or install through the convenience extra in a project
uv add "simplebroker[pg]"
# Or install the extension directly with uv
uv add simplebroker-pg
# Or install the extension directly with pip
pip install simplebroker-pg
simplebroker[pg] still installs this package as a separate distribution.
Postgres support is not built into the default simplebroker install.
Python Usage
from simplebroker import Queue
from simplebroker_pg import PostgresRunner
runner = PostgresRunner(
"postgresql://postgres@127.0.0.1:54329/simplebroker_test",
schema="simplebroker_app",
)
queue = Queue("jobs", runner=runner, persistent=True)
try:
queue.write("hello")
print(queue.read())
finally:
queue.close()
runner.close()
Connection Pressure Inspection
Callers that have narrowed a Queue to PostgreSQL can inspect server-wide connection pressure through the public package-root helper:
from simplebroker_pg import get_connection_stats
if queue.backend_name == "postgres":
stats = get_connection_stats(queue)
The returned dictionary has exactly numbackends, max_connections,
superuser_reserved_connections, and reserved_connections integer fields.
reserved_connections is zero on PostgreSQL versions where that setting does
not exist.
numbackends is sum(pg_stat_database.numbackends) across the server. Stock
catalog permissions let an ordinary role observe other established roles and
databases without pg_monitor, pg_read_all_stats, a grant, or an installed
function. It is intentionally conservative: autovacuum and other
database-attached workers can be included even when they do not consume a
max_connections client slot. The snapshot is not a reservation, so callers
must retain a safety margin and tolerate concurrent change.
The helper executes one read-only statement through the Queue's normal
operation checkout, core lock, and retry path. It does not use sidecar or
create database objects. A target-resolved persistent Queue borrows from its
process-session pool; an ephemeral Queue may open one connection for the
operation. Malformed result data raises ValueError;
database and permission failures retain SimpleBroker's database exception
types.
Connection Owners and Usage
Bind an opaque accounting label in each dedicated process before creating any PostgreSQL resources. Multiple processes may share a label.
from simplebroker_pg import bind_connection_owner, get_connection_usage
bind_connection_owner("worker-group-A") # Before pools, listeners, or inspection.
# Create a PostgreSQL Queue using the target examples above.
usage = get_connection_usage(queue)
print(usage["total"], usage["by_owner"].get("worker-group-A", 0))
ConnectionUsage is an exported TypedDict with total: int and
by_owner: dict[str, int]; returned dictionaries are fresh. One materialized
activity query supplies both counts through the Queue's existing probe.
Total includes all database-attached backends on the server, including idle
clients, the observer, unrelated clients and workers. Only visible client
backends with a valid owner marker receive owner credit. Other roles' backend
types may be hidden from ordinary observers. No privileges are granted; an
omitted owner proves neither absence nor death.
Labels match [!-~]{1,54}: non-space printable ASCII, case-sensitive,
without secrets. The extension sets application_name to sb-owner: plus
the label, overriding DSN/ambient names. Same-label binding is idempotent;
conflicting or late binding raises RuntimeError. Failed resource creation
also seals binding. Closure does not unbind, and fork/spawn children bind
explicitly. Even a usage read can start resources, so bind before reading.
Pooled connections (including later growth), shared notification listeners
and direct first-party connections are covered without changing pool or
session identity. Caller-built PostgresRunner is covered; caller-built
driver connections and third-party runners are not. Arbitrary caller SQL can
change the observed application name. Markers are cooperative, not authority.
Inside a caller-owned transaction, PostgreSQL's activity-cache semantics
apply; the helper does not commit, roll back, refresh the cache or open a
separate monitoring connection. Multiplexing proxies may not preserve this
accounting model. Usage is observation, not a permit. Budgets, reservations
and launch decisions stay in the application.
See the Python guide and SB-API-14/15.
Multi-Queue Activity Waiters
Postgres supports simplebroker.create_activity_waiter_for_queues(...) with
one process-local shared LISTEN/NOTIFY listener per DSN and schema. The waiter
wakes when any watched queue receives activity, ignores unrelated queue
notifications, and returns the same ActivityWaiter | None shape as the core
API.
Wakeups are hints. After wait(timeout) returns True, callers should still
drain queues through normal SimpleBroker reads or moves. Both waiter types
declare safety_recheck_interval = 30.0: PollingStrategy still returns for
a quiet recheck within 30-60 seconds plus one polling pass (about 0.115
seconds by default), plus scheduler delay and the queue check itself. This
bounds check scheduling when a notification is lost (an undetected
listener-session failure, or a writer that bypasses SimpleBroker), not delivery
when reconnecting or querying stalls. Normal wakeups arrive through NOTIFY and do not wait
for the recheck; see SB-API-6. Close the multi-queue
waiter explicitly when the watcher lifecycle ends. Its first close() is
terminal before cleanup; every later call is a no-op, including when the first
call raised. The waiter owns registrations, not the runner or shared listener,
and does not expose shutdown().
Built-in watcher recovery ends after the third failure in one streak (2/4-second
retry delays; 300-second budget checked between attempts). A processing wait
must return normally to reset the streak; connecting and draining alone do not
prove recovery. Repeated server idle-session expiry during a quiet 30–60-second
wait can therefore stop the watcher. Configure the existing broker DSN/libpq
option options='-c idle_session_timeout=0' or a broker-role policy when quiet
continuous watching is required. That policy applies to LISTEN and command
connections; there is no separate listener DSN. Client-pool idle reaping remains
in effect. No server setting is changed by the library.
Notification channels
Each write, move target, rename (old and new name) and broadcast target sends
one NOTIFY on that queue's own channel: simplebroker_q_ followed by the
first 24 hex digits of md5(schema || chr(31) || queue), with the queue name
as payload. The shared listener LISTENs the channel of every queue it
currently waits on. It also LISTENs the schema channel (simplebroker_
followed by the first 24 hex digits of md5(schema)), which carries the *
wildcard that wakes every waiter and the notifications of simplebroker-pg
4.7.x and older. Creating a waiter for a queue the listener does not yet
follow costs one LISTEN round trip; the constructor returns only after that
LISTEN is active, and raises OperationalError if the listener cannot
subscribe within its startup timeout.
A listener connection therefore receives no traffic for queues it does not
wait on. Through PostgreSQL 18 the server still signals every listening
session in the same database on each NOTIFY, and each signaled session runs a
short transaction to skip the message; separate databases, not separate
schemas, isolate that cost. PostgreSQL 19 signals only sessions listening on
the notified channel (upstream commit 282b1cde9), which per-queue channels
let it use.
Upgrading from 4.7.x or older: old waiters LISTEN only the schema channel, so they do not hear writes from newer clients and fall back to their idle re-poll (about 1–2 seconds with default settings) until they are upgraded. New waiters still hear old writers. Upgrade waiting processes before, or together with, the processes that write to their queues.
CLI Usage
Create .broker.toml in the project root, or use the configured
BROKER_PROJECT_CONFIG_PATH / BROKER_PROJECT_CONFIG_NAME location:
version = 1
backend = "postgres"
target = "postgresql://postgres@127.0.0.1:54329/simplebroker_test"
[backend_options]
schema = "simplebroker_app"
Then use the normal CLI from any child directory with project scope enabled:
broker init
broker write jobs hello
broker read jobs
You can also run entirely from environment variables without a project config:
BROKER_BACKEND=postgres \
BROKER_BACKEND_TARGET='postgresql://postgres@127.0.0.1:54329/simplebroker_test' \
BROKER_BACKEND_SCHEMA='simplebroker_app' \
BROKER_BACKEND_PASSWORD='postgres' \
broker init
Notes:
- In env-only backend configuration,
BROKER_BACKEND_TARGEToverrides the host/port/user/database parts. BROKER_BACKEND_HOST,BROKER_BACKEND_PORT,BROKER_BACKEND_USER,BROKER_BACKEND_PASSWORD, andBROKER_BACKEND_DATABASEare only used when there is no target from project config or env.- When project TOML provides the target or schema, the project file wins.
BROKER_BACKEND_PASSWORDcan still be supplied from env and is never written to project TOML. - The Postgres database must already exist.
broker initcreates the managed schema/tables inside that database; it does not create the database itself. - Missing backend/plugin errors are distinct from target/auth errors. Invalid schema names, bad passwords, malformed targets, and missing databases are reported as validation or connection failures, not as "backend not available" errors.
Schema identity and destructive maintenance
Schema names use the existing ASCII identifier grammar, must not be public,
and must fit within 63 bytes. All public plugin, runner and waiter entrances
validate before creating resources. SimpleBroker rejects rather than truncates
long names: PostgreSQL truncation can merge tenant storage while client lock and
notification names differ. Correct existing invalid configurations explicitly;
configuration changes cannot split data already mixed in one physical schema.
Destructive --cleanup ends the physical schema's client lifetime. Finish all
iterators/transactions, stop watchers, close every owning session/runner across
processes, then clean up and recreate. Construct fresh owners afterward. This
applies even when different DSNs name the same target. Cleanup does not verify
quiescence. Retained clients, including alias caches, are unsupported across
replacement; the alias-version counter can restart at the same value. Ordinary
alias mutation within a target lifetime retains its freshness guarantee.
See SB-API-2/3 and
SB-OPS-7.
Metadata
Release files for simplebroker-pg 4.8.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| simplebroker_pg-4.8.2.tar.gz | 45.0 kB | With provenance | Details for simplebroker_pg-4.8.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| simplebroker_pg-4.8.2-py3-none-any.whl | Python 3 | none | any | Details for simplebroker_pg-4.8.2-py3-none-any.whl |
Total release size: 103.5 kB
Release files / simplebroker_pg-4.8.2.tar.gz
| Download URL | simplebroker_pg-4.8.2.tar.gz |
|---|---|
| Size | 45.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e9a8f9527e1cdf8dcfea3ed228e207e8d5eb2113e06bda3eb7ce46841ab9afc3
|
|
BLAKE2b-256 checksum How to use checksums |
51997c1da4d30a1e30390deb6716955fa73eedbb29dd3211f69497232f3151e3
|
| 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 11, 2026.
Transparency logRelease files / simplebroker_pg-4.8.2-py3-none-any.whl
| Download URL | simplebroker_pg-4.8.2-py3-none-any.whl |
|---|---|
| Size | 58.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0be11396ea43482df2a7366317923f91d3f5782d4e7988e510a24917f328d465
|
|
BLAKE2b-256 checksum How to use checksums |
bde6f45336c2f9ecec62df5bc88ccb530cb11f968a240b0f63f1b74f518e2210
|
| 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 11, 2026.
Transparency logSecurity for simplebroker-pg 4.8.2
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.
Attestation for simplebroker_pg-4.8.2.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 11, 2026.
Transparency logA 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.