Replication slots and runaway WAL retention

PostgreSQL replication slots stop WAL from being removed until a consumer confirms it, which can fill the primary's disk. This page covers how to cap retention, monitor lag and drop slots safely.

On this page

Why PostgreSQL replication slots can fill the primary's disk

A replication slot keeps WAL on the primary until its consumer confirms it has received that WAL, so a standby or change data capture (CDC) consumer that stops reading can make the primary's disk fill. If your primary is running out of space and pg_wal keeps growing, check the slots first, because the cause is often a slot whose consumer has been down, paused or abandoned for days. This is the failure mode that makes slot monitoring and retention limits necessary, not an edge case.

Teams need slot monitoring from the day a slot is created, and they need a retention ceiling once any consumer can fall behind for longer than the disk can absorb. That applies to physical slots for streaming standbys, to logical slots used by CDC pipelines, and to slots created by tools or test environments that nobody remembers to clean up. The risk grows with write volume, so a slot that is harmless on a quiet system can exhaust the disk on a busy one. Plan who gets alerted when lag crosses a threshold, and who has the authority to drop a slot that no longer has a live consumer.

The supplied research for this topic does not cover replication slot internals, so confirm the exact behavior, the settings that control retention and the views that report slot state against the PostgreSQL documentation for the major version you run before you set limits. Start with the high availability documentation for the replication model, then verify the parameter names and defaults for your version in your own test environment.

How a slot pins WAL on the primary

The diagram starts with the primary writing WAL segments to disk. A replication slot records the position a consumer has confirmed, and the primary keeps every WAL segment from that position forward. When a standby or CDC pipeline stops confirming, the slot's position stays put while new WAL keeps arriving, so retained segments grow on the primary's disk. The optional max_slot_wal_keep_size cap, or dropping the slot, ends that growth. Check the slot's confirmed position against the current WAL position on every consumer you run. This diagram is illustrative and not drawn to scale.

Illustrative view of a stopped consumer holding WAL on the primary.

Configuration options for limiting slot WAL retention

This table compares the settings and views that govern how much WAL a replication slot can hold back. Read each row as a control you set, a signal you monitor, or a fallback you rely on, and confirm defaults and availability for your PostgreSQL version in the official configuration reference.

Setting or viewWhat it controlsWhen it fitsTrade-off
max_slot_wal_keep_sizeUpper limit on WAL kept for replication slots, beyond which the primary may invalidate a lagging slotAbandoned or slow consumers can threaten disk space and you accept losing the slotA lagging slot is invalidated, so its consumer must resync from a fresh snapshot
wal_status in pg_replication_slotsShows whether a slot's required WAL is reserved, extended, unreserved or lostRoutine monitoring and alerting on slot health before a limit is reachedOnly shows state at query time, so alerts must run often enough to act in time
safe_wal_size in pg_replication_slotsShows how many more bytes of WAL can be written before the slot is at risk of invalidationEstimating headroom and setting alert thresholds for a capped slotNull when no limit is set, so it gives no warning on uncapped slots
max_wal_sizeSoft target for WAL size between checkpoints, not a retention limit for slotsSizing checkpoint frequency and disk for normal write loadDoes not stop a slot from holding WAL, so it cannot be used as a substitute for slot limits
wal_keep_sizeMinimum amount of WAL the primary keeps for standbys regardless of slot stateGiving streaming standbys a buffer for short network interruptions without a slotKeeps extra disk use on every primary even when no lagging consumer exists
Archive-based recoveryLets a consumer or standby catch up from archived WAL after a slot is invalidatedRecovery path for consumers that lost their slot and need the missing changesRequires a working archive and restore path, and adds delay before the consumer is current

How slot lag turns into a full disk

A replication slot is a promise from the primary that it will keep every WAL segment the consumer has not yet confirmed. The slot stores a position, and the server will not recycle WAL at or after that position. A physical standby using a slot and a logical consumer such as a CDC pipeline both work this way. As long as the consumer keeps confirming progress, retained WAL stays small. When the consumer is slow, stopped, disconnected or abandoned, the position stops moving while the primary keeps writing. The retained volume then grows roughly in step with write volume, and nothing in normal query traffic signals the problem. Measure this in your own environment: compare each slot's confirmed position with the current WAL position and track the difference over time, because the rate of growth depends on your workload, not on a general rule.

