Fast EXPLAIN ANALYZE 2: Cutting the Overhead from 25% to 6.6%, or Even 1.8%

TL;DR

  • lite-rowcount patch: it reduces the overhead of EXPLAIN (ANALYZE, TIMING OFF) from 25% to 6.6%, with no measurable impact on ordinary SELECT statements.
  • feather-rowcount patch: an experimental variant that counts rows inline in ExecProcNode() without a wrapper. It reduces the overhead further, to under 1.8%, but slows plain SELECT statements by about 0.8%.

Introduction

EXPLAIN ANALYZE executes a query and reports, for every plan node, the number of rows it actually returned. With TIMING OFF it collects nothing else, so you would expect it to be almost free. In PostgreSQL it is not: in my benchmark the query runs about 25% slower.

This matters because row counts of running queries are useful far beyond a manual EXPLAIN ANALYZE:

  1. Detection of cardinality estimation errors. Comparing the planner’s estimated rows with the actual rows is the most direct way to find out why a bad plan was chosen. If the counts were always available, this could feed back into the optimizer, including modern AI-based techniques.
  2. Query progress monitoring. The number of rows each node has returned so far tells you how far a long-running query has progressed.

Both require that counting rows is cheap enough to be left on for ordinary queries. Making EXPLAIN (ANALYZE, TIMING OFF) fast is the first step in that direction.

I have been working on this topic for over a year. The earlier posts are listed below; you do not need to read them to follow this post.

This post presents lite-rowcount, the result of that work: a small patch (about 80 lines in six files) with two properties:

  • EXPLAIN (ANALYZE, TIMING OFF) runs with about 6.6% overhead instead of 25%.
  • Ordinary SELECT statements are not measurably affected, because the code that they execute is unchanged.

The patches and the benchmark tool are here: https://github.com/s-hironobu/fast_explain_analyze

Everything in this post is limited to row counting: TIMING, BUFFERS and WAL usage must all be off. If any of them is on, the existing code path is used unchanged.

Appendix A describes feather-rowcount, an experimental variant that lowers the overhead further at a small cost for plain SELECT statements.

Background

Execution paths

When a parent node wants a tuple from its child, it calls ExecProcNode(child). ExecProcNode() is a static inline function in executor.h, so it is expanded into the parent’s code, and all it does is an indirect call through child->ExecProcNode. That function pointer is set once per node, by ExecProcNodeFirst(), on the node’s first call.

Figure 1. Execution paths selected by ExecProcNodeFirst(). Orange boxes are per-tuple instrumentation work; dashed boxes are inline code with no call of their own.

  • (a) Without EXPLAIN ANALYZE, ExecProcNode points to the node’s real function (ExecProcNodeReal): one indirect call per tuple.
  • (b) With EXPLAIN ANALYZE, it points to the wrapper ExecProcNodeInstr(), which calls InstrStartNode(), then the real function, then InstrStopNode().
  • (c) lite-rowcount: the same wrapper structure as (b), but the wrapper only counts the row.

Because the path is chosen per node, at run time, a node that is not instrumented never sees a wrapper, and its code is not changed.

Why (b) is expensive

Even with TIMING and BUFFERS off, ExecProcNodeInstr() follows the node->instrument pointer, tests need_timer, need_bufusage and need_walusage twice (in InstrStartNode() and InstrStopNode()), adds 1.0 to a double, and tests and sets running and async_mode. For counting rows, none of this is needed: one increment is enough.

Implementation

A packed counter in PlanState

The “enabled” flag, the “running” flag and the row count are packed into one uint64 named instr_rows, which is placed in PlanState right after the ExecProcNode and ExecProcNodeReal pointers:

