100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
PostgreSQL Mastery
35 minintermediate

Replication: Streaming, Logical, and Slot-Based

Replication keeps copies of your database on more than one server. You replicate for high availability (if the primary fails, a replica takes over), for read scaling (route read-only queries to replicas), and for moving or upgrading data with minimal downtime. A single server is a single point of failure and a single bottleneck; replication is how PostgreSQL escapes both.

PostgreSQL offers two fundamentally different replication mechanisms. Physical (streaming) replication ships the write-ahead log byte-for-byte to standby servers that replay it, producing exact, whole-cluster copies. Logical replication decodes the WAL into row-level changes and publishes them, letting you replicate selected tables, across versions, into a differently-shaped target.

Underpinning both is the write-ahead log and the concept of a replication slot, which guarantees the primary retains the WAL a replica still needs. Understanding the difference between physical and logical replication — and the role of slots — is the foundation for the high availability, pooling, and backup topics that follow.

Analogy🏏Cricket
🏏 Think of it like cricket: Just as a selection decision can depend on a derived benchmark — 'pick batters whose average exceeds the squad's average', which itself must first be computed — a subquery computes an inner result that the outer query then uses. The insight is that some questions are inherently two-stage: you must establish the benchmark before you can judge against it, and composing queries is how SQL expresses that dependency. Watch the selector actually do it: first he tallies every batter's runs and computes the squad average — that inner computation stands alone, needing nothing from the final decision — and only then does he walk the list judging each player against the number he just derived. That independence is what makes it an uncorrelated subquery: the database can compute the benchmark once, keep it, and reuse it for every row, exactly as the selector does not recompute the squad average per player. The composition also comes in shapes: a benchmark producing one number slots in where a value goes (a scalar subquery in WHERE), while a computed shortlist of qualifying players is itself a table the outer query can select from — a subquery in FROM. Two-stage question, two nested queries, dependency flowing inward-out.
Lesson 26 of 35
0% complete