The failure is usually sudden for the operator. Retained WAL accumulates quietly on the same volume as the data directory until that volume fills. When it does, the primary cannot write new WAL, and writes stop across the database, not only for the workload that owned the slow consumer. Recovery then depends on freeing space quickly, which is hard if the cause is a consumer you no longer remember owning. Plan for this by alerting on free space on the WAL volume and on slot lag separately, so either signal gives early warning. The setting max_slot_wal_keep_size is the control that caps how much WAL a slot may force the server to keep, and it is covered in the next section. Confirm its behavior for your PostgreSQL version in the PostgreSQL continuous archiving documentation before relying on it.

The same slot can also hold back cleanup indirectly. A logical slot that has not advanced can keep old row versions that the decoding process may still need, and an inactive slot can hold back the cutoff that vacuum uses to decide which dead rows are removable. The result is table and index bloat that appears to have no connection to the replication setup. When someone investigates bloat, the slot list should be part of the review. Ask who owns each slot, what consumes it, and whether that consumer still exists. Those answers decide whether the slot should be fixed, advanced or dropped, and they belong in your runbook before an incident forces the decision.

Choosing a retention policy by consumer type

Physical slots serve streaming replication to hot standbys. The database team usually owns both the primary and the standby, so the owner can see the standby's state and act on it directly. If the slot is dropped or its WAL is removed by a retention limit, the standby can no longer catch up from the primary. In most setups the standby then needs a fresh base backup, which means a rebuild and a period of reduced redundancy. Set the retention limit from your recovery point target and the time your team needs to rebuild a standby, not from a default. Alert on slot lag well before the limit is reached, and make sure the standby's own health check runs often enough to catch a stalled receiver.

  • Owner: the database or platform team that runs the standby.
  • Lost slot consequence: the standby needs a rebuild from a new base backup.
  • Retention limit: size it to cover your planned standby maintenance window and expected rebuild duration.
  • Alert: page on growing lag while there is still room under the limit, not at the limit.
  • Check: confirm which standbys use each slot, since a slot for a retired standby is a common source of leftover WAL.

Before changing any limit, confirm the recovery procedure for each standby and the time it takes in your environment.

Setting up slot monitoring and a retention cap

This sequence turns replication slots from an invisible risk into a monitored, capped and documented part of the cluster, so a stalled consumer cannot silently fill the primary's disk. Each step ends with a check the operations team can repeat.

  1. Inventory every slot and assign an owner

    On each primary, list every replication slot from pg_replication_slots, including physical slots used by standbys and logical slots used by CDC tools or subscribers. Record the slot type, the database it belongs to, the consumer that reads it, and the team accountable for that consumer. Slots without a known consumer are the first candidates for review, because nothing is reading them and they still hold WAL. The step is done when every slot has a named owner and a written purpose, and the team agrees that any slot without an owner will be investigated before the cap is set.

  2. Enable slot and retained WAL monitoring

    Build a query or exporter view that reads pg_replication_slots and reports, for each slot, whether it is active, its restart_lsn and confirmed_flush_lsn where relevant, and the amount of WAL the server retains for it. Compare each slot's restart position with the current WAL position so retained volume is visible per slot, not only as total disk use. Run the query on a schedule and store the results where operators can graph them. The step is done when a deliberately idle test slot shows as inactive and its retained WAL grows on the dashboard over time.

  3. Set max_slot_wal_keep_size from agreed headroom

    Choose a value for max_slot_wal_keep_size based on the free disk left after normal WAL and data growth, the time a consumer may legitimately be down, and the recovery needs the team has agreed with the business. Confirm the exact setting name, its units and its behavior on the PostgreSQL version in use in the PostgreSQL configuration documentation, and apply it with a reload if the version allows it. Keep the value below the point where a full disk would stop the primary. The step is done when SHOW max_slot_wal_keep_size returns the agreed value on every primary and the decision, with its reasoning, is recorded.

  4. Alert on inactive slots and approaching the cap

    Create two alert rules. The first fires when a slot is inactive for longer than the team's agreed tolerance, which surfaces abandoned consumers early. The second fires when retained WAL for any slot approaches max_slot_wal_keep_size, with warning and critical thresholds set below the cap so operators have time to act. Route alerts to the owner recorded in step one, and include the slot name and the consumer in the message. The step is done when each rule appears in the alerting system with a tested notification path and a documented owner.

  5. Document the invalidated slot recovery procedure

    Write a runbook for the consumer team describing what happens when a slot is invalidated because it exceeded the cap. Covered items should include how to confirm the invalidation in pg_replication_slots, how a logical consumer re-synchronizes from a fresh snapshot, how a physical standby is rebuilt from a new base backup, and who approves the action. Note that an invalidated slot cannot be reused for the same stream, so the consumer must restart from a known point. Confirm the details against the PostgreSQL documentation for the installed version and the CDC tool's own reinitialization steps. The step is done when a reviewer from the consumer team has read the runbook and can state each recovery path.

  6. Test the alert and cap in non-production

    In a non-production environment that mirrors the primary's configuration, create a logical or physical slot, pause its consumer, and generate write load until retained WAL rises. Confirm that the inactive-slot alert and the approaching-cap alert fire at the expected thresholds and reach the named owner. Continue the test until the cap is reached and verify that the slot is invalidated, that the primary keeps accepting writes, and that the runbook steps restore the consumer. Record observed behavior against what the documentation describes and correct the thresholds or runbook where they differ. The step is done when the test record shows each alert fired, the cap behaved as documented, and recovery worked end to end.

