Advertisement
cbossie

AG Sync Lag

Apr 5th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.90 KB | None | 0 0
  1. ;WITH UpTime AS
  2.             (
  3.             SELECT DATEDIFF(SECOND,create_date,GETDATE()) [upTime_secs]
  4.             FROM sys.databases
  5.             WHERE name = 'tempdb'
  6.             ),
  7.     AG_Stats AS
  8.             (
  9.             SELECT AR.replica_server_name,
  10.                    HARS.role_desc,
  11.                    Db_name(DRS.database_id) [DBName],
  12.                    CAST(DRS.log_send_queue_size AS DECIMAL(19,2)) log_send_queue_size_KB,
  13.                    (CAST(perf.cntr_value AS DECIMAL(19,2)) / CAST(UpTime.upTime_secs AS DECIMAL(19,2))) / CAST(1024 AS DECIMAL(19,2)) [log_KB_flushed_per_sec]
  14.             FROM   sys.dm_hadr_database_replica_states DRS
  15.             INNER JOIN sys.availability_replicas AR ON DRS.replica_id = AR.replica_id
  16.             INNER JOIN sys.dm_hadr_availability_replica_states HARS ON AR.group_id = HARS.group_id
  17.                 AND AR.replica_id = HARS.replica_id
  18.             --I am calculating this as an average over the entire time that the instance has been online.
  19.             --To capture a smaller, more recent window, you will need to:
  20.             --1. Store the counter value.
  21.             --2. Wait N seconds.
  22.             --3. Recheck counter value.
  23.             --4. Divide the difference between the two checks by N.
  24.             INNER JOIN sys.dm_os_performance_counters perf ON perf.instance_name = Db_name(DRS.database_id)
  25.                 AND perf.counter_name like 'Log Bytes Flushed/sec%'
  26.             CROSS APPLY UpTime
  27.             ),
  28.     Pri_CommitTime AS
  29.             (
  30.             SELECT  replica_server_name
  31.                     , DBName
  32.                     , [log_KB_flushed_per_sec]
  33.             FROM    AG_Stats
  34.             WHERE   role_desc = 'PRIMARY'
  35.             ),
  36.     Sec_CommitTime AS
  37.             (
  38.             SELECT  replica_server_name
  39.                     , DBName
  40.                     --Send queue will be NULL if secondary is not online and synchronizing
  41.                     , log_send_queue_size_KB
  42.             FROM    AG_Stats
  43.             WHERE   role_desc = 'SECONDARY'
  44.             )
  45. SELECT p.replica_server_name [primary_replica]
  46.     , p.[DBName] AS [DatabaseName]
  47.     , s.replica_server_name [secondary_replica]
  48.     ,s.log_send_queue_size_KB / p.[log_KB_flushed_per_sec] [Sync_Lag_Secs]
  49. FROM Pri_CommitTime p
  50. LEFT JOIN Sec_CommitTime s ON [s].[DBName] = [p].[DBName]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement