34.9. Connecting Databases to Service Operations
A database's hardest problems usually arrive from outside its own process: an application deployed with credentials it should not hold, a health check that mistakes a read-only replica for a healthy primary, a backup that stopped completing three weeks ago, or a deployment rollback that expects the database to roll back with it. This closing section collects the boundary discipline the chapter has been applying piecewise - credential and schema management, health checks that respect roles, monitoring of the three quiet failure signals, and the separation of replication from recovery copies - into the operational habits that survive contact with a real service.
34.9.1. Application Credentials, Schema Changes, and Deployment Rollback Limits
The two halves of this chapter converged on one account model, and
it is the one to keep: the database administrator creates named
login roles; the application holds only its own credentials; and
the two never merge. PostgreSQL's app_owner and app_reader,
MariaDB's shop_app and repl, were each created with the minimum
privilege for one job, admitted from one network, and verified by
connecting as the application and failing to exceed the grant.
Rotation follows the same shape: ALTER ROLE ... PASSWORD (or
ALTER USER ... IDENTIFIED BY on MariaDB) changes the secret without
touching grants, and the application's deployment pipeline is where
the new secret lands - never a shell history, never a dump file in
the workspace left behind an exercise. The replication and rewind
accounts deserve the same discipline: replicator, repl, and
rewind_user exist for their protocols and nothing else, so a leaked
application password remains an application incident.
Schema changes are the point where deployments meet durability, and
the two servers differ in a way that changes deployment design.
PostgreSQL's DDL is transactional: a migration can run inside
BEGIN/COMMIT, and a failure at any statement rolls the whole
thing back - the failed deployment leaves no trace. MariaDB's DDL
is not: a multi-statement migration that fails halfway leaves
the completed statements in place, so MariaDB migrations need
explicit compensation or a restore path. Neither property rescues
the operations that are irreversible by nature on both systems -
DROP TABLE, DROP DATABASE, and TRUNCATE commit their damage
instantly, and the replica will helpfully replicate it. The backup,
not the transaction, is the rollback for those.
That asymmetry produces the deployment rule that keeps databases out of rollback emergencies: roll back code freely, roll forward schema only. A migration designed to be reversible in production is additive - add the column, backfill it, ship the code that writes it, retire the old path - so that reverting the application never requires reverting the database. A migration that renames or drops in the same release as the code that depends on it has bound the two together, and a bad application release then forces either a schema rollback the database cannot do or an outage waiting for the fixed code. Test the rollback of a deployment the way section 34.7 tested failovers: by performing it against a copy and reconciling the data afterward.
34.9.2. Database-Aware Health Checks and Client Reconnection
A health check that only proves "a TCP port answers" is worse than
none on a replicated database, because a replica answers too - the
check that matters is role-aware: does this server accept
writes, and can it prove it? The chapter built the same check twice.
On the PostgreSQL side, Patroni's REST API answers the question
directly - /primary returns 200 on the lease-holder and 503
elsewhere - and HAProxy consumed it as an HTTP check on port 8008,
TLS-verified, with on-marked-down shutdown-sessions to push
clients off a deposed leader. pg_isready (in
postgresql-client-17) is the lighter tool for scripts and
orchestrators: it reports whether a server accepts connections
without authenticating, which makes it a liveness probe but not a
role probe - pair it with the role question whenever the target is
a cluster. On the MariaDB side, the same information lives in
server variables: @@read_only distinguishes a writable server from
a replica, and SHOW SLAVE STATUS's Slave_IO_Running and
Slave_SQL_Running distinguish a healthy replica from a broken one
- the checks an orchestrator reads before routing or alarming.
Client reconnection is the other half of the same contract, and the
recorder demonstrated its shape: every wait bounded
(connect_timeout=3, statement_timeout=5000), every failure
recorded, every retry a new transaction with a new identity. Two
rules keep reconnection safe. First, bound every stage - a client
that hangs for minutes on a dead address has not survived a
failover, whatever the proxy did; the bounds should match the
cluster's real recovery time (the lab's measured half-minute, with
the lease arithmetic of section 34.6.7 explaining where that number
comes from). Second, treat retries as possible duplicates: the
ambiguous-commit window of section 34.7.3 means a retried write may
have committed on the deposed server and again on its successor, so
application-level idempotency - the unique attempt name in the
recorder, an idempotency key in a real service - is what turns
"at-least-once" reconnection into exactly-once effects. A client
that reconnects fast but retries blindly has traded a hang for a
duplicate.
34.9.3. Monitoring Backup Freshness, Replication Lag, and Disk Pressure
Three signals cover the quiet failures of a database service - the ones that surface only when you need the thing that silently stopped. Each has a specific place to read it:
| Signal | Where to read it | Alert when |
|---|---|---|
| Replication lag (PostgreSQL) | pg_stat_replication: sent_lsn vs replay_lsn, or replay_lag |
Lag grows or persists on an idle cluster; a member absent from the view |
| Replication lag (MariaDB) | SHOW SLAVE STATUS: Seconds_Behind_Master, both Running threads |
Nonzero lag at rest; either thread stopped |
| Backup/archive freshness (PostgreSQL) | pg_stat_archiver: last_archived_wal, last_archived_time, failed_count |
failed_count climbing, or last_archived_time old while traffic flows |
| Backup freshness (MariaDB) | Dump anchors vs SHOW MASTER STATUS |
Current position far past the last dump's MASTER_LOG_POS |
| Consensus health | etcdctl endpoint health; patronictl list |
Any endpoint unhealthy; any member not streaming |
| Disk pressure | df on the data, log, and archive filesystems |
Sustained growth of pg_wal, binlog, or archive directories |
The replication view under traffic looks like this - on the current Patroni leader, whenever the walk reaches it:
$ sudo -u postgres psql -c "SELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;"
client_addr | state | sync_state | replay_lag
----------------+-----------+------------+-----------------
192.168.237.11 | streaming | async | 00:00:02.294558
192.168.237.13 | streaming | async | 00:00:02.299567
(2 rows)
Two replicas streaming, asynchronous, each reporting a replay_lag
of about 2.3 seconds - a measurement from the one-vCPU practice
guests at the moment of the capture, and worth reading correctly:
replay_lag is the delay between a transaction's WAL reaching the
standby and its becoming visible there, so on a quiet cluster it
describes the last replayed transaction, and the number to watch
is its trend under load, not its idle value. On the disk side, the
archive filesystem from section 34.4.2 - still mounted on db1, the
node that carries the archive disk - is the one whose growth needs a
policy. On db1, as john:
$ df -h /srv/pgarchive
Filesystem Size Used Avail Use% Mounted on
/dev/vdb 2.0G 47M 1.8G 3% /srv/pgarchive
The 2 GB lab disk at 3% is comfortable because the lab's WAL volume
is a demonstration; a production archive is sized from the segment
rate (16 MB per switch, forced at least every archive_timeout)
times retention, and the alert that matters is not "percent used"
but growth that retention should have stopped - the section
34.4.3 signature of a broken archive command or a stuck slot.
MariaDB's mirror of the same three signals: Seconds_Behind_Master
from section 34.8.5, the dump anchors from section 34.8.4 as backup
freshness, and the binlog directory's size against the
binlog_expire_logs_seconds retention that should bound it.
34.9.4. Separating Database Replication from Independent Recovery Copies
The chapter kept two kinds of copying deliberately apart, and the closing argument is why. Replication - streaming WAL, binary-log shipping, the whole Patroni machinery - is an availability technology: it keeps a current copy somewhere else, measured in seconds of lag. Backups and archives are recovery technologies: they keep history somewhere else, measured in restore time. They fail differently and they answer different disasters, and the failure analysis is short:
- A replicated topology propagates damage at replication speed. The
DROP TABLEof section 34.8.4 would have reached client1 in under a second; no replica anywhere is a defense against the statement that destroys the data everywhere it is copied. - An archive does not help availability at all - restoring is minutes to hours, and the application is down the whole time.
- The worst outcomes come from the two being confused: a cluster
whose only copy is its replica (one
DROP, one disk, one encryption event from zero), or an archive stored on the primary (one machine from zero).
The separation the chapter practiced is three distinct artifacts with three distinct failure domains, each verified by restore: the replica for availability (sections 34.5, 34.6, 34.8.5), the base backup plus WAL or binlog archive for recovery to any point in time (34.4, 34.8.4), and - once a consensus store enters the picture - the DCS snapshot for the control plane's identity (34.7.6). Chapter 15 called the same separation the copy ladder and added the property that completes it: the recovery copies must be access-isolated, deletable by neither the database server nor the credentials an application or attacker holds on it. A database cluster is the most automate-able component in this book and the least forgiving of automation without verification - and every procedure in the chapter ended the same way on purpose: not when the status was green, but when an independent client reconciled the data and found it exactly as promised.