diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 588e9f2b85da443c7fb290f8548ac3960fd8923f..02f8f9cd635d50db5c9e3f18b11adbaac6331fd6 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -1090,6 +1090,7 @@ Exec_UnlistenAllCommit(void)
 void
 ProcessCompletedNotifies(void)
 {
+	MemoryContext caller_context;
 	bool		signalled;
 
 	/* Nothing to do if we didn't send any notifications */
@@ -1103,6 +1104,12 @@ ProcessCompletedNotifies(void)
 	 */
 	backendHasSentNotifications = false;
 
+	/*
+	 * We must preserve the caller's memory context (probably MessageContext)
+	 * across the transaction we do here.
+	 */
+	caller_context = CurrentMemoryContext;
+
 	if (Trace_notify)
 		elog(DEBUG1, "ProcessCompletedNotifies");
 
@@ -1135,6 +1142,8 @@ ProcessCompletedNotifies(void)
 
 	CommitTransactionCommand();
 
+	MemoryContextSwitchTo(caller_context);
+
 	/* We don't need pq_flush() here since postgres.c will do one shortly */
 }