Replication and Standby Status

A standby (secondary) receives the primary's logs and replays them to keep the same data. The stages are the same in all three databases: the log is sent (transport), the standby receives it and writes it to disk, and then applies it (redo, replay). Lag arises separately at each stage, so look at "how far behind" as transport lag and apply lag separately. Transport lag is the data you could lose in a failure (RPO), and apply lag is the time a failover takes (RTO) and the data freshness of a read-only standby.

Oracle

This is based on Data Guard. Data Guard is included in Enterprise Edition. To apply while the standby is open read-only (Real-Time Query), you need an Active Data Guard option license. If you apply only in MOUNT state, you do not.

Required privileges: V$ view access (SELECT_CATALOG_ROLE). If the standby is in MOUNT state, you must connect as SYSDBA or SYSDG (12c+) to query.

Role and protection mode

SELECT name, db_unique_name, database_role, open_mode,
       protection_mode, protection_level, switchover_status
FROM v$database;
  • database_role: PRIMARY, PHYSICAL STANDBY, LOGICAL STANDBY, SNAPSHOT STANDBY.
  • If open_mode is READ ONLY WITH APPLY, Active Data Guard is in use.
  • If protection_mode and protection_level differ (for example, MAXIMUM AVAILABILITY but the level is RESYNCHRONIZATION), synchronous transport is not working right now.

Lag on the standby (V$DATAGUARD_STATS)

SELECT name, value, unit, time_computed, datum_time
FROM v$dataguard_stats
WHERE name IN ('transport lag', 'apply lag', 'apply finish time');
  • value is a day-to-time interval string such as +00 00:00:05.
  • transport lag: how much of the redo generated on the primary has not yet been received. apply lag: how much has been received but not yet applied.
  • If datum_time is old, contact with the primary has been lost, so the value itself cannot be trusted.

Transport destination status on the primary (V$ARCHIVE_DEST_STATUS)

SELECT dest_id, dest_name, status, type, database_mode, recovery_mode,
       gap_status, archived_seq#, applied_seq#, error
FROM v$archive_dest_status
WHERE status <> 'INACTIVE' AND type <> 'LOCAL';
  • If status = ERROR, error has the cause (network errors such as ORA-12541 are common).
  • If gap_status is not NO GAP, the standby has not received some archive logs. On the standby, run SELECT * FROM v$archive_gap; to see the missing sequence numbers.
  • If recovery_mode is MANAGED REAL TIME APPLY, real-time apply (using standby redo logs) is in progress. If IDLE, the apply process (MRP) is stopped.

Standby processes and apply position

-- 12.2+ (earlier versions use V$MANAGED_STANDBY)
SELECT name, role, action, client_role, thread#, sequence#, block#
FROM v$dataguard_process
ORDER BY name;

SELECT thread#, MAX(sequence#) AS last_applied
FROM v$archived_log
WHERE applied = 'YES'
GROUP BY thread#;

If there is no process with name MRP0 (role = 'managed recovery'), apply has stopped.

Overview with the Broker (DGMGRL)

dgmgrl sys@orcl_prim      # enter the password at the prompt
SHOW CONFIGURATION;
SHOW DATABASE 'orcl_stby';
VALIDATE DATABASE 'orcl_stby';      -- 12c+, checks readiness for switchover

If the last line of SHOW CONFIGURATION is not SUCCESS, look at the WARNING/ERROR details.

Start and stop apply

-- On the standby
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;   -- real-time apply is the default from 12c
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

If you use the Broker, use EDIT DATABASE 'orcl_stby' SET STATE='APPLY-ON'; (or APPLY-OFF) instead of SQL. Changing it with SQL puts it out of sync with the Broker configuration.

WARNING While apply is stopped, apply lag keeps growing, and if you fail over then, you must wait until all the backlog of logs is applied. Turn it back on as soon as the work is done.

PostgreSQL

This is based on streaming replication. Required privileges: to see the LSN and lag columns of pg_stat_replication, you need superuser or pg_read_all_stats (pg_monitor). Without the privilege, those columns come back NULL.

Standby list and lag on the primary (pg_stat_replication)

SELECT application_name, client_addr, state, sync_state,
       sent_lsn, write_lsn, flush_lsn, replay_lsn,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn))   AS not_sent,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS not_replayed,
       write_lag, flush_lag, replay_lag, reply_time                          -- reply_time: 12+
FROM pg_stat_replication;
  • state: streaming is normal. catchup means it is catching up on backlogged WAL, and backup is a pg_basebackup connection.
  • sync_state: async, sync, potential (synchronous candidate), quorum. If a server listed in synchronous_standby_names is not here, commits on the primary can stall.
  • *_lag (10+) is time lag. If there are no writes on the primary and it has fully caught up, it becomes NULL after a short while.
  • If a standby is not in this list, its connection has dropped. Check the standby log and primary_conninfo.

Replication slots (pg_replication_slots)

SELECT slot_name, slot_type, database, active, wal_status, safe_wal_size,   -- wal_status, safe_wal_size: 13+
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots
ORDER BY restart_lsn;
  • A slot prevents WAL from being removed before the standby (or logical replication subscriber) has fetched it. If a slot with active = false stays around for a long time, pg_wal grows without bound and the disk fills up.
  • wal_status: reserved, extended (normal range), unreserved (about to be removed), lost (the required WAL has already been removed, so replication cannot continue with that slot).
  • PostgreSQL 13+ can cap the WAL a slot holds with max_slot_wal_keep_size. 17+ also has the inactive_since and invalidation_reason columns.
