The Sidecar Database: Reimagining Connection Pooling with Envoy and eBPF
Relying on static in-process connection pools across autoscaling Kubernetes pods guarantees self-inflicted database connection storms, while centralized proxy fleets introduce shared single points of failure and extra cross-AZ hops.
TL;DR
- Problem: Kubernetes HPA scaling multiplies per-pod HikariCP or
pgxpoolpools into thousands of PostgreSQL backend processes, while centralized PgBouncer tiers create shared blast radiuses and DNS failover lag.- Answer: Combine a pod-local transaction pooler, an Envoy sidecar fed by an xDS control plane for instant primary/replica routing, and an eBPF
sockmapprogram to bypass the loopback TCP/IP stack.- Watch out: Envoy’s
postgres_proxy+tcp_proxymaintains a 1:1 connection mapping (it does not multiplex like PgBouncer), per-pod sidecars amplify cluster RAM at thousands of pods, and transaction pooling breaks session-levelPREPAREandpg_advisory_lock.
Situation
Kubernetes replaced static virtual machine fleets with elastic microservice pods written in Java, Go, Python, and Node.js. Meanwhile, the underlying data plane remains anchored in stateful relational databases such as Patroni-managed PostgreSQL clusters, Amazon RDS/Aurora, and MySQL topologies.
Historically, teams managed database connections using two patterns:
- Application-Level Connection Pooling: Libraries embedded inside each service process (HikariCP in Java,
database/sqlorpgxpoolin Go, SQLAlchemy in Python). - Centralized Proxy Fleets: Shared intermediate tiers (PgBouncer, Odyssey, ProxySQL, or AWS RDS Proxy) placed in front of database primaries to multiplex client connections over fewer backend processes.
In static deployments, both patterns hold. Under aggressive Horizontal Pod Autoscaling (HPA), however, their assumptions break down simultaneously.
The Problem
- The Autonomous Pod Connection Storm: In-process pools have zero visibility into global cluster scale. If each pod configures HikariCP with
minimumIdle = 10andmaximumPoolSize = 20, scaling from 200 pods to 2,000 pods during a traffic spike triggers 18,000 to 36,000 concurrent TCP and TLS handshakes (and up to 40,000 open connections at max pool size). Because PostgreSQL forks a dedicated OS backend process per connection—typically consuming roughly 5–10 MB of private memory plus shared-memoryPGPROCand lock-array slots—40,000 simultaneous backends would demand 200–400 GB of RAM for connection state alone, exhaustingmax_connections, triggering kernel OOM kills, and stalling CPU scheduling on context switches before query load even arrives. - Centralized Proxy Blast Radius & Latency: Shared PgBouncer or ProxySQL clusters prevent backend exhaustion, yet centralizing the proxy creates a shared failure domain. A bad config reload, single-threaded epoll saturation (PgBouncer is single-threaded per process), or AZ network blip drops every dependent microservice at once while adding an extra network hop on every round-trip.
- Prepared Statement Collisions in Transaction Pooling: To achieve high N:1 multiplexing, proxies run in transaction pooling mode, returning the backend socket after each
COMMIT. Drivers that issue named server-sidePREPAREstatements on connection A fail withERROR: prepared statement "S_1" does not existwhenEXECUTElands on backend connection B unless unnamed statements or pooler-level prepared statement tracking are enabled. - Stale Client DNS Caching During Failover: When Patroni or RDS Multi-AZ promotes a standby, DNS updates propagate asynchronously. Runtimes that cache DNS records aggressively (such as legacy JVM
networkaddress.cache.ttlconfigurations) keep routing writes to the demoted read-only primary until pods restart.
The core engineering question is: How can platform teams give autoscaling Kubernetes pods multiplexed connection pooling, sub-second failover routing, and low loopback overhead without creating a centralized proxy single point of failure?
Options Considered
| Approach | Multiplexing & Routing | Where It Breaks | Decision |
|---|---|---|---|
App-Only Pools (HikariCP / pgxpool) | Direct to DB; zero proxy hop | O(N pods) connection storm on HPA; slow DNS failover | Rejected — crashes primaries under HPA |
| Centralized Proxy Tier (PgBouncer / RDS Proxy) | Strong N:1 transaction pooling | Shared failure domain across services; extra cross-AZ hop | Partial — simpler for small/medium fleets |
Envoy Sidecar Alone (postgres_proxy) | xDS dynamic endpoints + per-port primary/replica listeners + TLS | tcp_proxy is 1:1 per stream; does not perform PgBouncer N:1 multiplexing | Rejected alone — still passes pod pool fan-out |
Local Pooler + Envoy xDS + eBPF sockmap | Pod-local N:1 pooling, xDS failover, loopback bypass | Higher per-pod RAM than node proxies; requires transaction-pool hygiene | Chosen — isolated, elastic, xDS-driven |
Many engineers assume Envoy’s postgres_proxy filter replaces PgBouncer. In practice, Envoy’s postgres_proxy + tcp_proxy chain maintains a 1:1 downstream-to-upstream TCP connection mapping (the filter only parses traffic for statistics; it does not split reads and writes, so primary and replica traffic use separate listeners or ports, each mapped to its own cluster). Pairing a lightweight local transaction pooler (or bounding the pod pool to 1–2 connections) with Envoy xDS gives you both connection clamping and instant endpoint discovery, while eBPF sockmap removes the loopback TCP stack tax.
The Envoy Sidecar Architecture: Edge Routing with Local Pooling and eBPF
In this architecture, the application container connects to 127.0.0.1:5432 with a tiny local pool (2–4 connections). Inside the same pod network namespace, a local transaction pooler multiplexes concurrent app threads onto 1–2 persistent connections to Envoy, or Envoy enforces strict upstream circuit breakers (max_connections) fed by an xDS control plane. An eBPF sockmap program attached at the host kernel bypasses the loopback TCP/IP stack for pod-local sockets.
flowchart TD
A[App Container — localhost:5432] --> B[eBPF sockmap — SK_MSG Bypass]
B --> C[Local Pooler + Envoy Sidecar]
D[xDS Control Plane — Patroni/RDS Watch] --> C
C --> E[PostgreSQL Primary — Bounded Pool]
C --> F[PostgreSQL Read Replica]
1. Wire Protocol Inspection and Read/Write Splitting in Envoy
Envoy’s envoy.filters.network.postgres_proxy filter decodes PostgreSQL v3.0 wire frames (Query, Parse, Bind, Execute, ReadyForQuery) for observability metrics only. It is not a router or pooler, so primary/replica routing is done with separate listeners (for example port 5432 to the primary cluster and 5433 to the replica cluster) while xDS updates each cluster’s endpoints on failover:
filter_chains:
- filters:
- name: envoy.filters.network.postgres_proxy
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.postgres_proxy.v3alpha.PostgresProxy
stat_prefix: postgres
enable_sql_parsing: true
- name: envoy.filters.network.tcp_proxy
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy
stat_prefix: tcp
# One listener per role: this listener (port 5432) maps to the primary cluster;
# a second listener (port 5433) with the same chain maps to "pg_cluster_read".
cluster: "pg_cluster_write"
Because postgres_proxy cannot decode messages after an SSL handshake takes place inside the stream, TLS should be terminated at the Envoy listener or offloaded to Envoy’s upstream mTLS transport socket so Envoy can inspect unencrypted loopback traffic and wrap it in mTLS over the cluster network. When split_rw is enabled, postgres_proxy also tracks PostgreSQL’s ReadyForQuery transaction-status byte ('I' for idle, 'T' for inside a transaction block, 'E' for failed transaction): once a client sends BEGIN, subsequent SELECT statements inside that transaction stay pinned to the primary (write_cluster_name) until COMMIT or ROLLBACK returns the session to idle, preventing mid-transaction read-your-writes violations.
2. eBPF sockmap: Eliminating the Sidecar Loopback Tax
Running a sidecar normally forces every packet through the Linux loopback TCP/IP stack twice (socket buffer -> IP routing -> netfilter iptables -> loopback -> receiving socket). An eBPF BPF_PROG_TYPE_SK_MSG program attached to a sockmap / sockhash intercepts send() calls between co-located sockets on 127.0.0.1 and redirects payloads directly to the peer socket’s ingress queue:
SEC("sk_msg")
int bpf_tcp_msg_redirect(struct sk_msg_md *msg) {
if (msg->remote_ip4 == 0x7f000001 && msg->local_ip4 == 0x7f000001) {
if (msg->remote_port == bpf_htons(5432)) {
return bpf_msg_redirect_hash(msg, &sock_map, &msg->remote_ip4, BPF_F_INGRESS);
}
}
return SK_PASS;
}
By skipping TCP segmentation, checksums, and netfilter traversal on loopback, sockmap reduces sidecar CPU overhead and tail latency without requiring any changes to the application binary or database driver. Under the hood, two eBPF hooks cooperate: a BPF_PROG_TYPE_SOCK_OPS program attached to the cgroup intercepts BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB and BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB events when the app and sidecar complete their 127.0.0.1 three-way handshake, inserting both socket descriptors into the shared sock_map hash table keyed by their 4-tuple. On every subsequent send(), the BPF_PROG_TYPE_SK_MSG program looks up the peer socket in sock_map and copies the buffer directly to the peer’s receive queue. Teams whose drivers natively support Unix domain sockets (such as Go pgx or Python psycopg) can alternatively mount a pod-local emptyDir socket path to avoid TCP TIME_WAIT altogether, whereas Java JDBC services—which lack built-in Unix socket transport without JNI—rely on 127.0.0.1 + sockmap.
3. xDS Control Plane: Dynamic Quotas and Failover
An xDS management server (using go-control-plane or Istio) watches two signals: active pod count ($P_{\text{active}}$) from Kubernetes and primary/replica health from Patroni or the cloud RDS API. Given a safe database backend budget ($C_{\text{max}}$), the control plane computes the per-pod upstream connection quota:
$$\text{Per-Pod Max Connections} = \max\left(1,; \left\lfloor \frac{C_{\text{max}}}{P_{\text{active}}} \right\rfloor\right)$$
When HPA scales pods from 200 to 1,000 against a 2,000-connection budget, xDS pushes updated Envoy Cluster Discovery Service (CDS) circuit-breaker limits (max_connections: 2) and Endpoint Discovery Service (EDS) primary IPs over gRPC streaming. During a Patroni failover, Envoy drains connections to the demoted primary and opens connections to the newly promoted primary without waiting for JVM DNS caches to expire.
How It Rolls Out
Rolling out sidecar database proxies requires cleaning up session-scoped SQL anti-patterns before injecting proxies into production pods:
- Phase 1 — Session Hygiene Audit: Audit application code for session-scoped state that breaks transaction pooling: named
PREPAREstatements,SET search_path/SET timezone, temporary tables, and session-levelpg_advisory_lock. Migrate to unnamed statements,SET LOCAL, andpg_advisory_xact_lock. Gate: zero session-state errors in staging transaction-pool tests. - Phase 2 — Sidecar Canary Without eBPF: Inject the local pooler + Envoy sidecar into a single non-critical service in staging, pointing the app at
127.0.0.1:5432and keeping HikariCP/pgxpoolcapped at 2–4 connections. Gate: p99 query latency and sidecar memory stay within budget. - Phase 3 — eBPF
sockmapDaemonSet: Deploy theBPF_PROG_TYPE_SK_MSGDaemonSet on Linux 5.4+ (6.1 LTS recommended) worker nodes and verify attachment withbpftool prog list. Gate: loopback CPU usage drops under load without socket stalls. - Phase 4 — xDS Quota Clamping & Failover Drill: Connect the xDS control plane to Patroni/RDS health checks, run a 5x HPA scale-out test, and trigger a controlled primary failover. Rollback: flip the application
DATABASE_URLsecret back to the direct database or central proxy endpoint and remove the sidecar injection annotation.
In Practice
I have not operated a 3,000-pod Envoy + sockmap PostgreSQL mesh personally; the design constraints above derive from PostgreSQL’s documented process model, Envoy’s postgres_proxy specification, and Cilium’s eBPF sockmap architecture.
- PostgreSQL Process-Per-Connection Overhead: PostgreSQL spawns a dedicated OS backend process for every client connection bounded by
max_connections(100by default), consuming roughly 5–10 MB of private memory plus shared-memory tracking per backend—which is why unbounded client pools exhaust memory during connection bursts (PostgreSQL Connection Settings). - Envoy
postgres_proxyBehavior: Envoy’s PostgreSQL network filter decodes v3.0 wire protocol frames for stats only (no read/write splitting or pooling), whiletcp_proxymaintains a 1:1 connection mapping and ignores encrypted traffic once an SSL handshake starts (Envoy Postgres Proxy Docs). - Cilium eBPF
sockmapLoopback Acceleration: Cilium usesBPF_PROG_TYPE_SOCK_OPSandBPF_PROG_TYPE_SK_MSG(bpf_msg_redirect_hash) to bypass the TCP/IP and netfilter stack for co-located pod-to-sidecar sockets on the same host (Cilium eBPF Datapath). - Kubernetes Native Sidecar Ordering: Standard pod
containersstart and terminate in parallel with the application, which can drop in-flight database transactions if Envoy exits before the app drains. Defining the local pooler and Envoy as Kubernetes native sidecarinitContainerswithrestartPolicy: Always(introduced in Kubernetes 1.28 and beta by default in 1.29) guarantees the proxy is listening before the app container starts and remains alive until the app finishes itspreStopandSIGTERMdrain (Kubernetes Sidecar Containers).
Where It Breaks
| Edge Case | Failure Mechanism | Consequence | Detection & Mitigation |
|---|---|---|---|
| Sidecar RAM Amplification | Every pod runs a dedicated Envoy + pooler container. | At 5,000+ pods, proxy RAM overhead becomes substantial. | Strip unused Envoy HTTP/Lua filters; evaluate node-level proxies (Istio Ambient ztunnel) for huge fleets. |
| CPU Throttling on Bulk Reads | Reporting query returns 500,000 rows through postgres_proxy. | L7 wire parsing hits container CPU limits and throttles I/O. | Bypass enable_sql_parsing for bulk ETL/analytics listeners; enforce query pagination. |
| Prepared Statement Collisions | Named PREPARE stmt_1 runs across multiplexed backend sockets. | ERROR: prepared statement does not exist on next query. | Configure drivers (pgx, JDBC) for unnamed/protocol-level statements or pooler statement caching. |
Loopback TIME_WAIT Exhaustion | App opens/closes short-lived connections to 127.0.0.1:5432. | Ephemeral port exhaustion throws EADDRNOTAVAIL. | Keep persistent local app pool (2–4 conns); set net.ipv4.tcp_tw_reuse = 1. |
| Session Variable Leakage | Client executes SET timezone or SET search_path without LOCAL. | Next multiplexed client inherits contaminated session state. | Use SET LOCAL inside transactions or configure DISCARD ALL on pooler reset. |
| xDS Propagation Lag | Primary fails over before EDS updates reach all sidecars. | Sidecars send writes to demoted primary, hitting read-only errors. | Stream EDS over gRPC; configure active TCP/PG health checks and app retry on 25006 (read_only_sql_transaction). |
Legacy Kernel sockmap Gaps | Nodes run pre-5.4 kernels with incomplete SK_MSG support. | sockmap fails to attach; traffic falls back to full TCP loopback. | Standardize worker AMIs on Linux 6.1 LTS+; alert if bpftool prog list misses sk_msg. |
| Advisory Lock Deadlocks | App acquires session-level pg_advisory_lock over pooled socket. | Lock stays pinned on backend socket after client disconnects. | Ban session advisory locks in pooled services; use pg_advisory_xact_lock. |
April 2026 Update
Between 2023 and 2026, two architectural shifts reduced the operational weight of pod-local database proxies:
- Node-Level Ambient Proxies (Istio Ambient & Cilium): To eliminate per-pod sidecar memory amplification at thousands of pods, teams increasingly offload mTLS and L4 routing to shared per-node Rust/eBPF proxies (
ztunnel+ Ciliumsockmap), reserving L7 database poolers for dedicated pods or per-node pools. - Built-In Pooler Prepared Statement Support: Modern transaction poolers (including PgBouncer 1.21+
max_prepared_statements) added protocol-level named prepared statement tracking, removing the historical tradeoff between transaction multiplexing and JDBC/pgxstatement caching.
Key Takeaways
- Never rely on Envoy
postgres_proxyalone for N:1 multiplexing: Chained withtcp_proxy, Envoy is 1:1 per TCP stream; pair it with a transaction pooler (or tight per-pod circuit breakers) to clamp backend connections. - Bind HPA scale to dynamic xDS quotas: Compute per-pod
max_connectionsfrom total database capacity divided by active pods so autoscaling cannot fork-bomb PostgreSQL. - Use eBPF
sockmapto erase the loopback tax:BPF_PROG_TYPE_SK_MSGredirects co-located127.0.0.1socket buffers directly, avoiding double TCP/IP and netfilter traversal. - Terminate TLS at Envoy, not inside the app-to-sidecar hop:
postgres_proxystops parsing frames after an SSL handshake; keep loopback plaintext (or Unix socket) and let Envoy wrap mTLS to the database. - Enforce transaction-pooling hygiene before rollout: Migrate from session
pg_advisory_lockandSETtopg_advisory_xact_lockandSET LOCAL, or use PgBouncer 1.21+ prepared statement caching.
What to Do Next
- Problem: Check your Kubernetes services for large static
HikariCPorpgxpoolsizes (> 10per pod) that multiply beyond PostgreSQLmax_connectionsduring an HPA spike. - Solution: Pair a pod-local (or per-node) transaction pooler with Envoy xDS routing and eBPF
sockmaploopback acceleration. - Proof: Run a 5x HPA scale-out test in staging and verify that PostgreSQL backend count in
pg_stat_activitystays flat while Envoy EDS switches primaries cleanly on a Patroni failover. - Action: Audit services for session-scoped
PREPAREandpg_advisory_lockcalls this week, then canary the sidecar configuration on a single stateless service.
Sources to Verify
- Envoy Proxy Documentation: PostgreSQL Network Filter (
envoy.filters.network.postgres_proxy) (envoyproxy.io/docs/envoy/latest/configuration/listeners/network_filters/postgres_proxy_filter) - Cilium eBPF Documentation: Socket-Level Load Balancing and
sockmap(docs.cilium.io/en/stable/network/ebpf/) - PostgreSQL Documentation: Connections and Authentication (
max_connections) (postgresql.org/docs/current/runtime-config-connection.html) - PgBouncer Documentation: Protocol-Level Prepared Statements (
max_prepared_statements) (pgbouncer.org/config.html) - Kubernetes Documentation: Sidecar Containers (
kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/)