From 385f3729beb9e1e4bcf77e1428925a76e3300fdd Mon Sep 17 00:00:00 2001
From: Martijn van Oosterhout <oosterhout@fox-it.com>
Date: Mon, 3 Jun 2019 17:10:38 +0200
Subject: [PATCH 2/3] Don't notify other backends about notifications without
 cause.

It could be that there are other databases with active listens but unless
they need to know because it may be useful to advance the queue tail,
there's no point waking them up.
---
 src/backend/commands/async.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 53e28fe777..18bd3e975e 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -1519,11 +1519,13 @@ SignalBackends(void)
 	int			count;
 	int			i;
 	int32		pid;
+	int			notify_all = false;
 
 	/*
 	 * Identify all backends that are listening and not already up-to-date. We
 	 * don't want to send signals while holding the AsyncQueueLock, so we just
-	 * build a list of target PIDs.
+	 * build a list of target PIDs. If we haven't moved to a new page there is
+	 * no point notifying backends of other databases.
 	 *
 	 * XXX in principle these pallocs could fail, which would be bad. Maybe
 	 * preallocate the arrays?	But in practice this is only run in trivial
@@ -1532,6 +1534,7 @@ SignalBackends(void)
 	pids = (int32 *) palloc(MaxBackends * sizeof(int32));
 	ids = (BackendId *) palloc(MaxBackends * sizeof(BackendId));
 	count = 0;
+	notify_all = QUEUE_POS_PAGE(QUEUE_HEAD) != QUEUE_POS_PAGE(QUEUE_TAIL);
 
 	LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
 	for (i = 1; i <= MaxBackends; i++)
@@ -1541,6 +1544,9 @@ SignalBackends(void)
 		{
 			QueuePosition pos = QUEUE_BACKEND_POS(i);
 
+			if (!notify_all && QUEUE_BACKEND_DBOID(i) != MyDatabaseId)
+				continue;
+
 			if (!QUEUE_POS_EQUAL(pos, QUEUE_HEAD))
 			{
 				pids[count] = pid;
-- 
2.11.0

