diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index f845180..2611d62 100644
*** a/src/backend/replication/walsender.c
--- b/src/backend/replication/walsender.c
*************** WalSndWaitForWal(XLogRecPtr loc)
*** 1374,1379 ****
--- 1374,1387 ----
  		if (pq_flush_if_writable() != 0)
  			WalSndShutdown();
  
+ 		/*
+ 		 * If we have received CopyDone from the client, sent CopyDone
+ 		 * ourselves, and the output buffer is empty, it's time to exit
+ 		 * streaming, so fail the current WAL fetch request.
+ 		 */
+ 		if (!pq_is_send_pending() && streamingDoneSending && streamingDoneReceiving)
+ 			break;
+ 
  		now = GetCurrentTimestamp();
  
  		/* die if timeout was reached */

