The idea in one minute#
Databases cause a large share of serious incidents, because they are stateful, shared, and hard to scale or replace quickly. Four areas cover most of what an SRE must get right:
- Replication and failover: synchronous or asynchronous, how much data a failover can lose, and how to fail over without split brain.
- Replication lag and read routing: reads from a replica can be stale; route reads that need fresh data to the primary.
- Connections: databases handle hundreds, not tens of thousands, of connections well; pool them, cap them, and size them with Little’s law.
- Schema changes without downtime: never lock a big table; change schemas in backward- compatible steps — expand, migrate, contract — so code and schema can be rolled back independently.
An analogy#
A library with one master catalogue and several copies in branch libraries. Copies are updated by courier (replication) and may be a little out of date (lag). Only so many librarians can work the master desk at once (connections). Reorganising the shelves must happen while the library is open, one shelf at a time (online migrations).
A picture#
flowchart LR
APP[":go: <b>App</b>"] --> POOL[":i-layers: <b>Pooler</b><br/><small>PgBouncer / RDS Proxy</small>"]
POOL -->|"writes + fresh reads"| P[(":postgresql: <b>Primary</b>")]
POOL -->|"stale-OK reads"| R1[(":postgresql: Replica<br/><small>lag 40 ms</small>")]
POOL -->|"stale-OK reads"| R2[(":postgresql: Replica<br/><small>lag 3 s ⚠</small>")]
P -->|"sync"| S[(":postgresql: Sync standby<br/><small>RPO 0</small>")]
P -->|"async"| R1 & R2
HA[":etcd: <b>Patroni + etcd</b><br/><small>leader election, fencing</small>"] -.-> P & S
class APP compute
class POOL queue
class P,S,R1 memory
class R2 warn
class HA ioHow it really works#
Replication modes#
| Mode | Write is acknowledged when | Failover data loss | Write latency |
|---|---|---|---|
| Asynchronous | Written on the primary | Everything not yet replicated (the lag) | Lowest |
| Semi-synchronous / quorum | At least one (or k) replicas have received it | None, if a synced replica is promoted | + one round trip |
| Synchronous | All listed standbys have it | None | Highest; a slow standby slows every write |
A common production design: one synchronous standby in another zone (RPO 0 within the region), plus asynchronous replicas for reads and for another region.
Failover is managed by an HA manager — Patroni (PostgreSQL, with etcd/Consul/ZooKeeper), Orchestrator (MySQL), or the cloud provider for managed databases (RDS Multi-AZ, Cloud SQL HA, Azure Flexible Server). It must elect a new primary only with quorum, fence the old one, and repoint clients (DNS, virtual IP, proxy). Typical managed failovers take 30–120 seconds; applications must reconnect and retry idempotent work (6.b).
Replication lag#
An asynchronous replica is behind by the replication lag. Reads from it can miss the user’s own recent write — “I saved my profile and it reverted”.
- Monitor lag in seconds and bytes; alert when it exceeds what readers tolerate; remove a lagging replica from read rotation automatically.
- Read-your-writes: after a user writes, route their reads to the primary for a few seconds, or wait until a replica has replayed past the write’s position (PostgreSQL LSN, MySQL GTID).
- Big transactions, long-running queries on replicas, and vacuum or DDL cause lag spikes.
Connections and pools#
Each PostgreSQL connection is a process using memory; past a few hundred active connections, throughput falls. With 200 app pods × 20 connections each = 4,000 connections, the database is in trouble before any query runs.
- Size pools with Little’s law (7.e):
connections ≈ queries/s × query time, plus margin. - Put a pooler (PgBouncer in transaction mode, RDS Proxy, Cloud SQL Auth Proxy with pooling) between many app instances and the database.
- Set statement timeouts and idle-in-transaction timeouts in the database; a forgotten open transaction holds locks and blocks vacuum.
- Cap total connections across the fleet (autoscaling the app tier must not autoscale database connections past the limit — 7.d).
Zero-downtime schema changes: expand, migrate, contract#
Rename users.name to users.full_name without downtime:
| Step | Schema | Code | Rollback safe? |
|---|---|---|---|
| 1. Expand | Add full_name (nullable, no default rewrite) | Old code unaffected | Yes |
| 2. Dual write | — | New code writes both columns, reads name | Yes |
| 3. Backfill | Copy name → full_name in small batches | — | Yes |
| 4. Switch reads | — | Read full_name, still write both | Yes |
| 5. Stop old writes | — | Write only full_name | Yes, to step 4 |
| 6. Contract | Drop name (after a waiting period) | — | No — so wait until sure |
Rules for the DDL itself:
- Lock-aware: set
lock_timeoutso a migration waiting for a lock fails quickly instead of queueing every query behind it. CREATE INDEX CONCURRENTLY(PostgreSQL); online schema-change tools for MySQL (gh-ost, pt-online-schema-change).- Avoid rewrites of large tables (changing column types, adding volatile defaults).
- Backfill in batches with pauses, watching replication lag.
- Migrations run as a separate, reviewed step — never automatically on application start across 200 pods at once.
Other classic database incidents#
| Incident | Prevention |
|---|---|
| Disk full (WAL piling up because a replica or slot is stuck) | Alert on disk growth (predict_linear) and on replication slot lag |
| Transaction ID wraparound (PostgreSQL) | Monitor age(datfrozenxid); keep autovacuum healthy |
| A runaway query consumes the CPU | statement_timeout; query tagging; kill-query runbook |
| Hot row / lock contention under load | Load-test realistic contention; queue or shard hot keys |
| Lost writes during failover (async) | Sync standby for critical data; idempotent retries |
A worked example#
A team’s PostgreSQL primary fails over (managed Multi-AZ) at 14:02. Observations:
- 58 seconds of write errors while DNS moved to the standby; the app retried idempotent writes and most users saw only a slow request.
- Asynchronous read replicas briefly fell 40 seconds behind while they reconnected to the new primary. The “order status” page, which reads from replicas, showed new orders as missing; the support team got 30 tickets.
Fixes: replica lag above 5 s removes that replica from read rotation; order-status reads for orders created in the last 2 minutes go to the primary; a game day (10.c) repeats the failover monthly.
The program estimates the data at risk in an asynchronous failover and shows lag-aware read routing.
Code#
// dbreliability.go — data at risk in async failover, lag-aware read routing, and pool sizing.
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
type replica struct {
name string
lag time.Duration
}
// route picks where a read goes: the primary if it must see a recent write, else the least-lagged
// replica under the staleness limit, else the primary.
func route(replicas []replica, wroteAgo, maxStale time.Duration) string {
sort.Slice(replicas, func(i, j int) bool { return replicas[i].lag < replicas[j].lag })
for _, r := range replicas {
if r.lag < maxStale && r.lag < wroteAgo {
return r.name
}
}
return "primary"
}
func main() {
// 1. Data at risk during an asynchronous failover.
r := rand.New(rand.NewSource(11))
const writesPerSec = 1500
var lags []float64
for i := 0; i < 10_000; i++ {
// Lag is usually tens of ms, occasionally seconds (big transactions, vacuum).
l := 0.02 + r.ExpFloat64()*0.03
if r.Intn(200) == 0 {
l += r.Float64() * 5
}
lags = append(lags, l)
}
sort.Float64s(lags)
p := func(q float64) float64 { return lags[int(q*float64(len(lags)-1))] }
fmt.Println("async replica lag over a day, and writes lost if the primary dies at that moment:")
for _, q := range []float64{0.5, 0.99, 0.999, 1} {
fmt.Printf(" p%-5v lag %5.2f s → ~%5.0f writes lost\n", q*100, p(q), p(q)*writesPerSec)
}
fmt.Println(" with a synchronous standby promoted instead: 0 writes lost")
// 2. Lag-aware read routing.
reps := []replica{{"replica-a", 40 * time.Millisecond}, {"replica-b", 3 * time.Second}}
fmt.Println("\nread routing (staleness limit 1 s):")
for _, ago := range []time.Duration{10 * time.Millisecond, 200 * time.Millisecond, time.Minute} {
fmt.Printf(" user wrote %-6v ago → %s\n", ago, route(reps, ago, time.Second))
}
reps[0].lag = 2 * time.Second
fmt.Printf(" both replicas lagging, user wrote 1m ago → %s\n", route(reps, time.Minute, time.Second))
// 3. Pool sizing with Little's law.
const qps, queryMs, pods = 3000.0, 4.0, 60
busy := qps * queryMs / 1000
fmt.Printf("\npool sizing: %.0f q/s × %.0f ms = %.0f connections busy on average\n", qps, queryMs, busy)
fmt.Printf(" ×3 for peaks and variance = %.0f total; across %d pods = %.1f per pod\n", busy*3, pods, busy*3/pods)
fmt.Printf(" a default of 20 per pod would open %d connections — use a pooler and cap it\n", 20*pods)
}Remember this#
- Async replication loses the lag on failover; a synchronous standby gives RPO 0 at a latency cost.
- Failover needs quorum, fencing and client repointing; apps must reconnect and retry idempotently.
- Monitor replica lag; route read-your-writes to the primary; drop lagging replicas from rotation.
- Size pools with Little’s law; put a pooler in front; set statement and idle-in-transaction timeouts.
- Schema changes: expand, migrate, contract; lock timeouts; concurrent indexes; batched backfills.
Try it#
- Run
dbreliability.go. What happens to data at risk if write volume triples? - Write the expand/migrate/contract plan for splitting
addressintostreetandcity. - Check
max_connectionsand the actual connection count on a database you know. How many pods would it take to exhaust it at the default pool size?
Check yourself#
- Why can an asynchronous failover lose committed writes?
- What is read-your-writes consistency, and two ways to provide it with replicas?
- Why should a migration set
lock_timeout? - Why is the “contract” step the only one that is not rollback-safe?