typedef struct PlanState
{
	...
	ExecProcNodeMtd ExecProcNode;	/* function to return next tuple */
	ExecProcNodeMtd ExecProcNodeReal;	/* actual function, if above is a
										 * wrapper */

	/*
	 * Compact per-cycle row counter, used instead of ExecProcNodeInstr when
	 * the row count is the only instrumentation needed for this node.  It is
	 * maintained by ExecProcNodeInstrRows() and folded into *instrument by
	 * ExecInstrEndLoop().  Zero when not in use.  See INSTR_ROWS_* below.
	 */
	uint64		instr_rows;

	NodeInstrumentation *instrument;	/* Optional runtime stats for this
										 * node */
	...
} PlanState;

#define INSTR_ROWS_ENABLED		(UINT64CONST(1) << 63)
#define INSTR_ROWS_RUNNING		(UINT64CONST(1) << 62)
#define INSTR_ROWS_COUNT_MASK	(INSTR_ROWS_RUNNING - 1)

Figure 2. Layout of instr_rows and the memory accesses per tuple. master follows the instrument pointer and touches several fields of NodeInstrumentation. The patch touches one word in PlanState, next to the ExecProcNodeReal pointer that the wrapper has just loaded.

instr_rows is a private counter: it is folded into the existing double fields of NodeInstrumentation at the end of each loop (see below). EXPLAIN, auto_explain, parallel query and extensions therefore see the same data types as before.

The wrapper

The wrapper does the whole per-tuple work: one load, an OR, an add and one store.

static TupleTableSlot *
ExecProcNodeInstrRows(PlanState *node)
{
	TupleTableSlot *result = node->ExecProcNodeReal(node);

	node->instr_rows = (node->instr_rows | INSTR_ROWS_RUNNING) +
		(TupIsNull(result) ? 0 : 1);

	return result;
}

This is the arm64 code that Apple clang generates with -O3, the compiler used for the benchmark (comments added; the result == NULL case is a second copy of the tail, omitted here):

