LIVE β€’ TECH, ENTERPRISE ERP & RETAIL AI JOURNAL
🌐id
βš–οΈIndependent Research • Verified Affiliate Transparency

Mitigating PostgreSQL Connection Exhaustion in Dokploy

Production runbook to mitigate PostgreSQL connection pool exhaustion on Dokploy & Coolify v4 during multi-branch Edge POS re-sync under PSAK 72 standards.

IP
By Iswan Putera β€’ November 23, 2026 15:57 WIB
Mitigating PostgreSQL Connection Exhaustion in Dokploy

When 50+ retail branches running offline-first Edge POS systems experience a sudden WAN recovery after an outage, all edge nodes simultaneously trigger batch re-sync procedures for revenue recognition data under the PSAK 72 standard. On self-hosted PaaS platforms such as Dokploy or Coolify v4, standard architecture relying on a single PostgreSQL container without a third-party connection pooling layer collapses instantly. The default max_connections parameter (typically 100) saturates in milliseconds, throwing FATAL: sorry, too many clients already and completely freezing central financial integration pipelines.

This article presents a production runbook for mitigasi connection pool exhaustion postgresql dokploy coolify using a combination of PgBouncer transaction mode and a custom Rust proxy middleware featuring adaptive token bucket backpressure.

Test Environment & Infrastructure Specs

To ensure architectural accuracy without fabricating live load test metrics, the following lab environment specs were used to validate this pattern:

Parameter Specification
Operating System Ubuntu 22.04 LTS (Lab Environment)
Linux Kernel Linux kernel 5.15+
Network Driver VirtIO / Standard Cloud Network Driver
XDP Mode Not supported
Reference VPS Host Hostinger KVM 4 (4 vCPU AMD EPYC, 16 GB RAM DDR5, 200 GB NVMe RAID)
Target PostgreSQL PostgreSQL 16.2 (Containerized via Docker/Dokploy)
  • Operating System β€” Specification: Ubuntu 22.04 LTS (Lab Environment)
  • Linux Kernel β€” Specification: Linux kernel 5.15+
  • Network Driver β€” Specification: VirtIO / Standard Cloud Network Driver
  • XDP Mode β€” Specification: Not supported
  • Reference VPS Host β€” Specification: Hostinger KVM 4 (4 vCPU AMD EPYC, 16 GB RAM DDR5, 200 GB NVMe RAID)
  • Target PostgreSQL β€” Specification: PostgreSQL 16.2 (Containerized via Docker/Dokploy)

Architectural Heuristic: Coolify v4 and Dokploy use Docker Swarm / standalone container architectures that remain vulnerable to sudden database connection pool exhaustion when dozens of edge nodes re-sync transactions simultaneously. (Limitation: Not yet benchmarked on a live production VPS environment with 100+ concurrent branch nodes).

Edge POS Re-Sync Architectural Topology

The following data flow illustrates how incoming traffic from multiple Edge POS nodes is shaped at the proxy layer before reaching PostgreSQL:

graph TD
 A[Edge POS Node 1..N] -->|Resync Request PSAK 72| B[Rust Proxy Middleware]
 subgraph Edge System & Middleware
 B -->|Adaptive Token Bucket Rate Limiting| C[PgBouncer Sidecar]
 end
 subgraph Dokploy / Coolify v4 Environment
 C -->|pgbouncer transaction mode coolify v4| D[(PostgreSQL Container)]
 end

Step 1: Deploy & Configure PgBouncer Sidecar

Deploying PgBouncer in transaction mode is verified to substantially reduce direct concurrent connection load to PostgreSQL during mass re-sync events.

Verified: Utilizing PgBouncer in transaction mode significantly reduces direct connection overhead on PostgreSQL during mass re-syncs. (Limitation: Transaction mode does not support session-level features such as certain prepared statements without explicit pool_mode tuning).

Create the pgbouncer.ini configuration file within your Dokploy or Coolify v4 deployment:

[databases]
psak72_db = host=postgres_host port=5432 dbname=psak72_db user=pos_sync password=secure_password

[pgbouncer]
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
admin_users = admin_user; Critical Tuning for Edge POS Handshakes
pool_mode = transaction
max_client_conn = 5000
default_pool_size = 25
min_pool_size = 5
reserve_pool_size = 5
reserve_pool_timeout = 3
max_db_connections = 80

Authentication file userlist.txt:

"pos_sync" "md5e21c3b17457788ef929c212ef5ef6643"
"admin_user" "md5123456789abcdef123456789abcdef"

Docker Compose Override for Dokploy / Coolify v4

version: '3.8'
services:
 postgres:
 image: postgres:16-alpine
 environment:
 POSTGRES_DB: psak72_db
 POSTGRES_USER: pos_sync
 POSTGRES_PASSWORD: secure_password
 volumes:
 - pgdata:/var/lib/postgresql/data
 networks:
 - internal_net

 pgbouncer:
 image: edoburu/pgbouncer:latest
 container_name: pgbouncer_sidecar
 volumes:
 -./pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro
 -./userlist.txt:/etc/pgbouncer/userlist.txt:ro
 ports:
 - "6432:6432"
 depends_on:
 - postgres
 networks:
 - internal_net

networks:
 internal_net:
 driver: bridge

volumes:
 pgdata:

Step 2: Implement Rust Proxy Middleware (Adaptive Token Bucket)

To handle the edge pos offline first resync psak 72 traffic spike, the fronting layer requires a rust proxy backpressure token bucket mechanism to limit incoming connection burst rates before saturating PgBouncer’s socket pool.

Below is a minimal tokio-based Rust proxy server enforcing TCP connection stream limits:

// Cargo.toml dependencies:
// tokio = { version = "1.35", features = ["full"] }
// governor = "0.6"

use governor::{Quota, RateLimiter};
use std::num::NonZeroU32;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio::io;

#[tokio::main]
async fn main() -> Result&lt;(), Box<dyn std::error::Error>> {
 let listener = TcpListener::bind("0.0.0.0:7432").await?;
 println!("[RUST PROXY] Listening on port 7432...");

 // Rate limit: Max 50 connection attempts/sec with a burst allowance of 100 tokens
 let quota = Quota::per_second(NonZeroU32::new(50).unwrap()).allow_burst(NonZeroU32::new(100).unwrap());
 let limiter = Arc::new(RateLimiter::direct(quota));

 loop {
 let (client_stream, addr) = listener.accept().await?;
 let limiter_clone = Arc::clone(&limiter);

 tokio::spawn(async move {
 if limiter_clone.check().is_ok() {
 if let Err(e) = proxy_traffic(client_stream, "127.0.0.1:6432").await {
 eprintln!("[PROXY ERROR] Connection from {}: {}", addr, e);
 }
 } else {
 eprintln!("[DROPPED] Backpressure triggered for client {}", addr);
 // Dropping stream cleanly forces backoff algorithm on Edge POS nodes
 }
 });
 }
}

async fn proxy_traffic(mut client: TcpStream, target_addr: &str) -> io::Result&lt;()> {
 let mut server = TcpStream::connect(target_addr).await?;
 io::copy_bidirectional(&mut client, &mut server).await?;
 Ok(())
}

Step 3: Load Testing & Concurrency Verification

Simulate client connection bursts using pgbench directly against PgBouncer (6432) or the Rust Proxy (7432):

# Initialize pgbench schema
pgbench -h 127.0.0.1 -p 6432 -U pos_sync -i -s 10 psak72_db

# Run stress test with 150 concurrent clients (exceeding PostgreSQL default max_connections)
pgbench -h 127.0.0.1 -p 6432 -U pos_sync -c 150 -j 8 -T 60 psak72_db

Verify that PostgreSQL avoids FATAL: sorry, too many clients already by monitoring active sockets directly on the host:

# Check active connections to PostgreSQL on port 5432
netstat -anp | grep:5432 | grep ESTABLISHED | wc -l

# Query PgBouncer pool statistics
psql -h 127.0.0.1 -p 6432 -U admin_user -d pgbouncer -c "SHOW POOLS;"

Operational Gotchas & Solutions

  1. Prepared Statement Errors in Transaction Mode:
  • Issue: Edge POS ORM drivers (e.g., Prisma / TypeORM) fail executing prepared statements because backend TCP sockets switch between transactions.
  • Solution: Append ?pgbouncer=true to the client connection string or set prepareThreshold=0 in the driver config.
  1. Idle Connections in Open Transactions:
  • Issue: Edge clients disconnecting mid-sync leave uncommitted transactions blocking server resources.
  • Solution: Set idle_in_transaction_session_timeout = 5000 (5 seconds) in postgresql.conf.

Technical Limitations (What It Cannot Do)

This mitigation pattern is specifically tailored to protect central database host availability and has explicit operational boundaries:

  • Does not repair corrupted transaction log data on the edge POS application side.
  • Does not replace PSAK 72 compliance audits at the accounting business logic layer.
  • Does not eliminate physical network latency between retail branches and the central cloud server.

Rollback & Disaster Recovery Procedures

In the event of systemic failure (e.g., deadlock within the proxy layer or total proxy unresponsiveness), execute the following emergency rollback steps:

  1. Stop the Rust proxy middleware container:
docker stop rust_proxy_middleware || true
  1. Revert the application connection string directly to the default PostgreSQL port (5432) or bypass PgBouncer if a deadlock occurs:
# Update ENV variables via Dokploy / Coolify v4 UI
DATABASE_URL="postgresql://pos_sync:secure_password@postgres_container:5432/psak72_db"
  1. Restart application services in Dokploy / Coolify v4:
docker restart app_service_container
  1. Verify PostgreSQL error logs to confirm normal connection recovery:
docker logs --tail 100 postgres_container

Conclusion

Combining PgBouncer in transaction mode with a Rust proxy middleware provides a robust defense for self-hosted PaaS deployments on Dokploy or Coolify v4. By capping active PostgreSQL sockets between 25–80, your platform can handle thousands of edge re-sync requests without triggering memory exhaustion or socket exhaustion.

Primary Sources


Cloud Infrastructure Recommendation: To host Dokploy/Coolify v4 along with PgBouncer and PostgreSQL under high disk I/O demands during mass re-sync events, we recommend running on Hostinger KVM VPS infrastructure.

Transparency: Some links in this article are affiliate links that may earn us a commission at no additional cost to you.

IP

Iswan Putera

Principal Software Architect

Software Architect & Senior Systems Engineer with over a decade of hands-on expertise in distributed architectures, Linux private cloud deployments, and enterprise ERP implementations. Serves as Lead Technology Writer at Bijak Technology.

Share
Related Tags:#RetailTech#Edge Computing#Vision POS#Document AI#PSAK#Offline First#Whatsmeow Go#ESC/POS