You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Research: a Postgres database per company on Azure, pooling and budgets #178
What does one Postgres database per company cost and constrain on Azure Database for PostgreSQL Flexible Server, and how should the server hold connections to hundreds of them? Specifically: limits on databases per server and connections per SKU; whether PgBouncer built-in pooling works per database and what its transaction-pooling mode forbids (prepared statements, advisory locks, LISTEN); creating a database at company creation time from an application role (privileges, latency, what CREATE DATABASE cannot run inside a transaction); backup and point-in-time restore granularity (server-wide, not per database); how to keep company-to-database placement explicit so a company can move to another server later; and how effect/unstable/sql should model a per-company SqlClient (a registry service handing out bounded pools versus one pool per request). Primary sources only: Azure docs, the PgBouncer docs, the Postgres docs, and the Effect SQL source in node_modules/effect.
Recommendation to test against: a company registry service that lazily opens a bounded pool per company database with an idle eviction, a global connection budget below the SKU limit, and additive DDL for a patch run under a per-patch advisory lock in the company database. Say whether the evidence supports that, and what SKU floor it implies.
Billing is per server, not per database: shared compute, provisioned storage, excess backup; no company-specific CPU/IO isolation. East US USD PAYG retail prices, retrieved today: Standard_D2ds_v5 $0.178/hour; storage $0.115/GB-month. At 730 hours and the 32-GiB minimum: $133.62/month before HA, excess backups, extra IOPS, bandwidth, tax and discounts. HA doubles compute/storage; backup allowance equals provisioned storage (pricing).
Database and connection limits
No numeric Azure databases-per-Flexible-Server ceiling was established from its limits; obtain Azure confirmation before treating this as unlimited.
Documented default total/user connections, shared across databases:
Listed SKU groups
Total/user
B1ms
50/35
B2s
429/414
B2ms; GP D2
859/844
B4ms; GP D4; MO E2
1,718/1,703
B8ms; GP D8; MO E4
3,437/3,422
B12ms+; GP D16+; MO E8+
5,000/4,985
Read actual max_connections − reserved_connections − superuser_reserved_connections: currently 15 reserved; resizing does not automatically update max_connections. These are connection ceilings, not throughput guarantees.
PgBouncer and the global budget
Azure documents PgBouncer 1.25.2, port 6432, General Purpose/Memory Optimized only. Pools are per (database,user), never interchangeable across companies. Defaults: transaction mode, 50 backends/pair, minimum zero, 600-second backend idle timeout, 5,000 frontend connections. Thus 100 × 50 permits 5,000 backends; application eviction does not close those retained backends.
Proposed invariant, per server across all application replicas: retained/draining direct-pool maxima + platform/provisioning/admin headroom < available user slots. Budget idle connections, not merely running queries; bound admission. With PgBouncer, instead budget the sum of all database/user backend caps, including idle pools. Its exposed parameters do not establish an aggregate backend cap; max_client_conn is not one.
Transaction pooling forbids SQL PREPARE/DEALLOCATE, session advisory locks and LISTEN; NOTIFY works. Named protocol prepared statements work with max_prepared_statements>0 (Azure defaults zero). Avoid session SET search_path; qualify schemas.
Creating a company database
Use a separate provisioning login with explicit CREATEDB, not the ordinary data role. Azure's administrator has CREATEDB, not superuser. PostgreSQL 18 requires permission to SET ROLE when assigning another owner; CREATE DATABASE clones a template and cannot run inside a transaction block. Execute standalone against a maintenance database, then connect to the new database for permissions/schema setup. Keep platform company state provisioning until ready: creation cannot atomically commit with its platform row. No documented latency bound; measure p50/p95 on the selected Azure SKU under load, rather than promise milliseconds.
Backup and PITR
Automated backup/PITR is server-wide, retained 7 days by default, maximum 35. Restore creates a new, billed server; no individual-company PITR. Recover one company by restoring the server, dumping that database, then restoring it to its chosen placement. Reconcile platform metadata separately; company data and platform metadata cannot be independently rewound safely by assumption.
Explicit placement and moving companies
Following decision #168, propose platform mapping companyId → {serverId,databaseName,placementVersion,status}; server configuration owns endpoint/TLS/secret references. Keep stable physical IDs. Move: pause company operations across replicas, drain, dump/restore (provision roles separately), atomically switch placement/version, invalidate old pools, resume. This permits a deliberate downtime cutover, not an implicit zero-downtime promise.
Effect SQL lifecycle
Checkout lacked node_modules; inspected scratch copies of effect/@effect/sql-pg 4.0.0-rc.112, verified against lockfile SHA-512. PgClient.make constructs pg.Pool, probes SELECT 1, finalizes pool.end; per-request construction causes churn.
Use a scoped registry backed by RcMap: deduplicated lazy lookup, capacity, idle TTL, request-scoped leases; explicit pool maximum, minimum zero and idle timeout. Capacity exhaustion fails, not queues/LRU-evicts. Provide the leased company SqlClient only within company operations; retain the separate platform client.
Source-level pooler blocker: adapter cancellation uses pg_cancel_backend(client.processID); PgBouncer's identifier is random, not PostgreSQL's PID. Correct cancellation before adopting 6432. Normal adapter queries are unnamed; no prepare:false switch is needed.
Per-patch DDL and verdict
Use pg_advisory_xact_lock(stablePatchKey)inside the same company transaction as schema inspection, additive DDL and ledger update. SqlClient.withTransaction reserves that connection; transaction locks release on commit/rollback. Ordinary indexes block writers; CREATE INDEX CONCURRENTLY cannot join this transaction.
Verdict: amend. Keep the lazy bounded registry, idle eviction and per-patch DDL; require fleet-wide backend budgets and transaction locks. Start direct until pooler budgeting/cancellation is resolved. Recommend GP D2, 2 vCores/8 GiB: built-in PgBouncer floor; Burstable is not recommended for production. Database count alone imposes no such floor. Azure load/cancellation tests remain unperformed; active-company concurrency and DDL load determine any larger SKU.
Supplement, 2026-09-06. Facts from a second pass over the same primary sources that the resolution above does not carry:
Per-database observability caps at 30 databases. Azure's built-in PgBouncer metrics with the DatabaseName dimension cover 30 databases (10 on Burstable), chosen by OID order, so the 31st company's pool is invisible in per-database metrics (concepts-pgbouncer). Fleet-level budgeting has to come from the application, not from Azure metrics.
Azure's own pool sizing guidance is far below the 50-per-pair default: "use conservative values by multiplying the vCores within the range of 2 to 5" (concepts-limits), so on D2 a pool of 4–10 backends per (database, user) pair, which makes the 100 × 50 = 5,000 arithmetic above a misconfiguration rather than a ceiling to plan for.
Transaction-level advisory locks under transaction pooling are safe by inference, not by documentation. PgBouncer's feature table only lists session-level advisory locks as "Never" (features); the Postgres docs carry no pooler caveat at all. pg_advisory_xact_lock releases at commit, which is PgBouncer's release boundary. Record it as an inference in the ADR.
Built-in PgBouncer restarts with the server (scale operations, HA failover, restarts) and is single-threaded, so the application must reconnect and short-lived connection storms hit its ceiling first (concepts-pgbouncer).
CREATE DATABASE fails if any other session is connected to the template, and ALTER DATABASE settings and GRANTs are not copied from it (sql-createdatabase); provision from template1 with nothing else attached, and apply company-database settings after creation.
DDL lock nuances for the additive set:ADD FOREIGN KEY takes only SHARE ROW EXCLUSIVE; ADD CHECK and NOT NULL scan but do not rewrite; a volatile default, an identity column or a constrained domain column rewrites the table (sql-altertable). Tablespaces are not supported on Flexible Server.
Pricing ladder, East US PAYG, compute only, indicative: B1ms ≈ $12/mo (35 user connections, no PgBouncer, no on-demand backups, not for production), B2s ≈ $50, B2ms ≈ $99, D2ds_v5 ≈ $130 (cheapest PgBouncer-capable), E2ds_v5 ≈ $183; backup storage $0.095/GB-month above the free allowance equal to provisioned storage (retail prices API).
Long-term retention is pg_dump-based, all databases at once, restore-as-files only (concepts-backup-restore); it is not a per-company export path.
Activity
allisonmahmood commentedon Sep 6, 2026
Resolved 2026-09-06.
Cost
Billing is per server, not per database: shared compute, provisioned storage, excess backup; no company-specific CPU/IO isolation. East US USD PAYG retail prices, retrieved today: Standard_D2ds_v5 $0.178/hour; storage $0.115/GB-month. At 730 hours and the 32-GiB minimum: $133.62/month before HA, excess backups, extra IOPS, bandwidth, tax and discounts. HA doubles compute/storage; backup allowance equals provisioned storage (pricing).
Database and connection limits
No numeric Azure databases-per-Flexible-Server ceiling was established from its limits; obtain Azure confirmation before treating this as unlimited.
Documented default total/user connections, shared across databases:
Read actual
max_connections − reserved_connections − superuser_reserved_connections: currently 15 reserved; resizing does not automatically updatemax_connections. These are connection ceilings, not throughput guarantees.PgBouncer and the global budget
Azure documents PgBouncer 1.25.2, port 6432, General Purpose/Memory Optimized only. Pools are per (database,user), never interchangeable across companies. Defaults: transaction mode, 50 backends/pair, minimum zero, 600-second backend idle timeout, 5,000 frontend connections. Thus 100 × 50 permits 5,000 backends; application eviction does not close those retained backends.
Proposed invariant, per server across all application replicas: retained/draining direct-pool maxima + platform/provisioning/admin headroom < available user slots. Budget idle connections, not merely running queries; bound admission. With PgBouncer, instead budget the sum of all database/user backend caps, including idle pools. Its exposed parameters do not establish an aggregate backend cap;
max_client_connis not one.Transaction pooling forbids SQL
PREPARE/DEALLOCATE, session advisory locks andLISTEN;NOTIFYworks. Named protocol prepared statements work withmax_prepared_statements>0(Azure defaults zero). Avoid sessionSET search_path; qualify schemas.Creating a company database
Use a separate provisioning login with explicit
CREATEDB, not the ordinary data role. Azure's administrator has CREATEDB, not superuser. PostgreSQL 18 requires permission toSET ROLEwhen assigning another owner;CREATE DATABASEclones a template and cannot run inside a transaction block. Execute standalone against a maintenance database, then connect to the new database for permissions/schema setup. Keep platform company state provisioning until ready: creation cannot atomically commit with its platform row. No documented latency bound; measure p50/p95 on the selected Azure SKU under load, rather than promise milliseconds.Backup and PITR
Automated backup/PITR is server-wide, retained 7 days by default, maximum 35. Restore creates a new, billed server; no individual-company PITR. Recover one company by restoring the server, dumping that database, then restoring it to its chosen placement. Reconcile platform metadata separately; company data and platform metadata cannot be independently rewound safely by assumption.
Explicit placement and moving companies
Following decision #168, propose platform mapping
companyId → {serverId,databaseName,placementVersion,status}; server configuration owns endpoint/TLS/secret references. Keep stable physical IDs. Move: pause company operations across replicas, drain, dump/restore (provision roles separately), atomically switch placement/version, invalidate old pools, resume. This permits a deliberate downtime cutover, not an implicit zero-downtime promise.Effect SQL lifecycle
Checkout lacked
node_modules; inspected scratch copies of effect/@effect/sql-pg 4.0.0-rc.112, verified against lockfile SHA-512. PgClient.make constructspg.Pool, probesSELECT 1, finalizespool.end; per-request construction causes churn.Use a scoped registry backed by RcMap: deduplicated lazy lookup, capacity, idle TTL, request-scoped leases; explicit pool maximum, minimum zero and idle timeout. Capacity exhaustion fails, not queues/LRU-evicts. Provide the leased company
SqlClientonly within company operations; retain the separate platform client.Source-level pooler blocker: adapter cancellation uses
pg_cancel_backend(client.processID); PgBouncer's identifier is random, not PostgreSQL's PID. Correct cancellation before adopting 6432. Normal adapter queries are unnamed; noprepare:falseswitch is needed.Per-patch DDL and verdict
Use
pg_advisory_xact_lock(stablePatchKey)inside the same company transaction as schema inspection, additive DDL and ledger update. SqlClient.withTransaction reserves that connection; transaction locks release on commit/rollback. Ordinary indexes block writers; CREATE INDEX CONCURRENTLY cannot join this transaction.Verdict: amend. Keep the lazy bounded registry, idle eviction and per-patch DDL; require fleet-wide backend budgets and transaction locks. Start direct until pooler budgeting/cancellation is resolved. Recommend GP D2, 2 vCores/8 GiB: built-in PgBouncer floor; Burstable is not recommended for production. Database count alone imposes no such floor. Azure load/cancellation tests remain unperformed; active-company concurrency and DDL load determine any larger SKU.
allisonmahmood commentedon Sep 6, 2026
Supplement, 2026-09-06. Facts from a second pass over the same primary sources that the resolution above does not carry:
DatabaseNamedimension cover 30 databases (10 on Burstable), chosen by OID order, so the 31st company's pool is invisible in per-database metrics (concepts-pgbouncer). Fleet-level budgeting has to come from the application, not from Azure metrics.pg_advisory_xact_lockreleases at commit, which is PgBouncer's release boundary. Record it as an inference in the ADR.CREATE DATABASEfails if any other session is connected to the template, and ALTER DATABASE settings and GRANTs are not copied from it (sql-createdatabase); provision fromtemplate1with nothing else attached, and apply company-database settings after creation.ADD FOREIGN KEYtakes only SHARE ROW EXCLUSIVE;ADD CHECKandNOT NULLscan but do not rewrite; a volatile default, an identity column or a constrained domain column rewrites the table (sql-altertable). Tablespaces are not supported on Flexible Server.pg_dump-based, all databases at once, restore-as-files only (concepts-backup-restore); it is not a per-company export path.