Skip to content

perf(postgresql): read rows in libpq chunks instead of one result per row #4547

Done

Description

@datlechin

Problem

Every PostgreSQL read the user sees runs in libpq's single-row mode, so libpq builds and frees a whole PGresult for each row. On the same Mac and data, the full 1M-row trips_1m query took 1.46-1.51 s on PostgreSQL and 1.06-1.07 s on MySQL (results/research/tablepro-query-*-trips_1m-full.json, 3 runs). How much of that gap is the per-row result is not measured yet.

The cost grows with columns. In partial-result mode with a chunk size of 1, libpq copies the column descriptors and names into a new PGresult for every row: about 1 KB per row at 20 columns and 12-16 KB per row at 250 columns (wide_250), often more than the row's own data. Estimated 0.3-0.6 µs per row at 20 columns, not measured.

Cause

  • Seven read loops call PQsetSingleRowMode and handle PGRES_SINGLE_TUPLE, each on its own, in apple/Plugins/PostgreSQLDriverPlugin/LibPQPluginConnection.swift: boundedQuerySync (:1334), cappedCursorRead (:1528), streamResults for export, copy and compare (:1803), boundedReadSync (:2150), fetchCursorBatch (:2297), singleRowReadSync for table pages and Fetch All (:2377) and readsRowByRow (:2655).
  • Each loop makes one PQgetResult, PQresultStatus, decode and PQclear per row (singleRowReadSync, :2387-2405), decoding row 0 through singleRow (apple/Plugins/PostgreSQLDriverPlugin/LibPQPluginConnection+ResultReading.swift:96-101), and takes the PluginQueryCancellationGate NSLock once per row (apple/Plugins/TableProPluginKit/PluginQueryCancellationGate.swift:35-39).
  • The bundled libpq is 17.4 (apple/scripts/build-libpq.sh:27) and has PQsetChunkedRowsMode and PGRES_TUPLES_CHUNK (apple/Plugins/PostgreSQLDriverPlugin/CLibPQ/include/libpq-fe.h:50-51, :133, :512). Nothing in apple/ uses them.

Change

  • Fold the seven loops into one shared row reader first, so the change lands and is tested once. The header check carriesRowDescription (LibPQPluginConnection.swift:1761-1763) moves with it.
  • In that reader, call PQsetChunkedRowsMode(conn, n) after the send, the documented libpq 17 API, and decode rows 0..<PQntuples from each PGRES_TUPLES_CHUNK. Read column OIDs and metadata once from the first chunk, as today.
  • Choose n adaptively: start at 1 and grow (for example 1, 16, then up to about 1 MiB of row data per chunk), so first-row latency and Stop stay as they are for a slow query. A fixed chunk would hold back the first rows of a nested loop or a per-row function until n rows exist.
  • Check cancel and abort once per chunk. Keep the row-cap and byte-limit stops: stop mid-chunk, then run the existing cancelAndDrain or finishPendingResults.
  • Fall back to single-row mode when PQsetChunkedRowsMode returns 0. Test PGlite and the other PostgreSQL-compatible engines that use the same libpq.
  • The per-row timing label becomes time to first chunk; rename it to say so.

Measure

  • trips_1m and wide_250 on the bench fixtures: Time Profiler time under PQcopyResult, pqResultAlloc, malloc, free, PQclear and PQgetResult, before and after.
  • Count PQcopyResult calls during the fetch with dtrace: about 1M today for trips_1m, about 1M / n after.
  • Wall time of the full 1M-row query, 3 runs, and time to first row for SELECT pg_sleep(0.01), g FROM generate_series(1, 200) g (it must not get slower).

Part of the performance plan.

Activity

  1. added
    enhancement
    platform-macos
    on Nov 25, 2026
  2. datlechin commented on Nov 25, 2026

    @datlechin
    MemberAuthor

    #4566 ships the macOS part: every read in LibPQPluginConnection takes its rows in chunks of 8 through PQsetChunkedRowsMode, with single-row mode as the fallback and for reads with a byte limit. Client CPU for 1M rows x 20 columns drops from 1.35-1.64 s to 0.90-0.93 s.

    What is left:

    • Growing the chunk size during a result cannot be done with libpq 17: the size is set once per query, right after the send, and libpq hands a chunk over only when it is full or the result ends. The gain flattens at 8 rows (16, 256 and 1,024 measured no better), and the server buffers its own output, so a slow query's first rows came no later with chunks (pg_sleep(0.01) x 200: 2.158 s single-row, 2.184 s at 16).
    • Byte-limited reads (boundedReadSync and the cursor fetches with a byte budget) stay in single-row mode, since a chunk holds every raw row of it before the budget can stop the read.
    • The iOS PostgreSQLDriver (apple/TableProMobile/TableProMobile/Drivers/PostgreSQLDriver.swift, around :900 and :1006-1075) still calls PQsetSingleRowMode. Its stream has its own read-ahead, so it needs its own change and tests on the iOS target.
    • The full fold of the seven loops' status handling into one reader: they now share the row-mode entry, the row test and the decoder, but each keeps its own stop, drain and savepoint rules, which differ.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementplatform-macos

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions