CloudNativePG in production: running PostgreSQL on Kubernetes without fear
For years, my stance on running stateful databases inside Kubernetes was simple: don’t do it. Managed services like AWS RDS or GCP Cloud SQL were worth every penny of their markup because they shifted the operational nightmare of failover, WAL archiving, and point-in-time recovery (PITR) to someone else.
That changed when our high-frequency tick store and execution database hit RDS scaling walls. We were dropping $18,000 a month on large db.r6g.8xlarge instances while fighting connection pool limits, WAL replication lag during high-volatility trading spikes, and restrictive cloud vendor parameter groups. We needed bare-metal NVMe performance, local NVMe storage classes, custom PostgreSQL extensions, and tight integration with our internal Kubernetes network overlay.
I tried statefulsets with custom Helm charts. I tried the Zalando Postgres Operator. I tried Stolon. Every option broke during real-world failure injection tests: network partitions caused split-brain writes, or failovers took 45 seconds while connection strings stalled.
Then we migrated our core cluster to CloudNativePG (cloudnative-pg). In this post, I will share the exact manifests, physical storage architectures, failure modes, and code we deployed to run PostgreSQL on Kubernetes in production—handling over 14,000 write transactions per second at sub-10ms p99 latency without losing a single byte of WAL data.
The Failure Mode That Forced Our Hand
Our legacy setup relied on standard Kubernetes StatefulSet primitives backed by EBS volumes (gp3). During a high-volatility trading period on November 14th, a Kubernetes node experienced a kernel panic. The control plane marked the node NotReady, but because the node was unresponsive, the EBS volume stayed attached to the dead instance for 6 minutes while the control plane waited for the node controller timeout.
When the secondary pod was forcibly booted on another node, the persistent volume claim (PVC) could not attach. The cluster was stuck in a ContainerCreating loop:
Type Reason Age From Message
—- —— —- —- ——-
Warning FailedAttachVolume 2m14s attach-detach-controller Multi-Attach error for volume “pvc-8b9a11f2-41a8-4c22-b901” Volume is already exclusively attached to one node and cannot be attached to another.
The database was down for 11 minutes. Connection pools choked, trading engines threw exceptions, and our execution pipeline halted.
We evaluated cloudnative-pg specifically because it discards the old StatefulSet pattern entirely. Instead of relying on Kubernetes to manage stateful volume attachments during failovers, cloudnative-pg manages pods directly using a cloud-native architecture: fast, local NVMe drives attached to dedicated nodes, combined with streaming replication and immediate object-storage WAL fencing via Barman Object Store.
Architecture: CloudNativePG Design Patterns
Here is how our production database architecture looks inside the Kubernetes cluster.
flowchart TD client["Trading Application"] rwService["ClusterIP RW Service"] roService["ClusterIP RO Service"] primaryPod["Primary Postgres Pod"] replica1Pod["Replica 1 Pod"] replica2Pod["Replica 2 Pod"] s3Bucket["S3 Compatible Storage"] client -->|"Writes"| rwService client -->|"Reads"| roService rwService --> primaryPod roService --> replica1Pod roService --> replica2Pod primaryPod -->|"Streaming WAL"| replica1Pod primaryPod -->|"Streaming WAL"| replica2Pod primaryPod -->|"Barman WAL Archive"| s3Bucket
Key design decisions:
1. No StatefulSets: CloudNativePG creates individual Pod objects directly. This gives the operator granular control over pod deletion order, volume fencing, and node isolation.
2. Integrated Backup via Barman: Streaming WAL logs are pushed directly to S3-compatible object storage asynchronously without relying on external cron jobs or sidecars that can fail silently.
3. Primary-First Failover: When the primary fails, CloudNativePG executes a fence on the old node, promotes the replica with the lowest WAL lag, and updates the ClusterIP services in under 3 seconds.
Step-by-Step Production Setup
1. Operator Installation and Configuration
We install the operator using Helm, pinned to a specific release, with strict resource requests for the operator deployment itself to ensure it is never evicted during node pressure.
helm repo update
helm upgrade –install cnpg-operator cnpg/cloudnative-pg \
–namespace cnpg-system \
–create-namespace \
–set resources.requests.cpu=“200m” \
–set resources.requests.memory=“256Mi” \
–set resources.limits.cpu=“500m” \
–set resources.limits.memory=“512Mi”
Verify operator health:
bash
NAME READY UP-TO-DATE AVAILABLE AGE
cnpg-operator 1/1 1 1 42d
2. Physical Manifest Definition
Below is the exact Cluster definition we use for our high-throughput trading cluster (prod-pg-main). It includes:
– Synchronous replication settings for zero data loss (Any 1).
– Custom PostgreSQL engine tuning parameters for memory, WAL, and connection behavior.
– Barman object storage configuration for continuous archiving to AWS S3.
– Anti-affinity rules to guarantee pods land on separate physical racks/nodes.
kind: Cluster
metadata:
name: prod-pg-main
namespace: database
spec:
instances: 3
imageName: ghcr.io/cloudnative-pg/postgresql:16.2
# Primary failover strategy and sync constraints
postgresql:
parameters:
max_connections: “500”
shared_buffers: “16GB”
effective_cache_size: “48GB”
maintenance_work_mem: “2GB”
work_mem: “32MB”
min_wal_size: “4GB”
max_wal_size: “16GB”
checkpoint_completion_target: “0.9”
checkpoint_timeout: “15min”
wal_buffers: “16MB”
default_statistics_target: “100”
random_page_cost: “1.1”
effective_io_concurrency: “200”
synchronous_commit: “on”
# Enforce non-overlapping physical placements
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
– weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
– key: cnpg.io/cluster
operator: In
values:
– prod-pg-main
topologyKey: kubernetes.io/hostname
# Dedicated local NVMe storage configuration
storage:
size: 500Gi
storageClass: local-nvme-sc
# Automated Continuous Archiving via Barman
backup:
barmanObjectStore:
destinationPath: s3://prod-pg-backups-us-east-1/prod-pg-main/
endpointURL: https://s3.us-east-1.amazonaws.com
s3Credentials:
awsCredentials:
secretAccessKey:
name: aws-s3-credentials
key: AWS_SECRET_ACCESS_KEY
accessKeyId:
name: aws-s3-credentials
key: AWS_ACCESS_KEY_ID
wal:
compression: gzip
maxParallel: 8
data:
compression: gzip
# Node resource allocations
resources:
requests:
cpu: “8”
memory: “32Gi”
limits:
cpu: “16”
memory: “32Gi”
# Monitoring configuration
monitoring:
enablePodMonitor: true
Apply this manifest to provision the database infrastructure:
kubectl apply -f prod-pg-main.yaml -n database
Failure Injection and Chaos Testing
Deploying an operator is easy; proving it works under live fire is where most teams fail. We executed two chaos scenarios using Chaos Mesh and manual infrastructure tearing.
Test 1: Abrupt Primary Node Termination (kill -9 on Instance)
We simulated a hard infrastructure freeze by power-cycling the worker node running the primary database instance.
kubectl cnpg status prod-pg-main -n database
Output showing the active primary pod:
Name: prod-pg-main
Namespace: database
System ID: 7342119402918481029
PostgreSQL Image: ghcr.io/cloudnative-pg/postgresql:16.2
Primary instance: prod-pg-main-1
Status: Cluster in healthy state
Instances: 3
Ready instances: 3
Instances status
Name Status Gateway status Replication role Serial
—- —— ————– —————- ——
prod-pg-main-1 OK Healthy Primary 1
prod-pg-main-2 OK Healthy Standby (sync) 2
prod-pg-main-3 OK Healthy Standby (potential) 3
Now force-delete the primary pod without graceful shutdown:
Watch the operator respond immediately in the controller logs:
text
2024-03-22T14:10:02.104Z INFO controller/postgres “Primary instance is dead” {“cluster”: “prod-pg-main”, “pod”: “prod-pg-main-1”}
2024-03-22T14:10:02.148Z INFO controller/postgres “Fencing old primary” {“cluster”: “prod-pg-main”, “pod”: “prod-pg-main-1”}
2024-03-22T14:10:02.312Z INFO controller/postgres “Promoting standby to primary” {“cluster”: “prod-pg-main”, “target”: “prod-pg-main-2”}
2024-03-22T14:10:04.819Z INFO controller/postgres “Updated endpoint – RW pointed to new primary” {“endpoint”: “prod-pg-main-rw”, “targetPod”: “prod-pg-main-2”}
Total failover time to update the service target was 2.71 seconds. Our Python application connection pool (psycopg3) re-routed traffic instantly thanks to TCP keepalives and target_session_attrs=read_write.
Test 2: Network Partition and Split-Brain Prevention
We injected a unilateral network drop between the Primary (prod-pg-main-1) and the rest of the cluster using a NetworkPolicy.
kind: NetworkPolicy
metadata:
name: isolate-primary
namespace: database
spec:
podSelector:
matchLabels:
statefulset.kubernetes.io/pod-name: prod-pg-main-1
policyTypes:
– Ingress
– Egress
ingress: []
egress: []
bash
kubectl apply -f isolate-primary.yaml
Results:
1. The operator lost quorum access to prod-pg-main-1.
2. prod-pg-main-2 detected missing heartbeats from the primary.
3. Synchronous commit requirements blocked writes on prod-pg-main-1 immediately (preventing split-brain data corruption).
4. prod-pg-main-2 was promoted to primary.
5. Once the network policy was deleted, prod-pg-main-1 re-joined the cluster automatically, demolished its own inconsistent timeline, and re-cloned state from prod-pg-main-2 using pg_rewind.
bash
Instances status
Name Status Gateway status Replication role Serial
—- —— ————– —————- ——
prod-pg-main-1 OK Healthy Standby (sync) 4
prod-pg-main-2 OK Healthy Primary 2
prod-pg-main-3 OK Healthy Standby (potential) 3
Python Load Testing Script (psycopg3 + Connection Pooling)
To verify client resiliency during failovers, we ran an aggressive multi-threaded write load test using Python 3.11 with psycopg-pool. The script dynamically follows read-write IP switches without throwing unhandled exceptions.
import time
import logging
import random
from concurrent.futures import ThreadPoolExecutor
import psycopg
from psycopg_pool import ConnectionPool
logging.basicConfig(level=logging.INFO, format=“%(asctime)s [%(levelname)s] %(message)s”)
# Connection string uses the RW service DNS and specifies read_write requirement
DB_CONN_STRING = (
“host=prod-pg-main-rw.database.svc.cluster.local “
“dbname=trading “
“user=postgres “
“password=production_secure_pass “
“connect_timeout=3 “
“target_session_attrs=read_write”
)
pool = ConnectionPool(
conninfo=DB_CONN_STRING,
min_size=10,
max_size=50,
timeout=5.0
)
def init_db():
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(“””
CREATE TABLE IF NOT EXISTS trade_orders (
order_id UUID PRIMARY KEY,
symbol VARCHAR(16) NOT NULL,
price NUMERIC(12, 4) NOT NULL,
quantity INT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
“””)
conn.commit()
def execute_trade(worker_id: int):
success = 0
errors = 0
for _ in range(500):
order_id = f”{random.randint(10000000, 99999999)}-0000-0000-0000-000000000000″
symbol = random.choice([“BTCUSD”, “ETHUSD”, “SOLUSD”, “NVDA”, “AAPL”])
price = round(random.uniform(10.0, 50000.0), 4)
qty = random.randint(1, 100)
committed = False
while not committed:
try:
with pool.connection(timeout=3.0) as conn:
with conn.cursor() as cur:
cur.execute(
“INSERT INTO trade_orders (order_id, symbol, price, quantity) VALUES (%s, %s, %s, %s)”,
(order_id, symbol, price, qty)
)
conn.commit()
committed = True
success += 1
except (psycopg.OperationalError, psycopg.DatabaseError) as e:
errors += 1
logging.warning(f”Worker {worker_id} transient error: {e}. Retrying…”)
time.sleep(0.5)
return success, errors
if __name__ == “__main__”:
logging.info(“Initializing Schema…”)
init_db()
logging.info(“Starting load testing across 10 threads…”)
start_time = time.time()
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(execute_trade, i) for i in range(10)]
results = [f.result() for f in futures]
total_success = sum(r[0] for r in results)
total_errors = sum(r[1] for r in results)
elapsed = time.time() – start_time
logging.info(f”Complete. Writes: {total_success}, Retried Faults: {total_errors}, Elapsed: {elapsed:.2f}s”)
logging.info(f”Throughput: {total_success / elapsed:.2f} write ops/sec”)
During a simulated primary pod kill while running this script:
– Zero records were dropped.
– Transient errors spiked for 2.3 seconds (handled gracefully by application retries).
– Total write operations stabilized quickly after target DNS re-resolution.
Verification and Performance Benchmarks
After migrating our tick database from AWS RDS (db.r6g.8xlarge) to CloudNativePG running on physical worker nodes with local NVMe SSDs (i3en.3xlarge equivalent instances in EKS), we benchmarked the latency profiles using pgbench.
Performance Comparison
| Metric | AWS RDS Postgres (db.r6g.8xlarge) |
CloudNativePG (Local NVMe) | Impact |
|---|---|---|---|
| Write TPS (Sync Commit) | 4,200 ops/sec | 14,850 ops/sec | +253% Throughput |
| Read TPS (Scaled) | 31,000 ops/sec | 68,200 ops/sec | +120% Throughput |
| p95 Latency | 18.4 ms | 3.1 ms | 83% Drop |
| p99 Latency | 42.1 ms | 7.8 ms | 81% Drop |
| Monthly Infrastructure Cost | $18,400 / mo | $6,100 / mo | 66% Reduction |
Executing Benchmark Command
kubectl cnpg psql prod-pg-main 1 -n database — -c “CREATE DATABASE bench;”
kubectl exec -it prod-pg-main-1 -n database -c postgres — \
pgbench -i -s 100 -U postgres bench
bash
# Run 16-thread, 64-connection latency benchmark for 300 seconds
kubectl exec -it prod-pg-main-1 -n database -c postgres — \
pgbench -c 64 -j 16 -T 300 -P 5 bench
Sample run output under peak load:
scaling factor: 100
query mode: simple
number of clients: 64
number of threads: 16
maximum number of tries: 1
duration: 300 s
number of transactions actually processed: 4455800
latency average = 4.308 ms
latency stddev = 2.112 ms
initial connection time = 42.102 ms
tps = 14852.219804 (without initial connection time)
Lessons Learned and Production Rules
1. Always Use Local Storage Classes for Heavy Writes
Network-attached block storage (like AWS EBS or GCP Persistent Disk) introduces network hop latency for every WAL flush. When using synchronous replication in CloudNativePG, network storage doubles your write latency overhead. Deploy your operator on nodes with local NVMe drives using a provisioner like sig-storage-local-static-provisioner or Topolvm.
2. Set Connection Limits at the Proxy Layer
CloudNativePG creates native Kubernetes services (-rw, -ro), but Kubernetes ClusterIP proxying is not a connection pooler. If your microservices open thousands of raw connections during a traffic surge, PostgreSQL will exhaust memory due to backend process overhead. Deploy PgBouncer alongside your application or use CloudNativePG’s managed Pooler resource:
kind: Pooler
metadata:
name: prod-pg-main-pooler
namespace: database
spec:
cluster:
name: prod-pg-main
instances: 3
type: rw
pgbouncer:
poolMode: transaction
parameters:
max_client_conn: “5000”
default_pool_size: “50”
3. Tune Kernel Parameters on Worker Nodes
PostgreSQL inside a pod is still bounded by the host kernel options. Ensure your host worker node sysctl configuration allows deep socket queues and memory mapping before launching heavy instances:
sysctl -w vm.overcommit_memory=2
sysctl -w vm.overcommit_ratio=80
sysctl -w net.core.somaxconn=4096
4. Continuous PITR Testing is Non-Optional
An automated backup is useless until proven recoverable. We run a nightly Kubernetes CronJob that creates a restored staging cluster directly from our S3 WAL archive using CloudNativePG’s bootstrap.recovery spec to verify data integrity automatically.
Final Verdict
Moving PostgreSQL to Kubernetes was historically considered an anti-pattern because standard Kubernetes primitives (StatefulSets, naive PVC controllers) were designed for stateless microservices.
CloudNativePG changes this dynamic fundamentally. By giving the operator direct ownership over pod creation, network fencing, WAL archiving, and timeline promotion, it eliminates the failure modes of legacy storage controllers. We achieved zero-data-loss failover in under 3 seconds, lowered overall infrastructure spend by 66%, and unlocked raw local NVMe execution speeds that managed database platforms simply cannot match at scale.