Security and operational risks around replication slots

A replication slot is a server-side promise to keep WAL until a consumer confirms it has read it, so every slot is both a data-exposure path and a disk-space liability. The cards below cover the decisions that keep slot creation, data flow, alerting and removal under deliberate control.

Who may create and drop slots

Creating a physical or logical slot requires replication privileges, and dropping one changes what the primary retains. Decide which roles hold the REPLICATION attribute, which accounts your CDC tool and standbys use, and who may run pg_drop_replication_slot(). Review role grants in pg_roles and pg_hba.conf entries for replication connections, since a slot created by an unexpected role is hard to trace later.

HA docs

Slot names that reveal consumers

Slot names are the only built-in hint about who depends on a slot, so name them after the consumer and environment, such as the pipeline and the target system. Keep a register that maps each slot to an owner, a consuming service, and the date it was last confirmed in use. An unlabeled slot named after a test script is the most common reason an abandoned slot survives for months.

Change data exposure through logical slots

A logical slot streams decoded row changes to whatever client reads it, so it can expose the contents of tables that the consumer's own role never queries. Confirm which tables and columns the publication includes, which downstream systems receive the stream, and how those systems store, mask and retain it. Treat the consumer's credentials and network path as part of the data classification for the source database.

Disk-space alerting with a named owner

Slot lag grows silently until the volume holding pg_wal fills and the primary stops writing. Set an alert on retained WAL per slot and on free space for the WAL volume, and name the team that receives it and the team that can act on it at night. Confirm who has authority to drop a slot in an emergency, because the alert is only useful if someone is allowed to act on it.

Change control for dropping slots

Dropping an active slot ends the consumer's position in the WAL stream, and a logical consumer that reconnects afterward may need a resync. Require a written request that names the slot, its owner, the evidence it is abandoned, and the rollback plan, such as a fresh snapshot for the consumer. Record each drop in the change log so later incidents can be traced to a decision rather than a cleanup script.

Slot tracking across failover

Physical slots on a primary do not automatically exist on its standbys, and logical slots need their own handling after promotion. Decide how each consumer will reconnect after a failover, whether through failover-enabled slots or by recreating them, and verify it in a test. Review the high availability documentation for standby behavior before choosing an approach, and include slot state in your failover runbook.

HA docs

Dropping a slot without breaking a consumer

A replication slot should be dropped only after its consumer is confirmed stopped or decommissioned. A slot is a promise from the primary to keep WAL until the consumer confirms it has processed that position. Dropping the slot removes that promise immediately, so any WAL the consumer still needs can be recycled, and a consumer that reconnects later will find a gap it cannot replay. For a physical standby, that usually means a rebuild from a new base backup. For a logical consumer such as a CDC pipeline, it usually means a resync of the affected tables and a decision about events that were never delivered. Treat the drop as a change with an owner, a ticket and a rollback path, not as cleanup.

