
SaaS Connection Pools: Budget Database Capacity Across Every App Instance
Size SaaS database connection pools using the total number of processes, deployment overlap, wait behavior, and measured database capacity rather than one local setting.
MVPs & SaaS Projects
Use PostgreSQL advisory locks with explicit keys, transaction or session scope, bounded contention, and failure tests that keep SaaS worker coordination honest.

LET’S BUILD SOMETHING USEFUL
Talk to Ataraxy Developers about your website, app, or custom software.
Two workers notice that the same tenant needs a summary rebuilt. Each begins calculating, then both attempt to publish a result. An advisory lock can help coordinate that work, but only if every participating code path agrees on the lock’s meaning and lifetime. Adding a lock call to one worker does not automatically turn a distributed workflow into a single, reliable operation.
For a SaaS team, the useful starting point is a written ownership contract: what resource is protected, who must acquire the lock, how long it lasts, and what happens when acquisition fails or the connection disappears. PostgreSQL provides several advisory-lock choices. Selecting among them should follow that contract rather than whichever function appears first in an example.
Describe the problem in a sentence that can be tested. For example: “Only one participating transaction may replace the current summary for this tenant at a time.” Identify the data read and written inside that operation. A narrower invariant is easier to verify than a statement such as “only one worker runs,” which may accidentally include unrelated work and external services.
Next, list every writer: scheduled workers, manual rebuild tools, administrative scripts, and repair jobs. PostgreSQL’s advisory-lock documentation makes clear that these locks have application-defined meaning; the database does not enforce their use by all relevant code. If one writer skips the protocol, it can still violate the application’s intended coordination rule.
Review whether the invariant belongs in a database constraint, a row-level locking operation, or an application coordination protocol. A uniqueness requirement should usually have an appropriate database constraint even if workers also coordinate their preparation. An advisory lock is useful when the resource being coordinated does not map neatly to a single row, but it should not conceal missing validation of the final write.
In the summary example, a lock may prevent two participating rebuild transactions from racing. The stored summary should still carry the tenant identity and a version or other freshness rule appropriate to the application. If the calculation uses an older snapshot than another accepted result, decide whether it may replace that result. Mutual exclusion alone does not establish that the data being written is the newest or most appropriate data.
Document how the protected resource maps to a lock key. Include the operation type as well as the tenant or record identity so unrelated activities do not accidentally contend on the same value. Use a shared implementation for that mapping and test it across every language or service that participates. Treat a change to the mapping as a protocol migration, not a harmless refactor.
Avoid improvising a small hash without considering collisions. If two resources map to the same key, they may block each other unexpectedly; if two workers derive different keys for the same resource, they fail to coordinate. Choose a representation that fits the supported key forms and your identifier domain. Keep a human-readable resource label in diagnostics so an opaque numeric key can be traced back to the operation it represents.
PostgreSQL distinguishes session-level and transaction-level advisory locks. Session locks remain until released or the session ends, and rolling back a transaction does not release them. Transaction-level locks are released at transaction end. These differences matter when a worker uses pooled connections: the lifetime of an application request is not necessarily the lifetime of the underlying database session.
For a short operation that reads and updates database state within one transaction, a transaction-scoped lock often makes the intended boundary easier to express. Acquire it on the same transaction connection used for the protected work, then commit or roll back promptly. If session scope is necessary, define explicit acquisition and release ownership and verify the pool’s behavior. Never assume returning a connection to the pool means the session has ended.
The advisory-lock function reference includes blocking and try-lock forms. A try-lock form reports whether it acquired the lock without waiting for the competing holder to finish. Choose the behavior that fits the job: a duplicate optional rebuild may be deferred, while a user-requested operation may need a clear waiting or busy response.
Do not turn a failed try-lock into a tight retry loop. Record the reason for deferral, schedule another attempt under a bounded policy, and consider whether a pending request should be coalesced with existing work. For blocking acquisition, define acceptable waiting and cancellation behavior. Monitor lock wait time separately from calculation time so a contention problem is not misdiagnosed as a slow query inside the rebuild.
A database advisory lock cannot make an external email, payment, or storage operation atomic with a database transaction. If the worker loses its connection, the database may release its lock while some remote operation remains in progress. Another worker can then acquire the lock without knowing whether the first remote action completed. This is a workflow design problem that requires its own reconciliation and duplicate-prevention rules.
Keep the protected transaction focused where possible. Persist the intended work and its operation identity, then use an established delivery mechanism for remote effects. If remote work genuinely needs a longer ownership model, evaluate a durable lease and fencing design appropriate to that system. Do not describe a database session lock as proof of exactly-once execution across components that do not participate in its protocol.
If a transaction needs several locks, choose a consistent acquisition order based on stable resource identities. Test requests that involve the same pair of resources in opposite user-selected orders. Otherwise, two workers can each hold one resource while waiting for the other. Keep the number of locks small and make nested helper functions explicit about whether their caller already owns the required coordination boundary.
Session-level advisory locks can be acquired repeatedly by the same session, which makes balanced release important. A helper that silently reacquires a lock can leave a later release insufficient. Prefer a clear owner over scattered acquire-and-release calls. Review exception paths, early returns, and cancellation alongside the ordinary path; those are the places where apparently tidy code can leave a pooled session holding more than its caller expects.
Run two real database connections against the same resource and verify that only the intended participant enters the protected section. Then use different resources and verify that unrelated work can proceed. Test rollback, connection loss, lock-acquisition failure, and the administrative repair path. Check the final stored result, not only the order of log messages.
AI can help enumerate callers or propose missing failure tests from a sanitized design description. Review its suggestions against the actual transaction and pool boundaries. Add operational evidence such as acquisition outcome, wait duration, resource label, and completion status, without recording sensitive tenant contents. These details let an operator distinguish normal coalescing from a stuck session or a writer that never joined the protocol.
Advisory locks work when the application agrees on their meaning. Define the protected invariant, use stable keys, match scope to the transaction or session, and give contention a deliberate outcome. Keep external effects under their own delivery rules and test failure with concurrent connections. That turns a lock call into a coordination protocol the team can explain and maintain.
LET’S BUILD SOMETHING USEFUL
Talk to Ataraxy Developers about your website, app, or custom software.