SELECT pg_drop_replication_slot('old_standby_slot');

WARNING If you drop a slot, the standby or subscriber that was using it can no longer receive the WAL it needs, and may have to be rebuilt from a base backup. First confirm which server the slot name belongs to.

Receive status on the standby (pg_stat_wal_receiver)

SELECT status, sender_host, sender_port, slot_name,
       written_lsn, flushed_lsn, latest_end_lsn,                    -- written/flushed_lsn: 13+
       latest_end_time, last_msg_receipt_time
FROM pg_stat_wal_receiver;
  • If there is no row, there is no WAL receiver process (the connection failed, or it is recovering only from the archive).
  • If last_msg_receipt_time is old, communication with the primary has been lost.

Apply lag on the standby

SELECT pg_is_in_recovery(),
       pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(),
       pg_size_pretty(pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn())) AS not_replayed,
       now() - pg_last_xact_replay_timestamp() AS replay_delay;
  • replay_delay is based on the commit time of the last transaction applied. If there are no writes on the primary, it keeps growing even though the standby has caught up. Read it together with the byte difference (not_replayed).
  • If read queries on the standby block apply (max_standby_streaming_delay), lag results. pg_stat_database_conflicts shows the number of canceled queries.

Promote a standby

SELECT pg_promote();      -- PostgreSQL 12+, pg_ctl promote from the shell

WARNING Promotion cannot be undone. If you promote while the old primary is still alive, both servers accept writes, which is split-brain. Stop the old primary first, and when you reattach it as a standby, use pg_rewind or a new base backup.

SQL Server

This is based on Always On availability groups (AG). The full feature set (multiple databases, readable secondary replicas, backups on secondary replicas) is Enterprise Edition. Standard Edition (2016+) supports only Basic AG: two replicas, one database per AG, and no reads on the secondary replica.

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on 2022+).

Replica status

SELECT ag.name AS ag_name, ar.replica_server_name, ars.role_desc,
       ar.availability_mode_desc, ar.failover_mode_desc,
       ars.connected_state_desc, ars.synchronization_health_desc,
       ars.operational_state_desc
FROM sys.availability_groups ag
JOIN sys.availability_replicas ar ON ar.group_id = ag.group_id
JOIN sys.dm_hadr_availability_replica_states ars ON ars.replica_id = ar.replica_id
ORDER BY ag.name, ars.role_desc;
  • Run on the primary, it shows all replicas; on a secondary replica, it shows detail only for itself.
  • Look first at any replica with connected_state_desc = DISCONNECTED or a synchronization_health_desc other than HEALTHY.

Per-database synchronization and queues (sys.dm_hadr_database_replica_states)

SELECT ar.replica_server_name, DB_NAME(drs.database_id) AS db,
       drs.is_primary_replica, drs.synchronization_state_desc, drs.synchronization_health_desc,
       drs.is_suspended, drs.suspend_reason_desc,
       drs.log_send_queue_size AS send_queue_kb, drs.log_send_rate AS send_kb_per_sec,
       drs.redo_queue_size     AS redo_queue_kb, drs.redo_rate     AS redo_kb_per_sec,
       drs.last_commit_time, drs.secondary_lag_seconds              -- secondary_lag_seconds: 2016+
FROM sys.dm_hadr_database_replica_states drs
JOIN sys.availability_replicas ar ON ar.replica_id = drs.replica_id
ORDER BY db, ar.replica_server_name;
  • log_send_queue_size: log (KB) the primary has not yet sent. This is the amount you could lose in a failure (RPO).
  • redo_queue_size: log (KB) the secondary replica has received but not yet applied. This is how much failover will be delayed (RTO).
  • Rough times, in seconds, are send_queue_kb / send_kb_per_sec and redo_queue_kb / redo_kb_per_sec.
  • synchronization_state_desc: SYNCHRONIZED is normal for synchronous-commit replicas and SYNCHRONIZING for asynchronous-commit ones. NOT SYNCHRONIZING means data movement has stopped.
  • For lag between secondary replicas, compare last_commit_time against the primary's value.

Suspend and resume data movement

ALTER DATABASE sales SET HADR SUSPEND;
ALTER DATABASE sales SET HADR RESUME;

WARNING Suspending on the primary stops sending to all secondary replicas, and in the meantime the primary's transaction log cannot be truncated, so the log file grows (log_reuse_wait_desc = AVAILABILITY_REPLICA). While suspended, automatic failover for that database also cannot happen.

Manual failover

Run on the secondary replica you are switching to.

ALTER AVAILABILITY GROUP ag_sales FAILOVER;                          -- a synchronized synchronous-commit replica
ALTER AVAILABILITY GROUP ag_sales FORCE_FAILOVER_ALLOW_DATA_LOSS;    -- forced (data loss possible)

WARNING FORCE_FAILOVER_ALLOW_DATA_LOSS loses as much data as the log that was not sent. After a forced failover, data movement to the other secondary replicas is suspended, so you must run SET HADR RESUME on them one by one. Use it only when the primary is truly unrecoverable.

When using log shipping

SELECT secondary_server, secondary_database, last_copied_date,
       last_restored_date, last_restored_latency, restore_threshold
FROM msdb.dbo.log_shipping_monitor_secondary;

If last_restored_date is older than restore_threshold (minutes), the restore job (an Agent job) is failing.