From 94817d93be7dec98125f1c66385472f7dfe23180 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Wed, 2 Dec 2026 09:04:20 +0100
Subject: [PATCH v02122026 4/4] WAIT FOR LSN: avoid WaitLSNWakeupStandby()
 during crash-recovery

Avoid memory barrier and reading of three atomics in the main redo loop if
there cannot be potential WAIT FOR LSN backends as hot standby database did
no open yet.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Discussion: https://postgr.es/m/CAKZiRmzEs%2BS60pW_gbjBjSrRYLKfKRf08dTcmN-7%2Bqh8aDFPsw%40mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 4e0c03af07d..58382e290f0 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1808,8 +1808,13 @@ PerformWalRecovery(void)
 			 * LSN to reach current replay position.  Replay implies that the
 			 * WAL was already written and flushed to disk, so write and flush
 			 * waiters can be woken at the replay position too.
+			 *
+			 * Optimize this out during plain crash recovery: backends can connect
+			 * and issue WAIT FOR LSN only after consistency point has been reached
+			 * and hot standby has opened.
 			 */
-			WaitLSNWakeupStandby(XLogRecoveryCtl->lastReplayedEndRecPtr);
+			if (InArchiveRecovery && LocalHotStandbyActive)
+				WaitLSNWakeupStandby(XLogRecoveryCtl->lastReplayedEndRecPtr);
 
 			/* Exit loop if we reached inclusive recovery target */
 			if (recoveryStopsAfter(xlogreader))
-- 
2.43.0