Before running the drop, work through a fixed sequence. First, confirm the owner: find the team or service that created the slot, usually from its name, the application_name on the connection that uses it, or the deployment that references it, and get written confirmation that it is no longer needed. Second, confirm the consumer is detached: pg_replication_slots shows whether the slot has an active_pid, and the consumer's own logs or process list should agree that nothing is reading from it. Third, record the slot's restart_lsn, confirmed_flush_lsn for logical slots, its wal_status and its plugin so the state can be compared after the change. Fourth, take a backup or write down the recovery path, including the base backup and archived WAL needed to restore the consumer's data if it turns out the slot was still required.

Removing an unused slot is a routine change once those checks pass. Recovering from a slot that max_slot_wal_keep_size has invalidated is different: the slot is already lost, and its wal_status shows the WAL it needed has been removed. There is nothing left to protect, so the work is rebuilding the consumer, not preserving it. Confirm the exact drop function and its behavior for your PostgreSQL version in the PostgreSQL replication slot documentation, including how it treats an active slot, and test the sequence on a non-production cluster first.

Limits to confirm in your environment

The supplied sources explain how replication slots hold WAL, but they do not settle how retention limits behave on your chosen version, what each consumer sees when a slot is lost, or how your hardware and alerting should be sized. The cards below list what to confirm with the vendor documentation or a test run before you rely on a setting in production.

Retention setting behavior by version

Confirm the exact behavior and default of max_slot_wal_keep_size on the PostgreSQL version you run, including whether it is set at all in your configuration and what value your team has chosen. Read the setting's entry in the server configuration documentation for the version in use, then test it on a non-production primary by holding a slot idle and watching WAL accumulate. Record what happens to the slot at the limit, because the outcome determines which consumers you can afford to lose.

HA docs

Invalidated slot signals per consumer

An invalidated slot does not announce itself the same way to every consumer. Confirm how a streaming standby, a logical subscriber and each CDC connector report a slot that was removed or invalidated, including the error text, the log line and whether the consumer stops or retries. Reproduce the condition in a test environment for each consumer type you run, and make sure the alert your team relies on fires for that exact signal.

CDC resync path support

When a logical slot is lost, the CDC tool must rebuild its downstream state, and tools differ in how they do that. Confirm with the connector's documentation whether it supports a snapshot or resync from the source tables, whether that resync can run without downtime for your consumers, and how long it reads from the source while it runs. Test the full path against a realistic table volume before you commit to a retention window.

Slot handling during failover

Slots on a primary do not automatically exist on its standbys, so a failover can leave a consumer without its position. Confirm how your failover tool, and the PostgreSQL release you run, copy or synchronize logical slots to standbys, and whether standby slots are created for physical consumers. Run a planned switchover with an active logical consumer and check that the consumer resumes at the expected position without loss.

Failover docs

Disk headroom and alert thresholds

The right disk headroom depends on your write rate, WAL volume during peak batch jobs, checkpoint settings and how much space your archive and other files also need. Measure WAL generation on your own workload for a representative period, then set alert thresholds on the WAL directory and on slot lag in bytes, and confirm that the alert reaches an on-call person who can act within the time your headroom allows. Test the alert by stopping a consumer in staging.

Questions teams ask about replication slots and WAL retention

What drives the cost of fixing replication slot retention?

The cost comes from four pieces of work: setting up monitoring for slot lag and WAL disk use, auditing every consumer that holds a slot, recovering each affected consumer, and writing the runbooks that keep the problem from returning. Monitoring and the audit are mostly one-time work. Resync work depends on how many consumers fell behind and whether each one can resume from its position or must rebuild its copy of the data. Ongoing costs are usually alerting, periodic slot reviews and retesting after upgrades. Ask any partner to price each piece separately, list which consumers they expect to audit, and state whether resync is included or billed per consumer.

How long does a replication slot cleanup take?

The duration is set by the number of slots, the recovery method each consumer needs, and the volume of data those consumers must catch up on. A slot whose consumer can simply resume is quick to clear. A CDC pipeline that must rebuild a downstream table from a fresh snapshot takes much longer, because the snapshot and reload run before the slot can be safely dropped. Change windows and consumer owners also set the pace, since each drop has to wait for the team that depends on that slot to confirm. Ask for a schedule that lists each slot, its consumer, the expected recovery method and the sign-off step before any drop.

