Skip to content

[BUG]: SELECT COUNT(*) hangs indefinitely on large tables due to parallel query planner choosing a Gather node #945

Closed

Description

@damassima

Description

When running SELECT COUNT(*) on a table with a large number of rows, the query hangs indefinitely and never returns.

The root cause is that PostgreSQL's query planner selects a parallel sequential scan plan including a Gather node. However, since PGlite runs Postgres in WASM as a single process and cannot fork worker processes, the Gather node waits for workers that can never be started — causing the query to hang.

Note: Because PGlite's WASM runtime blocks the JavaScript event loop during query execution, Promise.race / setTimeout-based timeouts cannot interrupt the hang. The process must be killed manually (e.g. Ctrl+C).

Steps to reproduce

Setup

npm init -y
npm install @electric-sql/pglite

1_hang.mjs — reproduces the hang (stop with Ctrl+C)

import { PGlite } from "@electric-sql/pglite";

const ROWS = 200_000;

const db = new PGlite();
console.log(`Inserting ${ROWS.toLocaleString()} rows...`);
await db.exec(`
  CREATE TABLE t (id SERIAL PRIMARY KEY, val TEXT);
  INSERT INTO t (val)
    SELECT md5(i::text) FROM generate_series(1, ${ROWS}) AS i;
`);

const plan = await db.query("EXPLAIN SELECT COUNT(*) FROM t");
console.log("\nEXPLAIN SELECT COUNT(*) FROM t:");
plan.rows.forEach(r => console.log(" ", r["QUERY PLAN"]));

const hasGather = plan.rows.some(r => r["QUERY PLAN"].includes("Gather"));
if (!hasGather) {
  console.log("\n⚠️  No Gather node found. Try increasing ROWS (e.g. 500_000).");
  process.exit(0);
}

console.log("\nRunning COUNT(*) ...  (hangs here — press Ctrl+C to stop)");
const result = await db.query("SELECT COUNT(*) FROM t");
console.log("count =", result.rows[0].count); // should not reach here
node 1_hang.mjs

2_explain.mjs — confirms Gather node is present in the plan

import { PGlite } from "@electric-sql/pglite";

const ROWS = 200_000;

const db = new PGlite();
await db.exec(`
  CREATE TABLE t (id SERIAL PRIMARY KEY, val TEXT);
  INSERT INTO t (val)
    SELECT md5(i::text) FROM generate_series(1, ${ROWS}) AS i;
`);

const settings = await db.query(`
  SELECT name, setting FROM pg_settings
  WHERE name IN (
    'max_parallel_workers_per_gather',
    'max_parallel_workers',
    'max_worker_processes'
  )
  ORDER BY name;
`);
console.log("Parallel settings:");
for (const { name, setting } of settings.rows)
  console.log(`  ${name} = ${setting}`);

const e1 = await db.query("EXPLAIN SELECT COUNT(*) FROM t");
console.log("\nEXPLAIN SELECT COUNT(*) FROM t:");
e1.rows.forEach(r => console.log(" ", r["QUERY PLAN"]));

const e2 = await db.query(
  `EXPLAIN SELECT COUNT(*) FROM (SELECT * FROM t LIMIT ${ROWS}) sub`
);
console.log(`\nEXPLAIN with LIMIT subquery:`);
e2.rows.forEach(r => console.log(" ", r["QUERY PLAN"]));

await db.close();
node 2_explain.mjs

Expected behavior

SELECT COUNT(*) FROM t returns the row count promptly.

Actual behavior

1_hang.mjs: the process hangs indefinitely at Running COUNT(*) ... and must be killed manually.

2_explain.mjs output (the Gather node is present in the direct COUNT(*) plan, but absent when LIMIT is used):

Inserting 200,000 rows...

Parallel settings:
  max_parallel_workers = 8
  max_parallel_workers_per_gather = 2
  max_worker_processes = 8

EXPLAIN SELECT COUNT(*) FROM t:
  Finalize Aggregate  (cost=4223.80..4223.81 rows=1 width=8)
    ->  Gather  (cost=4223.68..4223.79 rows=1 width=8)
          Workers Planned: 1
          ->  Partial Aggregate  (cost=3223.68..3223.69 rows=1 width=8)
                ->  Parallel Seq Scan on t  (cost=0.00..2912.35 rows=124535 width=0)
  → Gather node: true

