diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 109c723f4e..fcea56d1c1 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -1469,6 +1469,9 @@ WalSndWaitForWal(XLogRecPtr loc)
 		/* Send keepalive if the time has come */
 		WalSndKeepaliveIfNecessary();
 
+		/* We may have queued a keep alive packet. flush it before sleeping. */
+		pq_flush_if_writable();
+		
 		/*
 		 * Sleep until something happens or we time out.  Also wait for the
 		 * socket becoming writable, if there's still pending output.