What does the client need to provide for this work?

The work needs four things from the client. First, a named owner for each replication slot, usually the team that runs the consumer such as a CDC tool, a standby or a reporting sync. Second, access to the primary servers with rights to read pg_replication_slots and pg_stat_replication, and to run the change on each primary. Third, a change window agreed in advance, because dropping a slot is irreversible and may affect downstream data. Fourth, a runbook for each consumer that explains how it resumes, rebuilds or retires. Without owners and runbooks, the work stalls at the first slot nobody can identify.

Can our own team fix runaway WAL retention without a partner?

Often yes, if the team already runs PostgreSQL in production and knows which applications read from each slot. The core steps are documented: read slot state, measure how far each slot trails, decide whether a consumer can catch up, and drop only slots that nobody needs. The harder part is organizational. Teams that lack a slot inventory, cannot reach the owners of CDC or standby consumers, or have never tested a consumer rebuild usually take longer than expected. A partner adds value mainly through the audit, the monitoring and the documented consumer recovery paths. Decide based on whether your team can complete the consumer audit within your change process.

How does a max_slot_wal_keep_size cap differ from a backup-based recovery plan?

A cap limits how much WAL the primary keeps for lagging slots, so a runaway slot cannot fill the disk. It protects the primary but invalidates the slot once the limit is exceeded, which means the consumer must rebuild. A backup-based recovery plan protects data. It combines a base backup with archived WAL so you can restore to a point in time, and it does not stop a slot from lagging. Teams usually need both: a cap to protect the server, and tested backups to protect the data. Confirm the exact behavior of the cap and the archive settings against the PostgreSQL documentation for your version before you set them.

Does setting a retention cap risk losing data for CDC consumers?

Yes, a consumer whose slot is invalidated by a cap loses its place in the WAL stream and cannot resume from it. It must recover from a snapshot or a replay from another source. For a CDC pipeline, that can mean a full reload of affected tables before events are consistent again. Downstream systems may show stale or missing data during that period. Before setting a cap, identify which consumers depend on continuous delivery, decide how each would recover, and agree the alerting that warns the owner while the slot is still healthy. Confirm with the CDC tool's documentation how it handles an invalidated slot.

What should we ask a partner to include in a written quote?

A written quote should list the scope in concrete terms. Ask for the inventory of slots and consumers covered, the monitoring and alert thresholds to be configured, the change plan for each primary, and the runbook for each consumer type. Confirm whether consumer resync is in scope or quoted separately, and how many consumers are included. Ask who performs each change, what evidence you receive at the end, and what happens if a consumer cannot recover within the window. Request the assumptions behind the schedule, the client responsibilities listed above, and any work that recurs after the first cleanup, such as slot reviews after upgrades.

How DeployOpen scopes and delivers slot monitoring and retention

DeployOpen treats replication slots as a retention risk to be designed, tested and documented before they cause an outage. We scope the slot inventory, retention limits and monitoring for your PostgreSQL environment, then build and test them in infrastructure you control. Engagements are fixed-scope, with the written scope agreed before work starts.

How we scope

  • Inventory every physical and logical slot, its consumer, and the owning team for each
  • Define the retention ceiling for WAL held by slots against your free disk and backup plans
  • Agree in writing which CDC tools, standbys and failover designs depend on each slot

How we build

  • Set max_slot_wal_keep_size and alert thresholds based on the scoped disk and recovery requirements
  • Build lag and retained-WAL monitoring with alerts routed to the operators who can act
  • Test slot behavior with a lagging consumer and a deliberately stalled slot in a non-production environment

How we hand over

  • Document the slot register, owners, and the runbook for safely dropping an abandoned slot
  • Record configuration changes, alert definitions and test results for your change and review records
  • Walk your operators through the runbook and confirm they can run it without DeployOpen present

How we support

  • Ongoing support, upgrades and periodic slot reviews are available as a retainer
  • Review new CDC connectors and slot requests against the agreed retention ceiling before they go live
  • Confirm the scope and any change requests in writing before additional work starts

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.