Skip to content

Backends

A backend is where persistence keeps what it saves: memory for tests, a SQLite file for a bot that runs as one process, PostgreSQL for a bot that runs as several. Pass one to PersistenceMiddleware(backend=...). With none, the library uses a SQLite file named cascadeui.db (Setup).

Diagram: the four tables a SQL backend creates and what writes each. cascadeui_persistent_views gets a panel's row at once when Kael posts the support desk: desk:22, TicketDesk, message 7001. cascadeui_application_slots gets a persistent slot's row about two seconds after it changes: the scoped slot with Kael's count of 3. cascadeui_schema is written at the first start and at each upgrade, and read at every start: the registry table at version 2 and the slots table at version 1. cascadeui_kv stays empty: only your own code writes it.

Choosing a Backend

Backend Install Suits Your own SQL
InMemoryBackend included tests: nothing outlives the process no
SQLiteBackend pip install "pycascadeui[sqlite]" a bot that runs as one process (the default) yes
PostgresBackend pip install "pycascadeui[postgres]" a bot that runs as several processes on one database yes

All three import from cascadeui. Your own SQL means execute(), fetch(), and transaction() on tables of your own (Custom Backends and Raw SQL).

The Tables

Both SQL backends create four tables and two indexes at their first start:

Table Holds Written
cascadeui_persistent_views one row per persistent panel at once, when the panel is sent or closed
cascadeui_application_slots one row per saved slot about 2 seconds after a change (When a Slot Is Written)
cascadeui_schema each table's version at the first start and at each upgrade
cascadeui_kv keys and values of your own only by your code (Pattern B)

Every table name starts with cascadeui_, so one pattern reaches all of them in a backup filter, a grant, or a query. The two indexes are named idx_cascadeui_.... To keep two deployments apart in one database, give each a prefix:

from cascadeui import PostgresBackend, SQLiteBackend

SQLiteBackend("bot.db", table_prefix="staging_")
PostgresBackend(dsn, table_prefix="staging_")

The prefix goes in front of every table and index (staging_cascadeui_kv) and, on PostgreSQL, the notification channel. It takes lower-case letters, digits, and underscores, starting with a letter or underscore, and on PostgreSQL at most 41 characters, so the channel's name fits PostgreSQL's 63-byte limit. Anything else raises ValueError when the backend is built (TypeError for a prefix that is not a str), since PostgreSQL reads a capital differently in different statements and refuses a longer channel. A new prefix on a database that holds rows starts on new, empty tables, and the old rows stay where they are.

Tables From Older Releases

The registry and slot tables were once named persistent_views and application_slots. A start that finds one of them with the library's columns renames it in place, with its index and version record, in one transaction. A backend with a table_prefix skips this: the prefix came with the current names, so a prefixed database never held the old ones.

A table of that name without the library's columns is your own and is left alone (logged at INFO). When the old and new names both hold rows, nothing is renamed: the library uses the new one, and a WARNING names both for you to merge. On PostgreSQL only the table's owner can rename it, so run the first start after the upgrade as the owner. Another role's start fails, with the error Database Privileges lists.

SQLite

from cascadeui import PersistenceMiddleware, SQLiteBackend, setup_middleware

await setup_middleware(PersistenceMiddleware(backend=SQLiteBackend("bot.db"), bot=bot))

The first start creates the file. The backend opens it in WAL mode, so another program (a backup, the sqlite3 shell) can read it while the bot writes. SQLite cannot tell one process about another's writes, so a bot that runs as several processes uses PostgreSQL.

PostgreSQL

import os

from cascadeui import PersistenceMiddleware, PostgresBackend, setup_middleware

backend = PostgresBackend(os.environ["CASCADEUI_DATABASE_URL"])
await setup_middleware(PersistenceMiddleware(backend=backend, bot=bot))

The connection string is a libpq URL. To check the server's certificate, add sslmode=verify-full and the certificate authority's file:

postgresql://user:password@host:5432/mybot?sslmode=verify-full&sslrootcert=/path/to/ca.crt

Database Privileges

The first start creates the tables, so its role owns them. After that, a role holding only read and write grants on the tables runs the bot:

GRANT CONNECT ON DATABASE mybot TO bot_app;
GRANT USAGE ON SCHEMA public TO bot_app;
GRANT SELECT, INSERT, UPDATE, DELETE
    ON cascadeui_persistent_views, cascadeui_application_slots,
       cascadeui_kv, cascadeui_schema
    TO bot_app;

Three starts change the tables, and each needs their owner:

Start On the read-and-write role
The first, on an empty database PersistenceInitError naming the table it cannot create
The first after an upgrade that changes a table PersistenceSchemaError naming the table and the step. The stored version is unchanged, so the next start tries again
The first on a database with the old table names PersistenceInitError, or with CREATE on the schema, PersistenceSchemaError naming the old and new names

Run those as the owner, then go back to the smaller role. On SQLite, access to the file covers all three.

Several Processes

Each process keeps its own copy of every saved slot in memory, read at its start. On PostgreSQL, every write sends a notification through LISTEN/NOTIFY to each process listening under the same prefix, and persistence reads the slot it names back into that process's store:

The notification What persistence does
Another process wrote a slot Reads the slot's row and puts its value in the store
Another process removed a slot Drops the slot from the store, when this process loaded or saved it
It names no slot (an expiry sweep, or a key too long to send) Reads every slot
It is this process's own write Nothing
This process has a change to that slot waiting to be written Nothing: the waiting write lands after the other process's, and wins

Diagram: two bot processes sharing one PostgreSQL database, on a seconds axis. Kael clicks +1 on process A's counter in server 22, and A's store holds Count 3 at once, while the database row still says 2 and process B still holds 2. About 2 seconds later the row is written, and PostgreSQL sends a notification to both processes. Process A hears its own write and reads nothing back. Process B reads the row in about 2 ms, and its store holds Count 3. When Kael then runs /counter in server 33, which process B serves, it opens on Count 3.

A listening connection that reconnects, and persistence opened again after a close, read every slot, since a notification sent meanwhile is lost. A read that changed the store dispatches APPLICATION_SLOTS_RELOADED with the slots' names. A view redraws for it when its subscribed_actions lists it or is None, as for any action (see What a View Hears). A read that fails is logged at WARNING and tried again 5 seconds later.

A read parses the whole slot. Measured against a local PostgreSQL 16, another process's change to a scoped slot holding 10,000 people's data reached the store in about 30 ms. At 100,000 people it took about 0.3 seconds and held up the event loop for up to 0.1 seconds.

Two processes that change one slot before either hears the other each write their whole value, so the later write wins and both processes end up showing it.

SQLite and the in-memory backend send no notifications, so two processes sharing a SQLite file each keep serving their own copy:

  • A process keeps its copy after another process writes the row.
  • A write that would store what this process last stored is skipped, so setting a slot back to that value, after another process changed it, leaves the other process's value in the database.
  • The expiry sweep goes by this process's own record, so a slot it recorded as expired leaves its memory even when another process has written the row since. The row stays.

To act on notifications yourself, for your own tables or panels another process posted, register a callback. It hears every notification, this process's own writes included:

def on_invalidate(namespace: str, key: str) -> None:
    cache.pop((namespace, key), None)


backend.set_invalidation_callback(on_invalidate)

namespace is the table (cascadeui_application_slots) and key the row's key: a slot's name, a panel's persistence_key, or your own key. An empty key means the whole table, sent when the key is too long for a notification (PostgreSQL caps one at 8000 bytes) or when expired slots are swept.

The callback may be a plain function or an async def, and must take (namespace, key), or setting it raises TypeError. An error it raises is logged at ERROR naming it, and the next notification still reaches it. Every 10 seconds the listening connection runs one small query, and it reconnects when the connection drops or the query gets no answer within 10 seconds, which is how a path a NAT or load balancer dropped without a word shows. A notification sent while it is down never reaches the callback.

A click reaches only the process running its server's shard, so a bot split into processes by shard restores and checks only the panels on its own shards (a panel in a DM is shard 0's). A bot running every shard, or one whose shard count is not known when it restores, takes them all.

Pool

The pool opens 2 connections and grows to 10, with asyncpg's statement cache at 1024. pool_kwargs overrides any of them, and takes any other asyncpg.create_pool() keyword:

PostgresBackend(dsn, pool_kwargs={"min_size": 5, "max_size": 20})

The listening connection is one more, outside the pool.

PgBouncer

In PgBouncer's session mode everything works. In transaction mode writes work, but notifications never arrive, since LISTEN needs a session of its own. listener_dsn sends that one connection straight to PostgreSQL:

PostgresBackend(
    "postgresql://bot@pgbouncer:6432/bot",
    listener_dsn="postgresql://bot@db:5432/bot",
)

With PgBouncer's max_prepared_statements at 0, also pass pool_kwargs={"statement_cache_size": 0}, or some writes fail with prepared statement does not exist. statement mode cannot run a transaction, which every write needs, so initialize() raises PersistenceInitError there.

A backend persistence saves slots to, or one with a callback set, sends itself one test notification when it opens, and logs a WARNING when it does not come back within two seconds.