Skip to content
Database

手动复制监控

Track replication health and performance.

监控复制延迟很重要,有三种方法可以做到这一点:

🌐 Monitoring replication lag is important and there are 3 ways to do this:

  1. 仪表板 - 在 报告 中,你可以查看项目的复制延迟
  2. 数据库 -
    • pg_stat_subscription(订阅者)- 如果 PID 为 null,则订阅未激活
    • pg_stat_subscription_stats - 查看这里的 error_count 来看看在应用或同步时是否有问题(如果有,查看日志了解原因)
    • pg_replication_slots - 用这个可以检查槽是否活跃,你也可以从这里计算延迟
  3. 指标 - 使用你项目的 prometheus 端点
    • replication_slots_max_lag_bytes - 这个更重要
    • pg_stat_replication_replay_lag - 在目标数据库上回放源数据库的 WAL 文件的延迟(受磁盘或高活动限制)
    • pg_stat_replication_send_lag - 从源数据库发送 WAL 文件的延迟(延迟高意味着发布者没有被要求发送新的 WAL 文件,或存在网络问题)

主要 #

🌐 Primary

复制状态和延迟 #

🌐 Replication status and lag

pg_stat_replication 表显示了连接到主数据库的所有副本的状态。

🌐 The pg_stat_replication table shows the status of any replicas connected to the primary database.

1
select pid, application_name, state, sent_lsn, write_lsn, flush_lsn, replay_lsn, sync_state
2
from pg_stat_replication;

复制槽状态 #

🌐 Replication slot status

一个复制槽可以处于三种状态之一:

🌐 A replication slot can be in one of three states:

  • active - 插槽处于活动状态并正在接收数据
  • inactive - 这个插槽没有激活,也没有接收数据
  • lost - 这个插槽丢失了,没有接收到数据

可以用 pg_replication_slots 表来查看状态:

🌐 The state can be checked using the pg_replication_slots table:

1
select slot_name, active, state from pg_replication_slots;

WAL 大小 #

🌐 WAL size

可以使用 pg_ls_waldir() 函数来检查 WAL 大小:

🌐 The WAL size can be checked using the pg_ls_waldir() function:

1
select * from pg_ls_waldir();

检查 LSN #

🌐 Check the LSN

1
select pg_current_wal_lsn();

订阅者 #

🌐 Subscriber

订阅状态 #

🌐 Subscription status

pg_subscription 表显示了副本上任何订阅的状态,而 pg_subscription_rel 表显示了订阅中每个表的状态。

🌐 The pg_subscription table shows the status of any subscriptions on a replica and the pg_subscription_rel table shows the status of each table within a subscription.

pg_subscription_rel 中的 srsubstate 列可以是以下之一:

🌐 The srsubstate column in pg_subscription_rel can be one of the following:

  • i - 初始化中 - 订阅正在初始化
  • d - 数据同步中 - 订阅正在第一次同步数据(即进行初始复制)
  • s - 已同步 - 订阅已同步
  • r - 正在复制 - 订阅正在复制数据
1
SELECT
2
sub.subname AS subscription_name,
3
relid::regclass AS table_name,
4
srel.srsubstate AS replication_state,
5
CASE srel.srsubstate
6
WHEN 'i' THEN 'Initializing'
7
WHEN 'd' THEN 'Data Synchronizing'
8
WHEN 's' THEN 'Synchronized'
9
WHEN 'r' THEN 'Replicating'
10
ELSE 'Unknown'
11
END AS state_description,
12
srel.srsyncedlsn AS last_synced_lsn
13
FROM
14
pg_subscription sub
15
JOIN
16
pg_subscription_rel srel ON sub.oid = srel.srsubid
17
ORDER BY
18
table_name;

检查 LSN #

🌐 Check the LSN

1
select pg_last_wal_replay_lsn();