Česky na konci článku.
High availability is one of the most misunderstood areas of PostgreSQL operations.
A PostgreSQL cluster can have:
- multiple servers
- streaming replication
- automatic failover
- monitoring
- backups
- a load balancer
…and still have a serious reliability problem.
Why?
Because replication alone does not guarantee recoverability.
A healthy PostgreSQL HA architecture must answer much more difficult questions:
- How much data can we lose?
- How quickly can we recover?
- What happens when the primary disappears?
- What happens when replication is delayed?
- What happens when WAL is missing?
- How does the application reconnect?
- Can we safely promote a replica?
- How do we know that the replica is actually ready?
- What happens when the network partitions the cluster?
This is where PostgreSQL administration moves from simple replication management into Database Reliability Engineering.
Streaming Replication Is Only One Part of HA
PostgreSQL streaming replication continuously sends WAL records from the primary to one or more standby servers.
A simplified architecture looks like this:
At first glance, this looks highly available.
But the important question is:
How far behind are the standbys?
A standby can be connected and appear healthy while still being significantly behind the primary.
That difference can become critical during a failure.
Replication Lag Is a Reliability Metric
Replication lag should not be treated simply as a performance metric.
It is also a measure of data-loss risk.
Suppose the primary has processed:
and the standby has replayed:
There is still approximately 500 MB of WAL that has not been replayed.
If the primary fails and the standby is promoted, the database may not contain the most recent transactions.
The important question becomes:
How much business data could be lost?
This is where RPO becomes real.
RPO Is Not Just a Number in a Document
Recovery Point Objective is often defined as:
“We have an RPO of 5 minutes.”
But how is that achieved?
If replication is asynchronous, the actual potential data loss depends on:
- network latency
- WAL generation rate
- replication throughput
- standby availability
- replay performance
- storage performance
- replication interruptions
A nominal RPO is meaningless if the infrastructure cannot consistently maintain it.
A mature PostgreSQL platform therefore monitors the actual replication state.
PostgreSQL Has More Than One Type of Replication Lag
One common mistake is to treat replication lag as a single number.
PostgreSQL provides several important positions:
sent_lsnwrite_lsnflush_lsnreplay_lsn
These represent different stages of WAL processing.
Conceptually:
A standby can therefore receive WAL but still not have replayed it.
That distinction matters.
For read workloads, a replica that has received WAL but has not replayed it may still return stale data.
For failover, replay position determines how much data is actually available.
The Primary Can Be Healthy While the Standby Is Not
This is another important operational lesson.
Imagine:
Everything looks good.
But:
The HA system is not actually in the state you think it is.
If the primary fails now, the standby may be missing eight minutes of transactions.
A good monitoring system therefore should not only ask:
Is replication connected?
It should ask:
Is the standby sufficiently current to satisfy the required RPO?
That is a much better question.
WAL Is the Backbone of PostgreSQL Recovery
Write-Ahead Logging is fundamental to PostgreSQL reliability.
Before database changes are considered durable, the corresponding WAL must be safely persisted.
WAL also enables:
- streaming replication
- point-in-time recovery
- crash recovery
- continuous archiving
- standby synchronization
This makes WAL one of the most important components of a PostgreSQL HA architecture.
If WAL is lost, delayed or incorrectly archived, recovery capabilities can disappear.
WAL Archiving and Streaming Replication Solve Different Problems
Streaming replication is excellent for high availability.
But it should not be considered a replacement for backups.
A standby replicates changes from the primary.
If an administrator accidentally executes:
the standby can faithfully replicate the mistake.
The disaster is now replicated too.
This is why a serious PostgreSQL architecture needs both:
Replication provides fast availability.
Backups and WAL archives provide recovery from logical or broader failures.
High Availability Does Not Protect Against Human Error
Consider the following sequence:
- Administrator runs an incorrect SQL command.
- Primary executes it.
- WAL is generated.
- Standby receives the WAL.
- Standby replays the WAL.
- The incorrect change now exists on both servers.
The HA system worked perfectly.
And the data was still damaged.
This is why:
High availability and disaster recovery are different capabilities.
HA minimizes service interruption.
DR protects against larger classes of failures.
You need both.
Automatic Failover Is Not Automatically Safe
Automatic failover sounds attractive.
The primary disappears.
The cluster promotes a standby.
The application reconnects.
Everything continues.
But distributed systems are rarely that simple.
Consider a network partition:
What happens if the primary is still running but cannot communicate with the rest of the cluster?
If both sides believe they should become primary, you can create split-brain.
This is why PostgreSQL HA systems commonly use a distributed consensus or coordination mechanism such as:
- etcd
- Consul
- ZooKeeper
alongside orchestration systems such as Patroni.
The goal is to ensure that only one node is considered the authoritative primary.
Patroni Does Not Replace PostgreSQL
Patroni is often described as an HA solution.
More precisely, Patroni provides orchestration around PostgreSQL.
It helps manage:
- leader election
- PostgreSQL configuration
- failover
- replica state
- cluster membership
- recovery behavior
A simplified architecture might look like:
The important point is that Patroni does not eliminate the need to understand PostgreSQL internals.
A DBA still needs to understand:
- WAL
- replication
- recovery
- timelines
- checkpoints
- synchronous/asynchronous behavior
- replication slots
- storage
- network failures
Automation cannot compensate for missing fundamentals.
Synchronous Replication Changes the Trade-Off
Asynchronous replication provides better write performance because the primary does not necessarily wait for the standby.
Synchronous replication provides stronger durability guarantees.
The trade-off looks roughly like this:
Neither approach is universally correct.
The decision should be based on business requirements.
For example:
A payment transaction may require stronger durability guarantees than an analytics workload.
The architecture should reflect that difference.
synchronous_commit Matters
PostgreSQL provides different durability behaviors through synchronous_commit.
Depending on the configuration, a transaction can be considered committed before the corresponding WAL has reached the desired durability point on a synchronous standby.
This means the DBA needs to understand exactly what the selected configuration guarantees.
Simply enabling synchronous replication does not automatically mean:
“No data can ever be lost.”
The actual durability semantics depend on the PostgreSQL configuration and the failure scenario.
Replication Slots Can Save You — or Fill Your Disk
Replication slots are extremely useful.
They prevent PostgreSQL from removing WAL that a consumer may still need.
But this creates another risk.
Suppose a standby stops consuming WAL.
The primary retains WAL because the replication slot tells it that the standby still needs it.
Eventually:
Disk usage grows.
If nobody is monitoring the slot:
The primary may eventually run out of disk space.
A reliability-oriented PostgreSQL platform therefore monitors:
- replication slot lag
- retained WAL
- filesystem utilization
- standby connectivity
- replay position
Replication slots are powerful, but they must be operated carefully.
Failover Should Be Tested
A common mistake is to test failover only when a real incident happens.
That is too late.
A proper HA environment should regularly test scenarios such as:
Primary failure
Network failure
Standby failure
Storage failure
Testing reveals problems that architecture diagrams cannot.
Application Failover Matters Too
A database can fail over perfectly and the application can still remain unavailable.
Why?
Because the application may continue trying to connect to the old primary.
This is why HA must be considered across the entire stack:
Database failover is only successful when the application can actually use the new primary.
Recovery Time Is More Than Database Startup
Suppose PostgreSQL starts successfully after a failure.
Is the service recovered?
Not necessarily.
You also need to verify:
- DNS / service discovery
- connection pools
- application sessions
- credentials
- background workers
- queues
- dependent services
- monitoring
- replication
- backups
The real recovery time is:
Time until the business service works again.
Not:
Time until PostgreSQL accepts a connection.
A Good PostgreSQL HA Architecture Measures Four Things
At minimum, I want to know:
1. Availability
Is the database serving traffic?
2. Replication health
Are replicas receiving and replaying WAL?
3. Recovery readiness
Can the system actually recover?
4. Business impact
Can the application continue operating?
These measurements are much more valuable than a simple:
PostgreSQL = UP
The DBA Should Think in Failure Scenarios
Instead of asking:
“Is my cluster healthy?”
ask:
“What happens if…?”
What happens if:
- the primary server disappears?
- the standby is 30 minutes behind?
- the network is partitioned?
- the WAL archive stops?
- the replication slot grows?
- storage reaches 95%?
- someone deletes critical data?
- both database nodes restart?
- the application connection pool contains stale connections?
- the entire availability zone disappears?
These questions lead to much stronger architectures.
From HA Configuration to Reliability Engineering
The evolution is straightforward:
The goal is not simply to have a replica.
The goal is to understand exactly what the system will do when something goes wrong.
Final Takeaway
PostgreSQL streaming replication is an excellent foundation for high availability.
But replication alone does not create a reliable database platform.
True reliability requires a combination of:
- replication
- WAL management
- backups
- point-in-time recovery
- monitoring
- failover orchestration
- application reconnection
- capacity management
- recovery testing
- documented procedures
- automation
The most important question is not:
“Do we have PostgreSQL replication?”
It is:
“If our primary database disappears right now, can we prove that the business will recover within its required RTO and RPO?”
That is the difference between having an HA configuration and engineering a reliable database platform.
About the Author
Tomas Solar
Principal Database Reliability Engineer
20+ years of experience with Oracle, PostgreSQL, SQL Server, MySQL and MongoDB.
Specialized in PostgreSQL HA/DR, database reliability, performance engineering, automation, migrations and database architecture.
Experience with Patroni, etcd, Ansible, Linux and enterprise database environments.
Replication gives you a copy. Reliability engineering gives you confidence that the copy will actually save you when you need it.
Vysoká dostupnost PostgreSQL: Replikace není totéž co spolehlivost
Vysoká dostupnost je jednou z nejčastěji špatně chápaných oblastí provozu PostgreSQL.
PostgreSQL cluster může mít:
- několik serverů
- streaming replikaci
- automatický failover
- monitoring
- zálohy
- load balancer
…a přesto může mít vážný problém se spolehlivostí.
Proč?
Protože samotná replikace nezaručuje možnost obnovy.
Dobře navržená PostgreSQL HA architektura musí odpovědět na mnohem složitější otázky:
- Kolik dat můžeme ztratit?
- Jak rychle dokážeme službu obnovit?
- Co se stane, když zmizí primary server?
- Co se stane při zpoždění replikace?
- Co se stane, když chybí WAL?
- Jak se aplikace znovu připojí?
- Můžeme bezpečně povýšit repliku na primary?
- Jak poznáme, že je replika skutečně připravena?
- Co se stane při výpadku sítě mezi jednotlivými uzly?
Právě tady se PostgreSQL administrace posouvá od jednoduchého řízení replikace k Database Reliability Engineering.
Streaming replikace je pouze jedna část HA
PostgreSQL streaming replication průběžně posílá WAL záznamy z primary serveru na jeden nebo více standby serverů.
Zjednodušená architektura:
Na první pohled to vypadá jako vysoce dostupné řešení.
Důležitá otázka ale zní:
Jak moc jsou standby servery pozadu?
Standby může být připojený a vypadat zdravě, přesto může být výrazně pozadu za primary.
A při jeho výpadku nebo failoveru to může být zásadní.
Replikační lag je metrika spolehlivosti
Replikační zpoždění bychom neměli chápat pouze jako metriku výkonu.
Je to také ukazatel rizika ztráty dat.
Představme si, že primary zpracoval:
a standby už replayoval:
Přibližně 500 MB WAL tedy ještě nebylo přehráno.
Pokud primary selže a standby bude povýšen na primary, databáze nemusí obsahovat nejnovější transakce.
Otázka tedy zní:
Kolik business dat můžeme skutečně ztratit?
A právě tady začíná být důležité RPO.
RPO není jen číslo v dokumentaci
Recovery Point Objective se často definuje například takto:
„Máme RPO 5 minut.“
Ale jak toho dosahujeme?
U asynchronní replikace závisí potenciální ztráta dat například na:
- síťové latenci
- rychlosti generování WAL
- rychlosti replikace
- dostupnosti standby
- rychlosti replay
- výkonu storage
- přerušení replikace
Papírově definované RPO je bezcenné, pokud infrastruktura nedokáže tuto hodnotu dlouhodobě udržet.
Vyspělá PostgreSQL platforma proto sleduje skutečný stav replikace.
PostgreSQL má více druhů replikačního zpoždění
Častou chybou je chápat replication lag jako jedno číslo.
PostgreSQL pracuje například s pozicemi:
sent_lsnwrite_lsnflush_lsnreplay_lsn
Ty představují různé fáze zpracování WAL.
Zjednodušeně:
Standby tedy může WAL přijmout, ale ještě ho nemusí přehrát.
Tento rozdíl je důležitý.
U read workloadu může replika, která WAL přijala, ale ještě ho nereplayovala, stále vracet zastaralá data.
Při failoveru zase rozhoduje replay pozice o tom, kolik dat je skutečně dostupných.
Primary může být zdravý, zatímco standby ne
Další důležitá provozní lekce:
Všechno vypadá dobře.
Ale:
HA systém tedy není ve stavu, který si myslíme.
Pokud primary právě teď selže, standby může postrádat osm minut transakcí.
Dobrá monitoringová platforma se proto nemá ptát pouze:
Funguje replikace?
Měla by se ptát:
Je standby dostatečně aktuální, aby splnil požadované RPO?
To je mnohem lepší otázka.
WAL je základ PostgreSQL recovery
Write-Ahead Logging je základním prvkem spolehlivosti PostgreSQL.
Předtím, než jsou změny databáze považovány za trvalé, musí být odpovídající WAL bezpečně uložen.
WAL umožňuje:
- streaming replikaci
- point-in-time recovery
- crash recovery
- continuous archiving
- synchronizaci standby serverů
WAL je proto jednou z nejdůležitějších součástí PostgreSQL HA architektury.
Pokud se WAL ztratí, zpozdí nebo není správně archivován, mohou zmizet důležité možnosti obnovy.
WAL archiving a streaming replication řeší různé problémy
Streaming replication je výborná pro vysokou dostupnost.
Neměli bychom ji ale považovat za náhradu záloh.
Standby replikuje změny z primary.
Pokud administrátor omylem spustí:
standby tuto chybu věrně zreplikuje.
Chyba se tedy dostane i na standby.
Proto potřebujeme obojí:
Replikace poskytuje rychlou dostupnost.
Zálohy a WAL archivy poskytují možnost obnovy po logických a širších typech havárií.
High Availability nechrání před lidskou chybou
Představme si:
- Administrátor spustí špatný SQL příkaz.
- Primary ho provede.
- Vygeneruje se WAL.
- Standby dostane WAL.
- Standby ho replayuje.
- Špatná změna nyní existuje na obou serverech.
HA systém fungoval dokonale.
A data byla přesto poškozena.
Proto:
High Availability a Disaster Recovery jsou dvě různé schopnosti.
HA minimalizuje přerušení služby.
DR chrání proti širší třídě problémů.
Potřebujeme obojí.
Automatický failover není automaticky bezpečný
Automatický failover zní velmi dobře.
Primary zmizí.
Cluster povýší standby.
Aplikace se připojí.
Systém pokračuje.
Distribuované systémy ale nejsou tak jednoduché.
Představme si network partition:
Co se stane, pokud primary stále běží, ale nemůže komunikovat se zbytkem clusteru?
Pokud obě strany uvěří, že mají být primary, může vzniknout split-brain.
Proto PostgreSQL HA řešení často využívají distribuovaný konsenzus nebo koordinační systém, například:
- etcd
- Consul
- ZooKeeper
v kombinaci s orchestration systémem, jako je Patroni.
Cílem je zajistit, že pouze jeden uzel je považován za autoritativní primary.
Patroni nenahrazuje PostgreSQL
Patroni je často označován jako HA řešení.
Přesněji řečeno poskytuje orchestrace nad PostgreSQL.
Pomáhá například s:
- leader election
- PostgreSQL konfigurací
- failoverem
- stavem replik
- členstvím v clusteru
- recovery chováním
Zjednodušená architektura:
Důležité ale je, že Patroni nenahrazuje znalost PostgreSQL internals.
DBA stále musí rozumět:
- WAL
- replikaci
- recovery
- timelines
- checkpointům
- synchronnímu/asynchronnímu chování
- replication slots
- storage
- síťovým problémům
Automatizace nemůže nahradit znalost základů.
Synchronní replikace mění kompromis
Asynchronní replikace poskytuje lepší write performance, protože primary nemusí vždy čekat na standby.
Synchronní replikace poskytuje silnější garanci durability.
Zjednodušeně:
Ani jedna možnost není univerzálně správná.
Rozhodnutí by mělo vycházet z business požadavků.
Například platební transakce může vyžadovat vyšší úroveň durability než analytický workload.
Architektura by měla tento rozdíl respektovat.
synchronous_commit je důležitý
PostgreSQL poskytuje prostřednictvím synchronous_commit různé možnosti chování z hlediska durability.
Podle konfigurace může být transakce považována za committed ještě před tím, než odpovídající WAL dosáhne požadovaného bodu durability na synchronním standby.
DBA proto musí přesně rozumět tomu, co konkrétní konfigurace garantuje.
Pouhé zapnutí synchronní replikace automaticky neznamená:
„Data už nikdy nemůžeme ztratit.“
Skutečná garance závisí na konfiguraci PostgreSQL a konkrétním scénáři selhání.
Replication slots mohou zachránit data — nebo zaplnit disk
Replication slots jsou velmi užitečné.
Zabraňují PostgreSQL odstranit WAL, který může odběratel stále potřebovat.
Současně ale vytvářejí nové riziko.
Představme si, že standby přestane WAL odebírat.
Primary ho kvůli replication slotu stále uchovává.
A postupně:
zaplní disk.
Pokud nikdo slot nemonitoruje:
primary může nakonec dojít na nedostatek místa.
Reliability-oriented PostgreSQL platforma proto sleduje:
- replication slot lag
- množství drženého WAL
- využití filesystemu
- připojení standby
- replay pozici
Replication slots jsou velmi silný nástroj, ale musí být správně provozovány.
Failover musí být testován
Častou chybou je testovat failover až při skutečném incidentu.
To je pozdě.
Správně navržené HA prostředí by mělo pravidelně testovat například:
Výpadek primary
Výpadek sítě
Výpadek standby
Výpadek storage
Testování odhalí problémy, které architektonický diagram nikdy neodhalí.
Failover aplikace je stejně důležitý
Databáze může failover provést dokonale a aplikace může být přesto nedostupná.
Proč?
Protože se může stále pokoušet připojovat ke starému primary.
Proto musí být HA navržena přes celý stack:
Databázový failover je úspěšný teprve tehdy, když aplikace skutečně dokáže používat nový primary.
Recovery time není pouze start PostgreSQL
Představme si, že PostgreSQL po výpadku úspěšně nastartuje.
Je služba obnovena?
Ne nutně.
Je potřeba ověřit také:
- DNS / service discovery
- connection pools
- aplikační session
- credentials
- background workers
- queues
- závislé služby
- monitoring
- replikaci
- zálohy
Skutečný recovery time je:
Čas do okamžiku, kdy znovu funguje business služba.
Není to:
Čas, za který PostgreSQL začne přijímat spojení.
Dobrá PostgreSQL HA architektura měří čtyři věci
Minimálně bych chtěl znát:
1. Dostupnost
Slouží databáze požadavkům?
2. Stav replikace
Přijímají a replayují repliky WAL?
3. Připravenost na recovery
Dokážeme skutečně provést obnovu?
4. Business impact
Může aplikace skutečně fungovat?
Tyto metriky jsou mnohem hodnotnější než jednoduché:
PostgreSQL = UP
DBA by měl přemýšlet v režimu failure scenarios
Místo otázky:
„Je cluster zdravý?“
se ptejme:
„Co se stane, když…?“
Co se stane, když:
- zmizí primary server?
- standby bude 30 minut pozadu?
- dojde k network partition?
- přestane fungovat WAL archive?
- začne růst replication slot?
- filesystem dosáhne 95 %?
- někdo smaže kritická data?
- oba databázové uzly restartují?
- connection pool obsahuje stará spojení?
- zmizí celý availability zone?
Tyto otázky vedou k výrazně robustnější architektuře.
Od HA konfigurace k Reliability Engineering
Vývoj může vypadat takto:
Cílem není pouze mít repliku.
Cílem je přesně rozumět tomu, co systém udělá, když se něco pokazí.
Závěr
PostgreSQL streaming replication je skvělý základ pro vysokou dostupnost.
Samotná replikace ale nevytváří spolehlivou databázovou platformu.
Skutečná spolehlivost vyžaduje kombinaci:
- replikace
- správy WAL
- záloh
- point-in-time recovery
- monitoringu
- orchestrace failoveru
- opětovného připojení aplikace
- capacity managementu
- testování recovery
- zdokumentovaných postupů
- automatizace
Nejdůležitější otázka tedy není:
„Máme PostgreSQL replikaci?“
Ale:
„Pokud náš primary databázový server právě teď zmizí, dokážeme prokázat, že se business obnoví v rámci požadovaného RTO a RPO?“
Právě to je rozdíl mezi HA konfigurací a spolehlivou databázovou platformou.
O autorovi
Tomas Solar
Principal Database Reliability Engineer
Více než 20 let zkušeností s Oracle, PostgreSQL, SQL Server, MySQL a MongoDB.
Specializace na PostgreSQL HA/DR, databázovou spolehlivost, performance engineering, automatizaci, migrace a databázovou architekturu.
Zkušenosti s Patroni, etcd, Ansible, Linuxem a enterprise databázovými prostředími.
Replikace vám dá kopii. Reliability engineering vám dá jistotu, že vás tato kopie skutečně zachrání, až ji budete potřebovat.
