Back to blog
developmentdatabaseperformance

Scaling Postgres: How the Connection Pool Taught Us Humility

19 May 20267 min readKansei TeamCzechEnglish

The Bug That Looked Like an Optimization

At one point in development, our database pool was configured with max: 1. The logic sounded reasonable: serverless functions are short-lived, connections are expensive, so keep few of them. Then AI streaming arrived — an assistant response holds a connection for up to 120 seconds. With a single connection in the pool, the entire app instance queued up behind one chat. The dashboard with its 15 parallel queries waited for the AI to finish talking.

The lesson: you size a pool for concurrency, not thrift. Today we run max: 20 per instance with a hard "never below 10" rule.

Math That Doesn't Add Up

The second problem of serverless deployments: every warm instance holds its own pool. Twenty connections × N instances quickly hits the ~100-connection cap of managed Postgres on Railway. The answer is PgBouncer — a pooler that sits between the app and the database, accepts hundreds of virtual clients, and multiplexes them onto ~20 real backends.

A transaction-mode pooler has its own rules though: CREATE INDEX CONCURRENTLY must run outside a transaction, VACUUM cannot run inside one at all, and named prepared statements leak across connections. So we keep two connection URLs — regular traffic goes through the pooler, migrations and maintenance take the direct path.

Row-Level Security: a Database-Level Safety Net

kansei is a multi-tenant system — dozens of studios' data in the same tables. The application layer checks isolation on every request, but a single forgotten WHERE clause would be enough to leak data. So every table with an entity_id column has Row-Level Security enabled with a tenant_isolation policy: a transaction first sets app.current_entity_id, and the database then physically refuses to return foreign rows even if the query has no WHERE at all.

The best detail: the setup endpoint discovers entity_id tables by itself via information_schema. A new table gets RLS automatically — nobody has to remember.

Three Rules We're Keeping

  • EXISTS instead of COUNT(*) — "does at least one exist?" should not be answered by scanning the whole table.
  • Aggregate through ::bigint — sums of hellers and AI tokens overflow a 32-bit int sooner than you expect.
  • Composite indexes lead with entity_id — an index that doesn't start with the tenant is nearly useless in a multi-tenant query.

A database is boring right up until it isn't. This is the list of things we learned to make ours boring again.

Related posts

Read enough? Try it on your next job.