_ExecProcNodeInstrRows:
	stp	x20, x19, [sp, #-0x20]!
	stp	x29, x30, [sp, #0x10]
	add	x29, sp, #0x10
	mov	x19, x0
	ldr	x8, [x0, #0x20]                ; node->ExecProcNodeReal
	blr	x8                             ; call ExecXXX()
	ldr	x8, [x19, #0x28]               ; load node->instr_rows
	cbz	x0, .Lnull                     ; result == NULL ?
	ldrh	w9, [x0, #0x4]                 ; slot->tts_flags
	tst	w9, #0x2
	cset	w9, eq                         ; !TTS_EMPTY(slot)
	orr	x8, x8, #0x4000000000000000    ; | INSTR_ROWS_RUNNING
	add	x8, x9, x8
	str	x8, [x19, #0x28]               ; store node->instr_rows
	ldp	x29, x30, [sp, #0x10]
	ldp	x20, x19, [sp], #0x20
	ret

A tuple costs 17 instructions, including a stack frame (four registers saved and restored) and a second blr/ret pair. ExecProcNodeReal (offset 0x20) and instr_rows (offset 0x28) are neighbors in memory.

Selecting the path: ExecProcNodeFirst()

ExecProcNodeFirst() selects the wrapper only when the row count is the only thing needed:

	if (node->instrument)
	{
		Instrumentation *instr = &node->instrument->instr;

		if (instr->need_timer || instr->need_bufusage || instr->need_walusage)
			node->ExecProcNode = ExecProcNodeInstr;		/* unchanged */
		else
		{
			node->instr_rows = INSTR_ROWS_ENABLED;
			node->ExecProcNode = ExecProcNodeInstrRows;
		}
	}
	else
		node->ExecProcNode = node->ExecProcNodeReal;	/* unchanged */

A node uses either ExecProcNodeInstr() or ExecProcNodeInstrRows(), never both, so a row is never counted twice.

Folding the counter: ExecInstrEndLoop()

EXPLAIN reads tuplecount and running through InstrEndLoop(), which is called at the end of each loop (on rescan, when EXPLAIN prints the plan, and when a parallel worker reports its statistics). The patch adds a thin function that first folds instr_rows into NodeInstrumentation and then calls InstrEndLoop():

void
ExecInstrEndLoop(PlanState *node)
{
	NodeInstrumentation *instr = node->instrument;
	uint64		rows = node->instr_rows;

	if (instr == NULL)
		return;

	if (rows & INSTR_ROWS_RUNNING)
	{
		instr->running = true;
		instr->tuplecount += (double) (rows & INSTR_ROWS_COUNT_MASK);
		node->instr_rows = rows & INSTR_ROWS_ENABLED;
	}

	InstrEndLoop(instr);
}

The five existing calls of InstrEndLoop(planstate->instrument) (one in execAmi.c, three in explain.c, one in execParallel.c) are replaced by ExecInstrEndLoop(planstate).

Two places maintain the instrumentation by themselves: nodes executed by MultiExecProcNode() (Hash, BitmapIndexScan, BitmapAnd, BitmapOr) and asynchronous execution (execAsync.c, postgres_fdw). Because the folding uses +=, rows counted there are simply added to the rows counted in instr_rows.

Why a plain SELECT has no overhead

  1. The normal path is unchanged. Without EXPLAIN ANALYZE, ExecProcNodeFirst() still sets node->ExecProcNode = node->ExecProcNodeReal, exactly as master does. Nothing is called in between.
  2. The inline ExecProcNode() is unchanged. It is expanded into the code of every parent node, so any instruction added there would run for every tuple of every query. lite-rowcount adds none, and adds nothing to any ExecXXX() either. The new code lives in a separate function, reachable only through the function pointer of a node that is instrumented for row counting.
  3. The other additions are not per-tuple. The setup in ExecProcNodeFirst() runs once per node, and ExecInstrEndLoop() once per loop.
  4. The only change on the normal path is the data layout: PlanState is 8 bytes larger. In theory this could affect alignment and caching; the benchmark below shows no measurable effect.

The remaining cost of lite-rowcount is one extra function call per tuple, but only for nodes that are instrumented.

Results

Figure 3. Left: overhead of EXPLAIN (ANALYZE, TIMING OFF) over the plain SELECT of the same build. Right: change of the plain SELECT against unpatched PostgreSQL.

Output of analyze.py (PostgreSQL 20devel, commit 9ebc9a458c3, Apple M1, 3 rounds; the order of the builds is rotated in every round):

==== pgsql-pg20 (base: 9ebc9a458c) ====
	Duration[s] (var. [s^2]) 	Overhead[%]	vs. original Query1[%]
---------------------------------------------------------------------
**** original:
Query1	121.4873 	(0.4225)	N/A	0.00
Query2	151.9161 	(0.6283)	25.05	25.05
**** lite-rowcount:
Query1	121.2020 	(0.4064)	N/A	-0.23
Query2	129.2084 	(0.4697)	6.61	6.36

Per round (Query1 / Query2 [s], Overhead[%]):
  original        121.70/152.20 (25.06)  121.92/152.48 (25.06)  120.84/151.07 (25.02)
  lite-rowcount   121.76/129.82 (6.62)   121.24/129.26 (6.61)   120.61/128.55 (6.59)

Query-1 is the plain SELECT; Query-2 is the same query under EXPLAIN (ANALYZE, TIMING OFF). Overhead is Query-2 / Query-1 − 1 of the same build; the last column divides by the Query-1 of the original build instead.

  • Plain SELECT: 121.20 sec against 121.49 sec (−0.23%). With a variance of about 0.4 sec² (a standard deviation of about 0.65 sec), this is within the noise: no overhead can be detected.
  • EXPLAIN ANALYZE: the overhead drops from 25.05% to 6.61%. The time added by instrumentation falls from 30.4 sec to 8.0 sec. The three rounds agree closely (6.59% to 6.62%), so the result is stable.

Correctness. lite-rowcount passes make check with assertions enabled (243 tests). I also compared the rows= and loops= of every plan node with unpatched PostgreSQL for queries covering rescans, LIMIT, semi/anti joins, SubPlans, bitmap scans, hash and merge joins, Memoize, recursive CTEs, partitioned DML, parallel query and TIMING ON. All were identical.

Discussion

The remaining 6.6% is the price of leaving the executor nodes and the inline ExecProcNode() untouched. In return, the patch has no effect on queries that do not use EXPLAIN ANALYZE.

Open points:

  • Reading the counter during execution. For progress monitoring, the row counts have to be read while the query runs. instr_rows is folded into NodeInstrumentation only at the end of a loop, so code that reads tuplecount earlier needs an accessor or a call to ExecInstrEndLoop(). This is the next step.
  • Worst-case benchmark. The nodes of the benchmark query do almost nothing per tuple, so per-tuple overhead is as visible as it can be. Typical queries should show a smaller relative overhead.
  • Architecture. I measured on arm64 only. x86-64 results are still to be measured.

For reference, SQL Server has collected per-operator row counts by default since SQL Server 2019 (lightweight query profiling). Always-on counting in PostgreSQL would need an overhead lower than 6.6%.

Conclusion

lite-rowcount reduces the overhead of EXPLAIN (ANALYZE, TIMING OFF) from 25.05% to 6.61%, with no measurable cost for a plain SELECT and without modifying any ExecXXX() function.

Appendix A: feather-rowcount

A.1 Idea

In the previous post, the fastest method (Phase 3) counted rows inside every ExecXXX() function. I tried to improve it with a second patch, feather-rowcount.

Apart from ExecProcNodeFirst(), a parent node gets tuples from its child only through the inline ExecProcNode(). So instead of counting in the callee (every ExecXXX()), we can count once in the caller:

Figure A.1. Phase 3 counts in the callee and must modify every ExecXXX(). feather-rowcount counts once, in the caller.

Figure A.2. Execution paths including feather-rowcount (d): no wrapper, one call per tuple.

ExecProcNodeFirst() sets node->ExecProcNode to the real function, as when there is no instrumentation, and the counting is done in the inline ExecProcNode() right after the call returns. The packed counter and ExecInstrEndLoop() are the same as in lite-rowcount.

static inline TupleTableSlot *
ExecProcNode(PlanState *node)
{
	TupleTableSlot *result;

	if (node->chgParam != NULL) /* something changed? */
		ExecReScan(node);		/* let ReScan handle this */

	result = node->ExecProcNode(node);

	/*
	 * Row-count-only instrumentation (see ExecProcNodeFirst).  Doing it here,
	 * on the caller's side, avoids both a wrapper function call per tuple and
	 * any knowledge of instrumentation in the individual ExecXXX functions.
	 */
	if (unlikely(node->instr_rows != 0))
		node->instr_rows = (node->instr_rows | INSTR_ROWS_RUNNING) +
			(TupIsNull(result) ? 0 : 1);

	return result;
}

instr_rows == 0 means “not instrumented”, so the flag test and the load of the counter are one instruction.

This is what Apple clang generates for arm64 (-O3) where ExecMaterial() fetches a tuple from its child (comments added, labels simplified). Two instructions are added to the normal path; the counting itself is moved out of line by unlikely():

	ldr	x8, [x23, #0x18]               ; node->ExecProcNode
	mov	x0, x23
	blr	x8                             ; call child's ExecXXX()
	mov	x22, x0
	ldr	x8, [x23, #0x28]               ; + load node->instr_rows
	cbnz	x8, .Lcount                    ; + instrumented?  -> out of line
.Lcheck:
	cbz	x22, .Ldone                    ;   (TupIsNull, as before)
	ldrh	w8, [x22, #0x4]
	tbnz	w8, #0x1, .Ldone
	...

.Lcount:                                       ; only when instrumented
	orr	x8, x8, #0x4000000000000000    ; | INSTR_ROWS_RUNNING
	cbz	x22, .Lnull
	ldrh	w9, [x22, #0x4]
	tst	w9, #0x2
	cset	w9, eq                         ; !TTS_EMPTY(slot)
	b	.Ladd
.Lnull:
	mov	x9, #0x0
.Ladd:
	add	x8, x9, x8
	str	x8, [x23, #0x28]               ; store node->instr_rows
	cbnz	x22, .Lcheck                   ; back to the normal path

Without instrumentation, the added ldr and cbnz run and the cbnz is not taken; no register is spilled and no stack frame is added. With instrumentation, 11 instructions are added and the path takes three branches (cbnz out, b, cbnz back). The same sequence appears at every call site of ExecProcNode().

Pros: no wrapper call; the patch is confined to one inline function and the common part.

Cons: the check runs even without EXPLAIN ANALYZE, and it is inlined at every call site of ExecProcNode() (29 of the 43 node*.c files), which slightly increases code size. Like Phase 3, it therefore costs a little for plain SELECT statements.

A.2 Results

Figure A.3. The same benchmark with feather-rowcount added.

**** feather-rowcount:
Query1	122.4316 	(0.2873)	N/A	0.78
Query2	124.5980 	(0.3341)	1.77	2.56

Per round (Query1 / Query2 [s], Overhead[%]):
  feather-rowcount  122.55/124.84 (1.87)  122.42/124.52 (1.71)  122.32/124.43 (1.73)

(The original and lite-rowcount rows are the same as in the Results section.) feather-rowcount reduces the overhead to 1.77%, but a plain SELECT is 0.78% slower than the original in all three rounds, so this is not noise.

Appendix B: Benchmark

B.1 Environment

  • Hardware: Apple Silicon MacBook Pro M1
  • OS: macOS 15.5
  • Compiler: Apple clang version 17.0.0 (clang-1700.0.13.5)
  • PostgreSQL: 20devel (commit 9ebc9a458c3), built with ./configure --without-icu CFLAGS="-O3 -g"

custom_settings.conf:

shared_buffers = 512MB
max_parallel_workers_per_gather = 0
max_parallel_workers = 0
parallel_leader_participation = off

B.2 Dataset

CREATE TABLE test1 (id int, data int);
CREATE INDEX test1_id_idx ON test1 (id);
CREATE TABLE test2 (id int PRIMARY KEY, data int);
CREATE TABLE test3 (id int PRIMARY KEY, data int);
INSERT INTO test1 (id, data) SELECT i, i % 51  FROM generate_series(1, 150000) AS i;
INSERT INTO test1 (id, data) SELECT i, i % 51 FROM generate_series(1, 5000) AS i;
INSERT INTO test2 (id, data) SELECT i, floor(random() * 50 + 1)::int FROM generate_series(1, 50000) AS i;
INSERT INTO test3 (id, data) SELECT i, i FROM generate_series(1, 100000) AS i;

B.3 Queries

  • Query-1: SELECT count(*) FROM test1 AS a, test2 AS b, test3 AS c WHERE a.id = c.id;
  • Query-2: EXPLAIN (ANALYZE TRUE, TIMING FALSE, BUFFERS FALSE) SELECT count(*) FROM test1 AS a, test2 AS b, test3 AS c WHERE a.id = c.id;

Each query is run 10 times after a warm-up run, in 3 rounds. All builds use the same data directory, and the order of the builds is rotated in every round, so that no build is always measured first or last.

B.4 How to reproduce

$ git clone https://github.com/s-hironobu/fast_explain_analyze.git
$ cd fast_explain_analyze
$ bash ./bench.sh setup
$ bash ./bench.sh benchmark          # original, lite-rowcount
$ bash ./bench.sh benchmark all      # + feather-rowcount (experimental)
$ python3 ./analyze.py