diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 15fa4d0a55e..56218cb6863 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -166,6 +166,7 @@ static void MemoryContextStatsInternal(MemoryContext context, int level,
 static void MemoryContextStatsPrint(MemoryContext context, void *passthru,
 									const char *stats_string,
 									bool print_to_stderr);
+static bool CheckMemoryContextLeak(MemoryContext context);
 
 /*
  * You should not do memory allocations within a critical section, because
@@ -502,6 +503,7 @@ MemoryContextDeleteOnly(MemoryContext context)
 	Assert(context != CurrentMemoryContext);
 	/* All the children should've been deleted already */
 	Assert(context->firstchild == NULL);
+	Assert(CheckMemoryContextLeak(context));
 
 	/*
 	 * It's not entirely clear whether 'tis better to do this before or after
@@ -530,6 +532,24 @@ MemoryContextDeleteOnly(MemoryContext context)
 	VALGRIND_DESTROY_MEMPOOL(context);
 }
 
+static bool
+CheckMemoryContextLeak(MemoryContext context)
+{
+#ifdef MEMORY_CONTEXT_CHECKING
+	if (!context->name)
+		return true;
+
+	if (!strcmp(context->name, "Subplan HashTable Temp Context") == 0)
+		return true;
+
+	/* The size of short-lived contexts should be kept under 1 MB. */
+	if ((MemoryContextMemAllocated(context, false) > 1024 * 1024))
+		return false;
+#endif
+	return true;
+}
+
+
 /*
  * MemoryContextDeleteChildren
  *		Delete all the descendants of the named context and release all
