PostgreSQL Batch Ingestion Using UNNEST and Dapper
How vectorizing typed 1D arrays with PostgreSQL UNNEST avoids parameter-limit failures and eliminates dynamic query plan cache bloat in .NET.
Relational database ingestion bottlenecks in .NET rarely originate inside PostgreSQL itself; they typically arise from dynamic multi-row SQL string concatenation and parameter-count limits.
The Multi-Row Concatenation Anti-Pattern
When inserting thousands of items in a batch, naive code often builds dynamic parameterized SQL:
INSERT INTO items (id, name, price)VALUES (@p0, @p1, @p2), (@p3, @p4, @p5), ...;This pattern degrades predictability as batch sizes vary:
- Plan Cache Fragmentation: Every distinct batch length produces a distinct SQL text hash, forcing PostgreSQL to parse and plan each variant separately.
- Driver Parameter Ceiling: PostgreSQL’s wire protocol caps bound parameters per statement at
65,535. Large multi-column batches hit this ceiling and fail at runtime. - Managed String Allocation: Building large concatenated SQL strings and thousands of individual
DbParameterobjects creates avoidable Gen0/Gen1 heap churn in .NET.
The Vectorized UNNEST Pattern
PostgreSQL provides the set-returning UNNEST function, which expands parallel typed 1D arrays into relational rows inside a single static SQL statement. This pattern is implemented in EricksonLopez.DapperExtensions.PostgreSql (BulkExtensions and BulkParameters):
INSERT INTO items (id, name, price)SELECT u.id, u.name, u.priceFROM UNNEST(@Ids::uuid[], @Names::text[], @Prices::numeric[])AS u(id, name, price);Because the SQL text remains identical whether a batch contains 10 rows or 10,000 rows:
- PostgreSQL caches one constant execution plan for the statement.
- Only one parameter per column is bound (three parameters total above), staying well below the 65,535 protocol limit regardless of row count.
Npgsqltransmits contiguous typed arrays cleanly without dynamic SQL generation on every call.
Verification Transparency
While the UNNEST SQL generation and parameter binding patterns are verified directly in EricksonLopez.DapperExtensions.PostgreSql and EricksonLopez.Outbox.Storage.PostgreSql, the current BenchmarkDotNet.Artifacts workspace snapshot does not yet include a comparative EF Core vs. UNNEST benchmark run. Quantitative throughput tables will only be published once verified BenchmarkDotNet artifacts are committed.