diff --git a/src/backend/access/gist/gistbuild.c b/src/backend/access/gist/gistbuild.c
index 58f1ef221e12196dc735a0aeece0036aaff0669a..0046c7b3ab3a106cf1343070bf39acb7db1cdc55 100644
--- a/src/backend/access/gist/gistbuild.c
+++ b/src/backend/access/gist/gistbuild.c
@@ -964,10 +964,14 @@ gistEmptyAllBuffers(GISTBuildState *buildstate)
 				 * Add this buffer to the emptying queue, and proceed to empty
 				 * the queue.
 				 */
-				MemoryContextSwitchTo(gfbb->context);
-				gfbb->bufferEmptyingQueue =
-					lcons(nodeBuffer, gfbb->bufferEmptyingQueue);
-				MemoryContextSwitchTo(buildstate->tmpCtx);
+				if (!nodeBuffer->queuedForEmptying)
+				{
+					MemoryContextSwitchTo(gfbb->context);
+					nodeBuffer->queuedForEmptying = true;
+					gfbb->bufferEmptyingQueue =
+						lcons(nodeBuffer, gfbb->bufferEmptyingQueue);
+					MemoryContextSwitchTo(buildstate->tmpCtx);
+				}
 				gistProcessEmptyingQueue(buildstate);
 			}
 			else