---
title: "Open sourcing PG Proxy: How we proxy 4 trillion queries a month"
description: "Use PG Proxy to pool PostgreSQL connections, coordinate routing, and integrate database access with your platform’s identity and telemetry systems."
author: "Mia Malden, Eddie Cai, Jonathan Hinds"
date: 2026-12-01
tags: ["database monitoring", "open source", "postgresql", "platform engineering", "load balancing", "authentication", "migration"]
blog_type_id: the-monitor
locale: en
---

Managing PostgreSQL across many applications often means coordinating connection pooling, routing, and database discovery across several tools. Each introduces configurations and operational dependencies that platform teams must account for when scaling infrastructure or moving databases. At Datadog, managing authentication, load balancing, and database migrations across these components required coordination across multiple teams. We’ve spoken previously about [Datadog’s move to self-managed PostgreSQL](https://postgresql.us/events/pgconfus2025/schedule/session/2064-how-and-why-datadog-is-moving-from-cloud-managed-to-self-managed-postgres/) at PGConf NYC and [how we rearchitected to scale PostgreSQL](https://www.postgresql.eu/events/pgconfde2026/schedule/session/7584-more-datacenters-less-problems/) at the PostgreSQL Conference Germany 2026.

Today we’re open sourcing PG Proxy, the production-ready PostgreSQL proxy written in Go that we built to bring these responsibilities together at Datadog. PG Proxy combines connection pooling and traffic management with integration points for authentication, configuration, and telemetry. As workloads grow, scale PG Proxy by adding instances or increasing resources per instance. You can run the supplied application or use its Go library to integrate the proxy with your platform. PG Proxy supports self-managed and cloud-hosted PostgreSQL databases.

In this post, we’ll cover how to:

- [Consolidate PostgreSQL access paths](#consolidate-postgresql-access-paths)
- [Pool connections and scale proxy capacity](#pool-connections-and-scale-proxy-capacity)
- [Coordinate database routing and migrations](#coordinate-database-routing-and-migrations)
- [Connect database access to identity and tracing](#connect-database-access-to-identity-and-tracing)
- [Adapt PG Proxy to your platform](#adapt-pg-proxy-to-your-platform)

## Consolidate PostgreSQL access paths

Although we’ve built our own data stores (such as [Husky](https://www.datadoghq.com/blog/engineering/introducing-husky.md)) for events, many Datadog products depend on PostgreSQL for transactional workloads. Applications previously reached their databases through a mix of direct connections and proxies. Some connected directly, while others passed through combinations of PgBouncer for connection pooling, HAProxy for load balancing and traffic shifting, and Envoy for discovery and health checks. Operating this setup meant maintaining separate configurations, metrics, and scaling behavior for each component.

Before PG Proxy, our proxy layer had many components that allowed applications to reach PostgreSQL on various paths:

![Applications reach PostgreSQL through different combinations of PgBouncer, HAProxy, and Envoy, each with a distinct role.](https://web-assets.dd-static.net/42588/1795552318-postgresql-paths-pg-proxy-feature-announcement.png)

These dependencies made database changes difficult to coordinate. During migrations from cloud-managed PostgreSQL to Kubernetes, we had to coordinate DNS updates, proxy configuration changes, and application redeployments, often waiting for application teams to switch endpoints before completing cleanup. We built PG Proxy to consolidate connection pooling and routing into a common access layer, allowing platform teams to manage database destinations centrally.

![PG Proxy consolidates application traffic management and integrates with platform identity and configuration services.](https://web-assets.dd-static.net/42588/1795552366-pg-proxy-traffic-routing-diagram.png)

## Pool connections and scale proxy capacity

Our previous PostgreSQL access layer created several operational challenges. We lacked consistent visibility into requests across PgBouncer, HAProxy, and Envoy. Authentication relied on shared static database credentials, making it difficult to tie access to individual services. 

We built PG Proxy to address these problems alongside connection pooling. Tracing integrations help us follow requests through the proxy. Authentication hooks connect database access to service identity. Central routing controls let us change database destinations while applications keep the same proxy endpoint.

### Share backend connections across transactions

Applications can keep database connections open even when not running queries, consuming PostgreSQL connection capacity. PG Proxy uses transaction pooling so long-lived client connections can share a smaller pool of backend connections. Each transaction keeps its backend connection until completion, then returns it to the pool.

Named prepared statements let clients reuse parameterized queries and can reduce parsing and planning work. Each statement belongs to a PostgreSQL session. With transaction pooling, a client may receive a connection where its named statement is missing or the same name refers to another client’s query. The pooler must track each client’s statements, map their names to the corresponding backend statements, and prepare them on the assigned connection as needed.

When we began building PG Proxy, PgBouncer did not support protocol-level named prepared statements with transaction pooling. We built support for that combination into PG Proxy so our applications could reuse prepared statements while sharing backend connections. PgBouncer later added the capability in [version 1.21.0 in October 2023.](https://www.pgbouncer.org/changelog.html#pgbouncer-121x)

### Protect existing traffic during overload

An overloaded proxy can drop the connections it is meant to serve. At Datadog, we use PG Proxy with internal load-shedding controls to reject some new connections under CPU or memory pressure. This preserves resources for established connections and reduces the risk of disruption across the instance.

These controls illustrate how PG Proxy can support overload protection. Although Datadog’s internal load-shedding and autoscaling systems are separate from the open source release, we plan to add support for these capabilities in a future release. Our internal PG Proxy deployment also integrates with Database Monitoring to connect proxy traffic with database health and query performance. This integration may be included in a future open source release.

### Scale proxy instances with your workload

PgBouncer is single-threaded, so an individual process cannot distribute its work across multiple CPU cores. Using additional cores requires running additional processes, as described in its[ configuration documentation](https://www.pgbouncer.org/config.html#so_reuseport). In our previous deployment, growth therefore meant operating more PgBouncer instances and adjusting pool sizes to stay within PostgreSQL connection limits.

Each PG Proxy instance can use multiple CPU cores, giving us more flexibility to increase resources per instance as traffic grows. Datadog’s infrastructure handles horizontal and vertical scaling around the proxy. We still account for the total number of proxy instances and their pool sizes when managing database connection capacity. 

Smaller PostgreSQL deployments can also benefit from connection pooling, centralized routing, and integrations with their existing systems. At Datadog, we operate PG Proxy in front of thousands of PostgreSQL hosts and hundreds of logical clusters. The following figures describe our deployment:

| Column 1 | Column 2 |
| --- | --- |
| Messages proxied per month | 4 trillion |
| Messages per second per core | More than 1,000 |
| Authentications per day | More than 200 million |
| Open client connections | More than 600,000 |

## Coordinate database routing and migrations

A common way to distribute load on a database is routing write traffic to the primary database while replicas handle all of the read queries. This works to prevent undue stress on the primary database without jeopardizing the queries’ results. 

With dynamic routing enabled, PG Proxy automatically sends eligible reads to replicas while writes continue to the primary. Clients opt in per connection with a startup option (`pg_proxy.dynamic_routing=true`), and operators can also configure weighted read clusters to distribute reads across clusters. PG Proxy parses the statement that begins each transaction: If it is read-only, such as a plain `SELECT`, `SHOW`, or `BEGIN READ ONLY`, the whole transaction runs on a replica. Classification errs toward the primary, so locking reads, `SELECT … INTO`, `EXPLAIN`, and most function calls stay there. If a replica can’t provide a connection quickly, PG Proxy falls back to the primary. This brings read distribution and traffic shifting, previously handled by separate components, into the proxy.

For connections using dynamic routing, replica lag can delay visibility of recent writes. Applications that need to read their own writes immediately can leave dynamic routing disabled on those connections.

### Coordinate database migrations centrally

PG Proxy separates the database name and address an application uses from the backend destination serving its traffic. That way, applications keep the same proxy address and database name when the backend destination changes. During a migration, operators can update that destination centrally without waiting for application teams to change their connection settings.

At Datadog, our configuration system updates PG Proxy’s routing settings at runtime. During a migration, we can use PG Proxy to direct a small share of eligible reads to a new cluster, evaluate its behavior, and increase that share before coordinating the write cutover. This separation also supports our work to[ unwind a shared database](https://www.datadoghq.com/blog/engineering/unwinding-shared-database.md).

Our internal migration workflows, built on [Temporal](https://temporal.io/), use PG Proxy’s controls to stop new logins, drain active transactions, and update read and write routing. Centralizing these controls gives us one place to improve migration safeguards as we encounter new requirements. Data copying and synchronization remain part of the surrounding migration workflow, and changing the main destination can interrupt transactions that have not drained.

## Connect database access to identity and tracing

Managing database credentials across applications adds operational work when credentials need to be rotated or access requirements change. Tying authentication to service identity lets platform teams manage database permissions per service.

At Datadog, PG Proxy authenticates services using JSON Web Tokens (JWTs). PG Proxy verifies each token and checks which databases the service may access. Our client libraries fetch, cache, and refresh tokens, then send them through the PostgreSQL password field. Application developers can connect through those libraries without managing database passwords themselves. Although this system is not included in the open source release, we built PG Proxy so that you can easily integrate with your own.

You can use PG Proxy’s authentication hooks to connect database access to your own identity system. Your integration verifies the caller and determines its permitted databases. For example, the integration can authorize an `orders-api` service to access an orders database. Datadog’s JWT integration and client helpers remain internal, while the public library provides the extension points for implementing your own policies.

### Trace queries through PG Proxy

Adding a proxy introduces another component to investigate when database requests slow down. Requests in our previous setup could pass through several components on their way to PostgreSQL, making them difficult to trace across the full path. That visibility gap helped motivate our work on PG Proxy. Now, PG Proxy records spans for handling protocol messages, executing and proxying queries, and returning results. When a client supplies supported trace context, these spans can join the application trace, helping engineers distinguish time waiting for backend results from time delivering them to the application.

At Datadog,[ Database Monitoring](https://docs.datadoghq.com/database_monitoring.md) runs on the PostgreSQL databases behind PG Proxy. Application Performance Monitoring traces include PG Proxy spans, adding visibility into request handling alongside database health and query-performance data. PG Proxy’s tracing complements the monitoring already running on those databases. 

![A trace from Datadog’s internal deployment connects an application request with PG Proxy’s query and protocol operations.](https://web-assets.dd-static.net/42588/1795552480-pg-proxy-feature-announcement-trace.png)

You can connect PG Proxy to native Datadog telemetry or OpenTelemetry providers and configure exporters and sampling for your environment. Optional bind-parameter capture adds query values to traces and is disabled by default in the open source library. SQL text and error messages can still contain values, so disabling this option does not redact all query data.

## Adapt PG Proxy to your platform

The open source release includes a production-ready application and a Go library for teams that need custom integrations. PG Proxy provides the protocol handling, pooling, and traffic-management foundation. You can use the supplied application or embed the library in an application tailored to your infrastructure.

When you need custom destination selection, discovery, or health checks, the library lets you connect those functions to your existing systems. You can also load existing settings into PG Proxy and use its centralized configuration controls to manage subsequent changes. These integration points let you adapt database access without rebuilding the proxy’s core connection-management behavior.

Logging, metrics, tracing, and authentication can likewise connect to the systems your platform already uses. This lets your team adopt PG Proxy while retaining its existing operational tools and access policies.

## Get started with PG Proxy

PG Proxy brings PostgreSQL pooling, routing, and platform integrations into a common access layer. It gives application teams a consistent connection point and platform teams centralized controls for managing database traffic. We’re also exploring database safeguards, closer observability integrations, and query optimizations within the proxy.

Explore the PG Proxy source code and documentation to configure the open source application or build an integration with the Go library. Start with a representative workload, evaluate its connection and routing behavior, and connect the identity and telemetry systems your deployment needs. Whether you manage a few databases or a large fleet,[ share your deployment experience and suggestions](https://app.datadoghq.com/forms/share/9b89fe08202cb7a6df9b975e7ebd367faa4b7a071b1e74703ba2c5dfbfb2f3e1) for what we should build next.

To deploy PG Proxy as a PgBouncer drop-in replacement, configure the application via [quick start](https://github.com/DataDog/pg-proxy#quick-start). To deploy PG Proxy as an extensible Go library with hooks for your own authentication and telemetry, build your integration [here](https://github.com/DataDog/pg-proxy/blob/main/docs/site/src/content/docs/reference/configuration/library.md).

If you’re new to Datadog, <!-- Sign-up trigger (sign up for a free 14-day trial) omitted -->.