EXPLAIN SELECT COUNT(*) FROM (SELECT * FROM t LIMIT 200000) sub:
  Aggregate  (cost=6074.80..6074.81 rows=1 width=8)
    ->  Limit  (cost=0.00..3574.80 rows=200000 width=36)
          ->  Seq Scan on t  (cost=0.00..3784.09 rows=211709 width=36)
  → Gather node: false

Analysis

  • The planner selects a parallel plan (Gather node) because max_parallel_workers_per_gather defaults to 2.
  • At execution time, the Gather node tries to launch background worker processes, but PGlite cannot fork processes in its WASM environment — so the workers never start and the query hangs.
  • When LIMIT is present in a subquery, the planner suppresses the parallel plan (no Gather node), so the query completes normally.
  • The PostgreSQL docs note that in single-user mode parallel plans should not be generated. However, PGlite appears to still generate them despite running as a single process, suggesting the planner is not correctly detecting the single-user/no-fork constraint.

Workaround

Set max_parallel_workers_per_gather = 0 after initializing the database:

const db = new PGlite();
await db.exec("SET max_parallel_workers_per_gather = 0;");

This forces the planner to use a serial sequential scan and the query returns immediately.

What versions are running?

  • @electric-sql/pglite: latest (0.4.2)
  • Node.js: v24.1.0
  • Memory: 16GB
  • CPU: Apple M2 Pro
  • OS: macOS 15.6

Activity

  1. added
    bug
    on Mar 28, 2026
  2. tdrz commented on Mar 28, 2026

    @tdrz
    Contributor

    I think you can also play with the startParams passed to PGlite - documentation of these needs to be done.

  3. self-assigned this
    on Mar 28, 2026
  4. damassima commented on Mar 28, 2026

    @damassima
    Author

    Thanks for the tip! I confirmed that the following initialization also works as a workaround:

    const db = await PGlite.create({
      startParams: [
        ...PGlite.defaultStartParams,
        "-c", "max_parallel_workers_per_gather=0"
      ]
    });
  5. tdrz commented on Mar 28, 2026

    @tdrz
    Contributor

    I'll look into the other worker params and push a fix.

  6. tdrz commented on Mar 28, 2026

    @tdrz
    Contributor

    @AntonOfTheWoods may be of interest for you?

  7. tdrz commented on Mar 29, 2026

    @tdrz
    Contributor

    I'll look into the other worker params and push a fix.

    Note to myself: maybe even better add an exception whenever we reach the code that creates a new worker. Only then disable the usage of workers.

  8. AntonOfTheWoods commented on Mar 30, 2026

    @AntonOfTheWoods
    Contributor

    Unfortunately @tdrz , @electric-sql/pglite@0.4.2 still just hangs for me with the following:

      const pg = await PGlite.create({
        extensions: {
          sync: electricSync(),
        },
        startParams: [...PGlite.defaultStartParams, "-c", "max_parallel_workers_per_gather=0"],
      });
      await pg.exec("SET max_parallel_workers_per_gather = 0;");  // the more the merrier?

    But it still hangs hard on a CREATE INDEX on a large table.

  9. tdrz commented on Mar 30, 2026

    @tdrz
    Contributor

    But it still hangs hard on a CREATE INDEX on a large table.

    @AntonOfTheWoods
    Thank for trying it out, sorry to hear it didn't help.

    You said this was working on 0.3.x, right?

  10. AntonOfTheWoods commented on Mar 30, 2026

    @AntonOfTheWoods
    Contributor

    You said this was working on 0.3.x, right?

    It takes a pretty absurd amount of memory (3-4GB) but yes, and it's relatively quick.

  11. damassima commented on Mar 30, 2026

    @damassima
    Author

    Additional note: I confirmed that this issue does not reproduce on @electric-sql/pglite@0.3.16 — no Gather node appears in the plan there.

  12. tdrz commented on Mar 30, 2026

    @tdrz
    Contributor

    Additional note: I confirmed that this issue does not reproduce on @electric-sql/pglite@0.3.16 — no Gather node appears in the plan there.

    Thanks! A fix is on its way.

  13. tdrz commented on Apr 2, 2026

    @tdrz
    Contributor

    Fixed in v0.4.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions