Home›Learn›Many servers 7: a thousand databases
Many servers · Chapter 7

How a database team runs 1,000 databases

What changes when you stop touching servers one at a time?

At a thousand databases you do not run servers, you run a system that runs them. This page maps the layers of that system and points to the page that explains each one.

Why this page exists

Why one database team cannot run 1,000 databases by hand

Running one database well is a craft. Running a thousand is a different job. You stop touching servers one at a time, and you start designing a system that touches them for you, with brakes. This page is the map of that system, and each part links to a page that goes deep.

The arithmetic is the problem

A routine 10 minute task on 1,000 servers is 10,000 minutes, about 167 hours (derived). Nobody does that by hand every quarter, so it either gets automated or it does not get done.

Failure becomes routine

With hundreds of clusters, some server is failing somewhere most days. Failover cannot depend on a person being awake.

Changes need a blast radius

A bad change hits one cluster, or the whole fleet. You choose which by how you roll it out: in waves, with a stop button.

What it is not

Not "automate everything". Automation without guardrails moves a mistake to every server at once.

What published teams report

None of these numbers are ours, and none are a promise for your fleet. Read them as proof that the approach works at that size.

How it was done before

The ssh loop and the spreadsheet

The early version of fleet management is a spreadsheet of hostnames and a shell loop. It works for ten servers.

  1. The spreadsheet says which hosts are in which cluster. It is right on the day somebody last edited it.
  2. You write for h in $(cat hosts.txt); do ssh $h ...; done to change a setting.
  3. Host 214 times out. The loop either stops, and you do not know which 213 changed, or it carries on, and you find out in the morning.
  4. Some hosts were rebuilt last month with different defaults, so the same command does different things.

The fix is not a better loop. It is four ideas: a source of truth for what exists, config that is declared and not typed, changes that go in waves with a stop rule, and a way to know the state afterwards.

Step through it:

Explained clearly

The layers of a fleet

Think of nine layers. Each answers one question, costs something, and decides what happens to the app's request.

LayerThe problem it solvesWhat it costsWhat the app sees
1. Inventory and service discoveryWhat databases exist, who owns them, what role and version each has, and where the writer is.Someone must keep it true. Make it generated, not hand-edited: from Terraform state, cloud tags, or the orchestrator itself.Nothing directly. A stale inventory causes wrong changes.
2. Config management (Ansible, Terraform)Servers built and configured the same way, from files in version control.Review discipline and a way to test changes.Fewer surprises: a replica behaves like the primary.
3. Proxies and poolers (ProxySQL, HAProxy, PgBouncer)A stable address for the writer, connection reuse, and a place to drain traffic.One more hop, and one more thing to run and keep in sync.One name for writes. Failover moves the target, not the app config.
4. Orchestrators and operatorsSomeone to watch replication or pods and promote a new primary.You must run them, and understand when they act. See below.A few seconds of errors, then writes work again.
5. Failover with guardrailsAutomatic recovery without automatic mistakes.Rules to maintain, and some failures that stay manual on purpose.Fewer long outages, a small risk of a wrong decision.
6. Backups and restore testsRecovery from the failures failover cannot fix: bad deletes, corruption, a lost region.Storage, and the discipline to restore on a schedule.Nothing, until the day it matters.
7. Upgrades in wavesMoving a thousand servers to a new version without one big bang.Mixed-version fleets for weeks, and a rollback plan.No outage if replicas go first and the switch is graceful.
8. ObservabilityKnowing the state of every server, cluster and tool.Metrics storage and alert tuning.Problems found before users report them.
9. Runbooks and agentsMaking the on-call response the same for everyone, at any hour.Writing and testing them.Shorter outages and fewer mistakes under pressure.

Which page covers which part

If you runOrchestrator or operatorRead
MySQL, source and replicasOrchestratorOrchestrator for MySQL
MySQL, Group ReplicationBuilt in, with MySQL RouterInnoDB Cluster
MySQL on KubernetesPercona operatorsMySQL on Kubernetes
PostgreSQL on VMsPatroni with etcd and HAProxyPatroni
PostgreSQL on KubernetesCloudNativePGCloudNativePG
MongoDBReplica set election, Percona operator on KubernetesReplica sets, MongoDB on Kubernetes

Step through it:

Step by step

Build it in this order

You do not need all nine layers on day one. This order gives you the most safety per hour of work.

  1. An inventory, generated. One record per instance: cluster, role, engine, version, tier, zone, owner. Keep tier (how much it matters) because upgrades and change windows use it.
# one record (YAML, stored in version control or generated from Terraform state)
- cluster: orders
  engine: mysql
  version: "8.4"
  tier: 1                  # 0 = most critical, 5 = least
  zone: us-west-2a
  role: primary            # primary | replica
  owner: team-payments
  1. Config as code, applied in waves. Terraform builds hosts. Ansible configures them. The key Ansible controls are serial and max_fail_percentage: change one host, then 10 percent, then the rest, and stop if too many fail.
# site.yml
- hosts: mysql_replicas
  serial: [1, "10%", "50%"]      # canary, then a tenth, then half
  max_fail_percentage: 10        # abort the play if more than 10 percent of a batch fails
  tasks:
    - name: apply my.cnf
      ansible.builtin.template: {src: my.cnf.j2, dest: /etc/mysql/conf.d/fleet.cnf}
      notify: restart mysql
terraform plan -out=tfplan      # always read the plan
terraform apply tfplan             # apply exactly what you read

Keep one Terraform state per cluster or per tier, not one for the fleet, so a bad apply cannot touch everything.

  1. A proxy with one stable writer name. For MySQL, ProxySQL hostgroups: a writer group and a reader group. ProxySQL has memory, runtime and disk layers, so a change is staged, loaded to runtime and saved:
INSERT INTO mysql_servers (hostgroup_id, hostname, port) VALUES (10, 'db1.example.com', 3306);
INSERT INTO mysql_servers (hostgroup_id, hostname, port) VALUES (20, 'db2.example.com', 3306);
LOAD MYSQL SERVERS TO RUNTIME;
SAVE MYSQL SERVERS TO DISK;

For PostgreSQL on VMs, HAProxy checks Patroni's REST API (/primary), as on the Patroni page. For connection reuse, PgBouncer in transaction mode assigns a server connection only for the length of a transaction, which breaks features that depend on session state, so check your app first (see connection pooling).

[databases]
orders = host=orders-rw port=5432 dbname=orders

[pgbouncer]
listen_port = 6432
pool_mode = transaction
default_pool_size = 20
max_client_conn = 1000
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
  1. An orchestrator or operator per engine, with automatic recovery off at first. Detect and alert for a month. Then turn recovery on for one low-tier cluster, then more.
  2. Backups that are restored on a schedule. A restore into a scratch cluster, with a row-count and checksum check, run by a job. See backup and restore.
  3. Upgrades in waves (below), with a runbook per wave.
  4. One monitoring view and a runbook per alert. Link each alert to a page in Something is slow or broken or your own.
When it breaks

Automated failover with guardrails, and upgrades in waves

Automatic failover is a decision made by software while you sleep. Three kinds of guardrail keep it from making things worse: evidence (more than one observer agrees), limits (not again within an hour, not across regions) and escape hatches (a pause switch and a manual path). Every tool in this section has them.

GuardrailWhere it shows up
Several observers must agreeOrchestrator asks the replicas, not just the source. Patroni needs the leader key in etcd. Group Replication needs a majority. CloudNativePG checks a lease and, with quorum failover, that the replica cannot miss a synchronous commit.
No flappingOrchestrator's RecoveryPeriodBlockSeconds: one automatic recovery per cluster per period, unless a human acknowledges it.
Opt in per clusterOrchestrator recovers only clusters in RecoverMasterClusterFilters.
Stay in the regionOrchestrator PreventCrossDataCenterMasterFailover and PreventCrossRegionMasterFailover.
A pre-failover vetoA non-zero exit from an Orchestrator pre-failover hook aborts the recovery.
A global pauseOrchestrator disable-global-recoveries. Percona operators: spec.pause.
Fence the old primaryMake it read-only at boot, or fence it. GitHub notes a gap for apps inside an isolated data center and says it is working on a STONITH approach.

