Every guide I read about running Postgres on Kubernetes had the same step three. Install the Prometheus stack, add a PodMonitor, import the Grafana dashboard. I skipped it. Not because I think Prometheus is wrong, but because I was one person running one database cluster for a product with two paying tenants, and the monitoring stack would have used more memory on that node than the database did.
So I wrote a shell script instead. It runs every 15 minutes, checks six things, and posts to a webhook when one of them looks wrong. I mentioned it briefly in the first post in this series, and a couple of people asked to see the whole thing. This is the whole thing, plus the bugs I hit writing it and the list of problems it will never catch.
Do you actually need Prometheus to monitor a CloudNativePG cluster?
No, not to catch the failures that destroy data. A CronJob that reads the Cluster resource’s status with kubectl and posts to Slack covers the ones that matter most on a small cluster: broken WAL archiving, failed backups, a crashed instance, and a disk filling up. What you lose is history and graphs, which matter later, not on day one.
The thing that made this click for me is that CloudNativePG already does the hard part. The operator watches Postgres constantly and writes what it finds into the Cluster object’s status: a phase string, a list of conditions, a count of ready instances. My script doesn’t monitor Postgres. It reads the operator’s opinion of Postgres and complains when that opinion turns bad.
That’s a much smaller job. It’s maybe 90 lines of sh.
What the script checks, and why those six things
The script checks six conditions, each picked because it’s a way the database can break quietly while the app keeps working fine.
| Check | Fires when | What it usually means |
|---|---|---|
| Cluster phase | not Cluster in healthy state |
operator sees something wrong, read the phase text |
ContinuousArchiving condition |
not True |
WAL isn’t reaching the bucket, point-in-time recovery is silently broken |
LastBackupSucceeded condition |
not True |
last nightly base backup failed |
| Ready instances | fewer ready than spec.instances |
Postgres pod is down or restarting |
| Newest completed backup | older than 36 hours | backups stopped being scheduled at all |
| Data volume | over 80% full | WAL piling up, or a tenant’s table growing fast |
The archiving one is the scariest, and it’s the reason the script exists. When WAL archiving breaks, nothing in the app notices. Requests succeed. Writes commit. Meanwhile every WAL segment that can’t be shipped to object storage stays on the data volume, and your recovery window quietly stops moving forward. You find out the day you need a restore, or the day the disk fills, whichever comes first.
The 36-hour backup age check looks redundant next to LastBackupSucceeded, and I almost cut it. It isn’t. If a backup runs and fails, the condition flips and the first check catches it. But if the ScheduledBackup never fires at all (suspended by hand and forgotten, operator down, someone deletes it), there’s no failed backup to report. The condition stays True from the last good one, forever. Only the age check notices that nothing has happened. Backups run daily at 20:30 UTC, so 36 hours gives one full missed day plus twelve hours of slack before it shouts.
The script itself
Most of it is kubectl get with a jsonpath and a comparison. Here’s the core, trimmed a little:
#!/bin/sh
set -u
NS=$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)
PROBLEMS=""
note() { PROBLEMS="${PROBLEMS}- $1\n"; echo "PROBLEM: $1"; }
cond() {
kubectl get cluster "$CLUSTER" -n "$NS" \
-o "jsonpath={.status.conditions[?(@.type=='$1')].status}" 2>/dev/null
}
PHASE=$(kubectl get cluster "$CLUSTER" -n "$NS" -o jsonpath='{.status.phase}' 2>/dev/null)
[ -n "$PHASE" ] || note "cluster $CLUSTER not found in $NS"
case "$PHASE" in
"Cluster in healthy state"|"") ;;
*) note "cluster phase: $PHASE" ;;
esac
[ "$(cond ContinuousArchiving)" = "True" ] || \
note "WAL archiving is failing - WAL will pile up on the data volume until it is full"
READY=$(kubectl get cluster "$CLUSTER" -n "$NS" -o jsonpath='{.status.readyInstances}' 2>/dev/null)
INSTANCES=$(kubectl get cluster "$CLUSTER" -n "$NS" -o jsonpath='{.spec.instances}' 2>/dev/null)
[ "$READY" = "$INSTANCES" ] || note "ready instances: ${READY:-0}/${INSTANCES:-?}"
The note function is the only design decision in there, really. Every check appends a line to one PROBLEMS string instead of alerting on its own, so a bad night produces one Slack message listing four problems instead of four messages. When the disk is full, archiving is also failing, and the phase is also unhealthy. You want to read that as one story.
The disk check is the only one that has to reach inside the pod. The Cluster status doesn’t report volume usage, so the script finds the primary by label and runs df in the postgres container:
POD=$(kubectl get pods -n "$NS" -l "cnpg.io/cluster=$CLUSTER,role=primary" \
-o jsonpath='{.items[0].metadata.name}' 2>/dev/null)
USED=$(kubectl exec -n "$NS" "$POD" -c postgres -- \
sh -c "df -P /var/lib/postgresql/data | awk 'NR==2 {print \$5}' | tr -d '%'")
That 80% threshold matters more on my setup than it would on yours, probably. The cluster uses the local-path storage class, which is just a directory on the node. The 20Gi in the spec is a request, not a quota. So df inside the pod actually reports the node’s root disk (145G, about 83G free right now), and a runaway database doesn’t stop at 20Gi, it keeps going until it takes every other workload on the node down with it. The alert is the only fence there is.
Three bugs that cost me an evening each
None of these were hard. All of them were the kind where the script looked right and wasn’t.
Alerting mid-backup. CloudNativePG clears LastBackupSucceeded while a backup is pending or running, which is honest of it, the last backup hasn’t succeeded yet because it hasn’t finished. My first version fired a “backup failed” alert every night at 20:30 like clockwork. The fix is to count in-flight backups first and skip both backup checks for that run:
INFLIGHT=$(kubectl get backup -n "$NS" \
-o jsonpath='{range .items[*]}{.status.phase}{"\n"}{end}' 2>/dev/null \
| grep -cE '^(pending|started|running)$')
Dates in busybox. The container image is alpine/k8s, which ships busybox date, not GNU date. Busybox can’t parse an RFC 3339 timestamp like 2026-11-24T20:31:12Z with plain -d, it needs -D with a format string. The annoying part is how it failed: the epoch came back empty, the arithmetic treated that as zero, and the script reported the newest backup as about half a million hours old. Now it tries both forms and reports “could not read the timestamp” instead of a number from 1970.
JSON with real newlines in it. The alert text is built with \n between problems. The first version used echo to build the payload, and the shell’s echo helpfully turned those into actual newline characters. Raw newlines aren’t allowed inside a JSON string, so Slack rejected every alert. The script logged “alert posted” because curl succeeded at sending a request that the other end refused. It’s printf '%s' now, which leaves the \n alone for Slack to interpret.
That last one is the bug that bothers me most, honestly. The alert script failed silently, which is the one thing an alert script exists to not do.
The CronJob around it
The YAML is mostly boring, but four settings in it are deliberate.
spec:
schedule: '7,22,37,52 * * * *'
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 0
ttlSecondsAfterFinished: 3600
template:
spec:
serviceAccountName: app-pg-alerts
restartPolicy: Never
containers:
- name: check
image: alpine/k8s:1.37.0
env:
- name: WEBHOOK_URL
valueFrom:
secretKeyRef:
name: app-pg-alerts
key: WEBHOOK_URL
optional: true
The schedule runs at :07, :22, :37 and :52 instead of every quarter hour, so it never lands on the same minute as the 20:30 backup or anything else scheduled on round numbers. backoffLimit: 0 means a run that finds a problem exits non-zero and stays failed, no retry. A retry would just post the same alert again. The failed Job also shows up in kubectl get jobs, which is a second signal if the webhook itself is down. ttlSecondsAfterFinished: 3600 cleans up finished pods after an hour, because a bad weekend otherwise leaves close to 200 Error pods sitting in the namespace.
The optional: true on the secret is the one I’d have missed. The webhook URL lives in a secret created by hand per namespace, not in git. Without optional, a namespace where nobody created that secret yet can’t even start the container, it sits in CreateContainerConfigError and the check never runs. With it, the job runs, logs what it found, and says the webhook isn’t configured. Much better failure mode.
The whole thing requests 10m of CPU and 32Mi of memory. That’s the actual argument for this approach on a small node.
Giving it only the permissions it needs
The job runs under its own service account with a Role that can read clusters and backups, read pods, and create pods/exec. Nothing else, and nothing cluster-wide.
rules:
- apiGroups: ['postgresql.cnpg.io']
resources: ['clusters', 'backups']
verbs: ['get', 'list']
- apiGroups: ['']
resources: ['pods']
verbs: ['get', 'list']
- apiGroups: ['']
resources: ['pods/exec']
verbs: ['create']
That pods/exec line made me uncomfortable at first, and I still think it’s the weakest part of the design. Exec into the Postgres pod is a lot of power for a job that only wants to run df. If someone got hold of that service account token, they could open a shell next to the database. It’s scoped to one namespace, and the only thing that runs as that account is a script mounted from a ConfigMap I control, but I’d drop that permission the moment there’s another way to read disk usage. Which brings me to the part I keep coming back to.
What this setup can’t see
A CronJob that checks current state every 15 minutes is blind to anything that needs history, anything inside Postgres, and its own death. That’s the honest cost, and it’s bigger than it looks from the table above.
No history. When the disk alert fires at 81%, the script can tell me it’s 81%. It can’t tell me whether it was 79% last week or 40% yesterday. Those are completely different emergencies, and I have to go dig through du output by hand to find out which one I’m in.
Nothing inside Postgres. No query latency, no slow queries, no lock waits, no replication lag (there’s no replica yet, but there will be). And no connection counts, which is the one that actually worries me. In the multi-tenant post I worked out that 20 connections per tenant against max_connections = 100 gives me roughly four busy tenants. Nothing in this script would warn me as that ceiling gets close. I’d find out from a too many clients error in the app logs.
Nothing about the app. Request rates, error rates, response times for the NestJS backend, none of that exists anywhere. This is database-only monitoring, and I should be clear with myself that it’s not monitoring the product.
Its own death. This is the one that keeps me up. If the CronJob stops being scheduled, nobody gets told. If the controller breaks, if someone suspends the CronJob during an incident and forgets to resume it, if the namespace gets recreated without the secret, silence. And silence looks exactly like “everything’s fine”. The fix is a dead man’s switch, a heartbeat the script pings on every successful run, with an external service that alerts when the pings stop. I haven’t added that yet. I should have before writing this post.
When it’s time to graduate to Prometheus
Move to a real metrics stack when you need to ask “what happened over time”, not just “is it broken right now”. For me that line is the second replica or the fifth tenant, whichever comes first.
The funny thing is most of the work is already done. Every CloudNativePG instance already runs a Prometheus exporter on port 9187, named metrics, with a default set of queries built in. Nothing scrapes it today, but it’s sitting there. Moving over is mostly a PodMonitor pointed at it:
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: app-pg
spec:
selector:
matchLabels:
cnpg.io/cluster: app-pg
podMetricsEndpoints:
- port: metrics
Plus, of course, actually running Prometheus, which is the expensive part.
| CronJob + shell script | Prometheus + Grafana | |
|---|---|---|
| Resource cost | 10m CPU, 32Mi RAM, for seconds every 15 min | always-on, a few hundred MiB minimum |
| Time to set up | an afternoon | a day or two, plus learning PromQL |
| Catches broken archiving/backups | yes | yes |
| History and trends | no | yes |
| Connection counts, query stats | no | yes, from the built-in exporter |
| Detection delay | up to 15 minutes | scrape interval, usually 30 to 60 seconds |
| Knows when it’s dead itself | no, needs a heartbeat | Alertmanager watchdog alert |
I don’t regret starting with the script. It took an afternoon, it’s caught real archiving stalls, and it forced me to figure out which failures actually matter before I had a dashboard full of graphs telling me about all the ones that don’t. But I’ve stopped thinking of it as the monitoring. It’s the smoke detector. The building still needs someone looking at it.
References
- CloudNativePG: Monitoring — the built-in exporter on port 9187, default metrics, and
PodMonitorsetup - Kubernetes: CronJob —
schedule,concurrencyPolicy, and job history limits - PostgreSQL: Continuous Archiving and Point-in-Time Recovery — what happens to WAL when archiving fails
