Lesson 5 of 5 Developing with Azure Database for PostgreSQL

Optimizing PostgreSQL Connections

This lesson explains why PostgreSQL connections are expensive, how client-side pools and the built-in PgBouncer help, and other ways to raise throughput.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain the cost of a PostgreSQL connection.
  • Describe how a client-side pool is used.
  • Compare a client-side pool with PgBouncer.
  • Identify practices that reduce database latency.

Why connections are expensive

PostgreSQL creates a separate server process for each client connection. Opening a connection therefore involves a TCP handshake, a TLS handshake, authentication (including token validation for Microsoft Entra), and starting a process with its own memory. This can take tens of milliseconds, far longer than a simple indexed query. Each idle connection also consumes server memory, and the server accepts at most max_connections connections, a limit that depends on the compute size.

Two application patterns cause trouble. Code that opens a new connection per request adds the connection cost to every request's latency. And platforms that scale out quickly, such as Azure Functions or Container Apps with many replicas, can each open their own connections until the server's limit is reached, after which new connections fail with errors such as "too many clients already".

True or false

The cost of a connection

Exam skills 2.2.6

Decide whether each statement about PostgreSQL connections is true.

Log in to try this activity Interactive activities are free with an account.

Client-side connection pools

A connection pool in the application keeps a set of open connections and lends them to requests. A request borrows a connection, runs its queries and returns it, so the connection cost is paid once and reused thousands of times. psycopg provides psycopg_pool.ConnectionPool (and an asynchronous version), created once when the application starts.

import os
from psycopg_pool import ConnectionPool

pool = ConnectionPool(
    conninfo=f"host={os.environ['PGHOST']} dbname={os.environ['PGDATABASE']} sslmode=require",
    min_size=2, max_size=10, max_idle=300, open=True)

def get_document(doc_id):
    with pool.connection() as conn:          # borrowed, then returned automatically
        return conn.execute("SELECT title FROM documents WHERE id = %s", (doc_id,)).fetchone()

max_size caps how many connections one process holds, which must be multiplied by the number of processes and replicas when comparing with max_connections. With Microsoft Entra authentication, the pool must supply a fresh token whenever it opens a new connection, for example through a custom connection class or a configure callback that fetches the token from DefaultAzureCredential.

Fill in the value

Counting connections

Exam skills 2.2.6

Work out how many connections client-side pools can open.

Log in to try this activity Interactive activities are free with an account.

The built-in PgBouncer

A client-side pool works within one process. When there are many processes, such as dozens of function instances or container replicas, their pools together can still exceed the server's limit. PgBouncer, a lightweight connection pooler built into flexible server, solves this on the server side: many client connections share a smaller number of real server connections. It is enabled with the pgbouncer.enabled server parameter and listens on port 6432 on the same host; applications switch to it by changing the port.

The built-in PgBouncer uses transaction pooling by default: a server connection is assigned to a client only for the duration of a transaction. This multiplexes efficiently but means that session state does not persist between transactions, so features such as session-level SET commands, advisory locks held across transactions and some prepared statement usage need care. PgBouncer is not available on the Burstable tier.

Client-side pool
Runs inEach application process
Limits connections acrossOne process
Best forLong-running apps with few instances
CaveatsTotal grows with instances
Choose when A few long-lived API instances
Built-in PgBouncer
Runs inThe database server, port 6432
Limits connections acrossAll clients together
Best forServerless and highly scaled-out clients
CaveatsTransaction pooling drops session state; not on Burstable
Choose when Many short-lived or scaled-out instances

The two are often combined: each instance keeps a small client pool that connects to PgBouncer, which keeps the total server connection count low.

The following diagram compares how serverless functions handle database connections before and after the fix.

Connection handling before and after the fix. Each invocation of the 150 function instances opened its own connection, paying about 40 ms of set-up and exhausting the server's connection slots. With a module-level pool in each instance and the built-in PgBouncer on port 6432, the instances reuse connections and share a limited number of server connections.
Because PgBouncer uses transaction pooling, code should not depend on session-level settings.

Reducing latency and raising throughput

Beyond pooling, several practices reduce the time each request spends on the database.

  • Place the application near the database: same region, ideally the same availability zone, over private networking, because every round trip adds network latency.
  • Reduce round trips: fetch what is needed in one query with joins, batch writes with executemany or COPY, and avoid query-per-row loops.
  • Return less data: select only needed columns, especially avoiding embedding columns when they are not used.
  • Set timeouts: connect_timeout and statement_timeout stop slow operations from tying up pool connections.
  • Retry transient errors: during a high availability failover or a scaling operation, connections drop briefly; retries with backoff make the application resilient.
  • Offload reads: send read-only queries, such as retrieval, to read replicas when the primary is busy with writes.
Match the pairs

Reducing database time

Exam skills 2.2.6

Match each problem with the practice that addresses it.

Log in to try this activity Interactive activities are free with an account.
Worked example

A function app that exhausts connections

A Python function app on the Flex Consumption plan answers retrieval requests from PostgreSQL. It opens a new connection in each invocation. During peaks the app scales to 150 instances, and the server, a General Purpose server, starts rejecting connections with "remaining connection slots are reserved". Average latency also includes about 40 ms of connection set-up.

The fix has two parts. Enable the built-in PgBouncer and point the function app at port 6432, so that the 150 instances share a limited number of server connections. And create a small module-level connection pool in the function code, so that each instance reuses its connections across invocations instead of paying the set-up cost every time. Because PgBouncer uses transaction pooling, the code should not depend on session-level settings.

Raising max_connections would allow more processes but each consumes memory, and the limit would be reached again at higher scale. Scaling the server up adds cost without removing the per-invocation connection overhead. Capping the function app's scale-out would protect the database by refusing user traffic.

Check yourself

On which port does the built-in PgBouncer listen, and which tier does not support it?

Show answer

PgBouncer listens on port 6432 on the same host. It is not supported on the Burstable tier.

Exam Tips

Remember for the exam

  • Each PostgreSQL connection is a server process; opening one costs tens of milliseconds.
  • Create one client-side pool per process at start-up and borrow connections from it.
  • Enable built-in PgBouncer (port 6432) for many scaled-out clients; it uses transaction pooling.
  • Keep the app close to the database, batch round trips and retry transient failover errors.