Step through it:

Upgrades in waves

Both GitHub and Uber describe the same shape: replicas first, a small canary, then tiers or batches, a soak period, and a point of no return you cross on purpose. The primary is moved by a graceful failover to an upgraded replica, not upgraded in place.

Step through it:

Day to day

The checks and commands a fleet team runs

These are patterns, with the exact commands on the engine pages.

TaskHowWhere
See every cluster and its topologyorchestrator-client -c clusters and -c topology -i HOST:PORT (MySQL). kubectl cnpg status CLUSTER (CNPG). kubectl get pxc,ps,psmdb -A (Percona operators).Orchestrator, CNPG
Pause automationorchestrator-client -c disable-global-recoveries. Percona operators: set spec.pause.Orchestrator, MySQL on Kubernetes
Planned switchoverorchestrator-client -c graceful-master-takeover-auto -alias CLUSTER, kubectl cnpg promote CLUSTER INSTANCE, patronictl switchover.Engine pages
Roll a config change in wavesAnsible serial and max_fail_percentage, one batch per tier.This page
Prove a backupA scheduled restore into a scratch cluster, then a checksum or row-count check.Backup and restore
Plan a major upgradeReplicas first, canary, tiers, soak, graceful switchover.Major upgrades
What goes wrong

Failures to plan for

SymptomLikely causeFirst checkFix
A change hit hosts it should not haveStale or hand-edited inventory.Compare inventory with what the cloud or Terraform says exists.Generate the inventory. Run changes with --check or a plan first.
A bad config reached the whole fleetNo waves, no stop rule.Which hosts changed, and when.Use serial and a failure threshold. Roll back with the same pipeline.
Automation failed over twice, then stoppedThe anti-flapping block did its job.Orchestrator audit, why the first failover happened.Find the root cause before you acknowledge and unblock.
The app still writes to the old primaryProxy or discovery not updated.Where the writer name points.Make the proxy update part of the recovery, and alert when it fails.
Backups exist, restore failsNever tested, or the key or bucket changed.The last restore test result.Schedule restore tests. Page on a failed test, not just a failed backup.
Orchestrator or operator is downIt is a single service.Health endpoints.Run it with raft or several replicas. Databases keep running without it, but nobody heals them.
Upgrade wave stuckA client or query that works on the old version only.Error logs for the new version, query plan changes.Fix and re-run the wave. Uber and GitHub both report client library and query issues.
Alert noise at scalePer-host alerts instead of per-cluster.Alert volume by rule.Alert on cluster health. Link each alert to one runbook.
Monitoring

What to watch across a fleet

SignalWhereAlert when
Clusters with no healthy primaryOrchestrator, operators, PatroniAny, at once.
Failovers and recoveries per day, per clusterOrchestrator /metrics, Kubernetes eventsMore than one on a cluster in a day.
Replication lag per clusterEngine metricsLag above the RPO for that tier.
Last good backup and last good restore testBackup tool and test jobOlder than the window.
Version and config driftInventory against realityAny host off its declared version.
Wave progress and failure rateThe upgrade pipelineFailure rate over the stop rule.
The control plane itselfOrchestrator health, operator deployments, proxy healthAny down.

Each alert needs an owner and a runbook. See on-call and symptoms.

Hands off

Let the agent do it

The agent can run the tool commands from the pages above. Every change is shown to you first and runs only after you type an approval. Reads run straight away. The commands are listed on each tool page:

More on the agent is on the agent page. A runbook is the same thing for a human: the exact commands, in order, with the check after each one.

Where this came from

Sources

← Chapter 6: Across servicesYou finished the Many servers trackBack to chapter 1Next, see these ideas inside real systems in the Design menu.
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect