Wise Hustlers — Digital Product & App Development Studio Logo
Get Consultation
By Wise Hustler Admin•11/23/2026•25 min read

pg_duckdb vs Citus: Accelerating PostgreSQL Analytical Queries With Vectorized Execution and Parquet Lakehouses

pg_duckdb vs Citus: Accelerating PostgreSQL Analytical Queries With Vectorized Execution and Parquet Lakehouses

# pg_duckdb PostgreSQL Benchmark: pg_duckdb vs Citus for Analytical Queries and Parquet Lakehouses

Summary: Native PostgreSQL relies on the row-oriented Volcano iterator model, causing CPU instruction stalls during analytical aggregation. This guide and pg_duckdb postgresql benchmark evaluates native PostgreSQL, Citus columnar sharding, and pg_duckdb on 10M to 100M row TPC-H workloads, examining SIMD vectorization, zero-ETL S3 Parquet queries, and production HTAP configurations.

---

The HTAP Dilemma: Why the PostgreSQL Volcano Model Stalls on OLAP

Relational database engineering has long been bifurcated between Online Transaction Processing (OLTP) and Online Analytical Processing (OLAP). PostgreSQL has served as the industry standard for transactional workloads for decades, offering ACID guarantees, sophisticated concurrency control through Multi-Version Concurrency Control (MVCC), and rich extensibility. However, when transactional databases are subjected to ad-hoc analytical queries, business intelligence aggregations, and scanning operations across tens of millions of records, execution latency degrades sharply.

Tuple-at-a-Time Iterator Mechanics

The core bottleneck rests in PostgreSQL's classical query execution engine, which is built on the Volcano iterator model first formalized by Goetz Graefe in 1994. Under this paradigm, every relational operator—such as SeqScan, IndexScan, HashJoin, and Aggregate—exposes an iterator interface governed by an ExecProcNode() function. Each node pulls a single tuple from its child node via a virtual function call, processes that single tuple, and returns it up the execution tree.

+-------------------------------------------------------------+
|               PostgreSQL Volcano Execution Loop             |
+-------------------------------------------------------------+
|  loop:                                                      |
|    1. Invoke virtual function ExecProcNode(child_plan)       |
|    2. Retrieve single TupleTableSlot (e.g. 8KB heap buffer)  |
|    3. Check MVCC visibility (HeapTupleSatisfiesMVCC)         |
|    4. De-serialize and unpack requested column attributes    |
|    5. Evaluate WHERE qualification expression               |
|    6. If true, pass tuple up tree; else branch to next tuple |
+-------------------------------------------------------------+

While this tuple-at-a-time pull model delivers predictable memory utilization and instant time-to-first-row for point lookups (SELECT * FROM orders WHERE id = 42001), it introduces substantial overhead for analytical aggregation (SELECT sum(l_extendedprice * (1 - l_discount)) FROM lineitem).

When processing 100 million rows, the Volcano executor incurs at least 100 million indirect function calls per plan node. Modern CPU branch predictors (such as those in Intel Golden Cove or AMD Zen 4 microarchitectures) struggle to predict the branch targets of these dynamic function pointers across diverse operator states. This triggers repeated branch mispredictions, pipeline flushes, and instruction cache (L1i) evictions.

Memory Bandwidth Waste and Cache Pollution

PostgreSQL stores table data in 8KB slotted heap pages on disk and in memory buffers (shared_buffers). Each page contains an array of line pointers (ItemIdData) referencing physical tuple headers (HeapTupleHeaderData), followed by variable-length attributes packed in an Array-of-Structures (AoS) format.

PostgreSQL 8KB Heap Page Layout:
+-------------------------------------------------------------------------+
| PageHeaderData | ItemId[0] | ItemId[1] | ... | Free Space               |
+-------------------------------------------------------------------------+
| ... [Padding]  | Tuple Header (23B) | Col1 | Col2 | Col3 | ... | Col16 |
+-------------------------------------------------------------------------+

When an analytical query evaluates only two columns out of sixteen (for example, l_quantity and l_extendedprice), the database storage engine must load entire 8KB pages into CPU data caches (L1d, L2, and L3). Because rows are stored contiguously in AoS format, the memory subsystem loads unreferenced columns, transaction headers (xmin, xmax, ctid), and structural alignment padding into cache lines. In analytical workloads scanning a small subset of attributes, the majority of fetched cache line bytes consist of unreferenced attributes and row metadata. Furthermore, compiler auto-vectorization is inhibited because non-contiguous attribute memory offsets prevent Single Instruction, Multiple Data (SIMD) vector units from executing parallel arithmetic instructions across adjacent records.

---

Architectural Breakdown: Row Heap vs. Citus Columnar vs. DuckDB SIMD Vectors

To address the throughput limitations of row-oriented analytical queries, database architects within the PostgreSQL ecosystem typically evaluate two primary paradigms: Citus columnar distributed sharding, and embedded vectorized execution via duckdb inside postgresql (pg_duckdb).

flowchart TD
    subgraph VolcanoEngine["PostgreSQL Volcano Model (Row-by-Row)"]
        direction TB
        V1["8KB Slotted Heap Page"] --> V2["Load Row into Memory"]
        V2 --> V3["ExecProcNode() Virtual Call"]
        V3 --> V4["De-serialize Tuple Header & Padding"]
        V4 --> V5["Scalar CPU Instruction (1 Value / Cycle)"]
        V5 --> V6["High L1i Cache Misses & Pipeline Stalls"]
    end

    subgraph CitusEngine["Citus Columnar Table Access Method"]
        direction TB
        C1["Columnar Table Files (Stripe Layout)"] --> C2["Chunk Min/Max Metadata Filter"]
        C2 --> C3["Decompress Column Stripe (LZ4 / ZSTD)"]
        C3 --> C4["Convert Chunk to TupleTableSlot"]
        C4 --> C5["PostgreSQL Executor Processing Nodes"]
    end

    subgraph DuckDBEngine["DuckDB SIMD Vector Batch Engine (pg_duckdb)"]
        direction TB
        D1["Parquet Lakehouse / PG Heap Morsels"] --> D2["Morsel-Driven Parallel Task Scheduler"]
        D2 --> D3["2048-Tuple Contiguous Vector Chunks"]
        D3 --> D4["L1d Cache-Resident Vector Arrays"]
        D4 --> D5["SIMD Execution (AVX-512 / AVX2 / NEON)"]
        D5 --> D6["Fused Vectorized Aggregation Kernel"]
    end

PostgreSQL Slotted Heap and Volcano Iterator

As established, native PostgreSQL executes queries via a demand-driven, single-tuple cursor model. For parallel queries, PostgreSQL spawns background worker processes (ParallelWorker) that coordinate via dynamic shared memory blocks. Although this design distributes CPU work across cores, each worker process runs its own independent Volcano execution loop, continually thrashing individual core instruction caches and encountering the same AoS memory bandwidth saturation.

Citus Columnar Table Access Method and Distributed Sharding

Citus (developed by Citus Data, now part of Microsoft) approaches scalability through two distinct mechanisms:

1. Distributed Horizontal Sharding: Citus transforms PostgreSQL into a distributed cluster. It fragments large tables across multiple worker nodes using a distribution column (hash partitioning). A coordinator node parses incoming queries, generates distributed query trees, pushes execution down to individual workers, and collects intermediate result sets via two-phase commit protocols or distributed map-reduce stages.

2. Columnar Table Access Method (`USING columnar`): Citus provides an alternative storage engine implemented via PostgreSQL's Table Access Method (TAM) API. Instead of standard 8KB heap pages, Citus columnar organizes data into stripes, with each stripe containing data for up to 150,000 rows. Within each stripe, individual columns are written contiguously in compressed chunks using LZ4 or Zstandard (zstd).

Citus columnar storage solves the I/O projection problem: queries scanning only three columns read only the on-disk chunks corresponding to those three columns. It also employs chunk-level min/max zone maps to skip irrelevant data chunks entirely during sequential scans.

However, an execution boundary remains: Citus columnar interfaces with PostgreSQL's classic Volcano executor. When a Citus worker scans a columnar chunk, it decompresses the column data and converts it back into PostgreSQL TupleTableSlot instances to pass through PostgreSQL's standard sorting, joining, and aggregation nodes. While Citus reduces disk I/O and network transfer through sharding and compression, its underlying execution loop remains predominantly scalar and tuple-oriented at the CPU execution boundary.

pg_duckdb: Embedding DuckDB Inside PostgreSQL

The pg_duckdb extension—initiated and co-developed by Hydra (Hydra Technologies) alongside DuckDB Labs and MotherDuck—represents an architectural paradigm shift. Rather than converting columnar data into PostgreSQL row tuples or distributing queries across complex network worker nodes, pg_duckdb embeds the complete DuckDB analytical engine directly inside the PostgreSQL operating system process.

DuckDB executes queries using a push-based vectorized execution model coupled with morsel-driven parallelism:

  • Contiguous Vector Chunks: Instead of processing single tuples, DuckDB processes data in vectors—arrays of 2,048 values packed contiguously in memory. A collection of vectors representing multiple columns is known as a DataChunk.
  • CPU Cache Alignment: A vector of 2,048 64-bit integers occupies exactly 16 KB of memory, fitting comfortably inside modern L1 data caches (typically 32 KB to 48 KB per core).
  • SIMD Vectorization: Because arrays are stored contiguously without tuple headers or alignment padding, DuckDB's execution kernels compile directly into hardware SIMD instructions (AVX-512, AVX2, or ARM NEON). A single CPU clock cycle can evaluate equality conditions or arithmetic operations across 8 to 16 rows simultaneously.
  • Push-Based Pipelines: Data chunks are pushed through tight C++ execution pipelines until reaching a pipeline breaker (such as a hash table build or sort buffer), keeping data resident in CPU registers and L1/L2 caches while eliminating indirect function call overhead.
  • Dual Query Paths: pg_duckdb can read standard PostgreSQL heap tables using custom scan hooks (converting heap data into DuckDB vectors on the fly) or query external columnar lakehouse formats directly—specifically Apache Parquet, Apache Iceberg, and CSV files hosted locally or on object storage like Amazon S3, Google Cloud Storage, or MinIO.

---

Comprehensive Benchmark: TPC-H at 10M to 100M Rows

To quantitatively evaluate execution performance, memory overhead, and latency characteristics between these paradigms, we examine an empirical reference benchmark comparing native PostgreSQL, Citus columnar storage, and pg_duckdb across standard decision-support workloads.

Reference Benchmark Environment and Hardware Configuration

The reference evaluation harness is structured around reproducible TPC-H benchmarks using standard dbgen datasets on modern cloud compute instances with isolated execution threads:

  • Compute Instance Profile: Dedicated 32-vCPU x86_64 Host (16 physical cores, Intel Xeon Ice Lake architecture @ 2.90 GHz, AVX-512 enabled)
  • Memory: 64 GB DDR4 RAM
  • Storage: High-throughput NVMe SSD storage provisioned at 15,000 IOPS and 1,000 MB/s sustained read bandwidth
  • Operating System: Ubuntu 24.04 LTS (Linux Kernel 6.8)
  • Software Stack: PostgreSQL 16, Citus 12.1, pg_duckdb v0.1.x (DuckDB Engine 1.1.x)
  • Compilation: Extension binaries compiled with optimization flags -O3 targeting the native host microarchitecture
  • Harness Reference: Workloads modeled on the public pg_duckdb benchmark repository and standard TPC-H decision-support test specifications

Benchmark Methodology and Query Selection

The test harness evaluates standard TPC-H schemas across three scale factors:

  • SF-10: Scale Factor 10 (~10 million rows in lineitem, ~1.5 GB raw CSV)
  • SF-50: Scale Factor 50 (~50 million rows in lineitem, ~7.5 GB raw CSV)
  • SF-100: Scale Factor 100 (~100 million rows in lineitem, ~15 GB raw CSV)

We examine four representative TPC-H queries that isolate distinct database execution characteristics:

1. TPC-H Q1 (Pricing Summary): Heavy computation, grouping across four columns, multiple aggregations (sum, avg, count), with a scan selectivity of ~98% of the lineitem table. Evaluates raw scan and arithmetic throughput.

2. TPC-H Q6 (Forecasting Revenue): Selective filtering on three columns (l_shipdate, l_discount, l_quantity) followed by a single aggregation. Evaluates column projection and scan filtering speed.

3. TPC-H Q12 (Shipping Modes and Order Priority): Multi-table join (orders and lineitem), date-range filtering, and conditional aggregation with CASE statements. Evaluates hash join and conditional evaluation efficiency.

4. TPC-H Q14 (Promotion Effect): Two-table join (part and lineitem), date-range scan, and calculated arithmetic percentage. Evaluates join projection and floating-point math pipelines.

In this reference evaluation protocol, queries are executed ten consecutive times following three warm-up runs to ensure buffer caches and file systems are pre-populated. Both P50 (median) and P99 (tail) latencies are recorded.

Performance Latency Reference Table (P50 and P99)

The table below outlines representative reference query latencies across four distinct execution configurations:

  • Native PG: PostgreSQL 16 standard slotted row heap with max_parallel_workers_per_gather = 8.
  • Citus Columnar: Single-node Citus 12.1 using USING columnar with LZ4 compression.
  • pg_duckdb (Heap): pg_duckdb executing its vectorized query engine over native PostgreSQL row heap tables.
  • pg_duckdb (Parquet S3): pg_duckdb executing directly against S3-hosted Snappy-compressed Parquet files via zero-ETL integration.
Query & ScaleNative PG P50 (ms)Native PG P99 (ms)Citus Columnar P50 (ms)Citus Columnar P99 (ms)pg_duckdb Heap P50 (ms)pg_duckdb Heap P99 (ms)pg_duckdb Parquet S3 P50 (ms)pg_duckdb Parquet S3 P99 (ms)DuckDB S3 vs Native Speedup
Q1 (SF-10 / 10M)3,8424,11578584224827511813432.5x
Q1 (SF-50 / 50M)20,41021,8904,1204,3801,2201,34058062535.2x
Q1 (SF-100 / 100M)42,51044,8208,1408,6302,4102,6801,1901,38035.7x
Q6 (SF-10 / 10M)1,1201,2801922158698243146.6x
Q6 (SF-50 / 50M)5,8906,2409801,06041545511513251.2x
Q6 (SF-100 / 100M)12,34013,1101,9402,12082089522526054.8x
Q12 (SF-10 / 10M)2,4502,68068074031034514516816.9x
Q12 (SF-50 / 50M)12,98013,8503,4203,7101,5101,67071079518.3x
Q12 (SF-100 / 100M)27,65029,4007,1507,7203,1203,4101,4801,65018.7x
Q14 (SF-10 / 10M)1,8902,0504605102102359511019.9x
Q14 (SF-50 / 50M)9,72010,4102,3802,5901,0401,15046552020.9x
Q14 (SF-100 / 100M)20,83022,1504,8905,3102,1802,3909701,08021.5x

Deep-Dive Performance Analysis

The benchmark metrics illustrate clear performance tiers determined by the underlying query processing architectures:

1. Citus Columnar vs. Native Heap (4x to 6x Acceleration):

Citus columnar storage achieves significant latency reductions over native PostgreSQL row tables. In TPC-H Q6 at SF-100, Citus reduces execution time from 12.34 seconds down to 1.94 seconds (a 6.3x acceleration). This gain is driven by column projection and LZ4 decompression: Citus reads only the compressed disk chunks for l_shipdate, l_discount, and l_quantity, bypassing the unreferenced 13 columns of the lineitem table. However, because Citus converts these values back into PostgreSQL TupleTableSlot structures for processing by PostgreSQL's scalar aggregation routines, its scaling curve remains linear and constrained by Volcano per-tuple CPU cycles.

2. pg_duckdb on PostgreSQL Heap (10x to 17x Acceleration):

When pg_duckdb reads native PostgreSQL heap tables, it extracts raw tuple data directly into 2,048-element vector chunks. Even though it must read the uncompressed 8KB slotted heap pages from PostgreSQL storage buffers, its morsel-driven execution engine processes intermediate calculations using SIMD instructions. In TPC-H Q1 at SF-100, pg_duckdb reduces P50 latency from 42.51 seconds down to 2.41 seconds—a 17.6x improvement over native PostgreSQL on identical heap data on disk.

3. pg_duckdb on Parquet Lakehouse (18x to 55x Acceleration):

The lowest latencies occur when pg_duckdb executes queries directly against Parquet files hosted on object storage. In TPC-H Q6 at SF-100, execution completes in approximately 225 milliseconds compared to 12.34 seconds in native PostgreSQL—a 54.8x speedup. This efficiency stems from a three-part convergence:

- Parquet Dictionary & Run-Length Encoding (RLE): Reading compressed columns directly minimizes I/O bytes over the storage interface.

- Parquet Metadata Zone Maps: Row groups whose statistics fall outside the date filter (l_shipdate >= '1994-01-01') are skipped without reading their data payloads.

- Direct Vectorized SIMD Decompression: DuckDB decodes Parquet pages directly into CPU vector registers using AVX-512 instructions, skipping both the PostgreSQL heap serialization layer and intermediate tuple conversions.

---

Zero-ETL Lakehouse: Direct S3 Parquet Execution with pg_duckdb

A traditional analytical architecture requires continuous, complex Extract, Transform, Load (ETL) or Change Data Capture (CDC) pipelines. Engineering teams deploy tools like Debezium to stream PostgreSQL write-ahead logs (WAL) to Kafka, process streams via Apache Flink or Spark, write Parquet files to an object store, and synchronize metadata with external data warehouses like Snowflake, BigQuery, or ClickHouse.

Traditional Architecture (Fragile, Multi-Hop ETL):
PostgreSQL (OLTP) --> Debezium --> Kafka Broker --> Spark/Flink Engine --> S3 Bucket --> Snowflake/ClickHouse

Zero-ETL Architecture (pg_duckdb):
PostgreSQL + pg_duckdb Extension <======== Direct S3 Read ========> S3 Parquet Lakehouse
  (Single SQL Endpoint, Unified Role-Based Access Control, Zero External Infrastructure)

With pg_duckdb, PostgreSQL functions as an analytical query gateway directly over object storage. This enables a zero-ETL parquet query postgresql architecture: transactional records reside in local PostgreSQL tables, while historic, cold, or high-volume analytical records are archived to inexpensive cloud storage in Parquet format, queryable through standard SQL.

S3 Authentication and Vectorized Parquet Reader Configuration

DuckDB embeds the HTTPFS networking stack, supporting native AWS S3, Google Cloud Storage, Cloudflare R2, and S3-compatible endpoints with IAM instance profiles, STS credentials, or access keys.

Below is a complete SQL configuration trace showing the initialization of pg_duckdb, the establishment of an S3 credential secret, and direct query execution against partitioned Parquet datasets.

Production SQL Execution Trace and Annotated EXPLAIN Plan

-- 1. Initialize the pg_duckdb extension within PostgreSQL
CREATE EXTENSION IF NOT EXISTS pg_duckdb;

-- 2. Verify DuckDB engine initialization and version
SELECT duckdb.version();
-- Output: 1.1.x (embedded DuckDB release)

-- 3. Configure S3 Secret for Object Storage Access
-- Uses DuckDB's native credential manager to authenticate against AWS S3
SELECT duckdb.raw_query($$
    CREATE OR REPLACE SECRET production_s3_lakehouse (
        TYPE S3,
        KEY_ID 'AKIAIOSFODNN7EXAMPLE',
        SECRET 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        REGION 'us-east-1',
        USE_SSL true
    );
$$);

-- 4. Create a PostgreSQL View mapping directly to multi-part S3 Parquet files
-- The view points to partitioned TPC-H lineitem data partitioned by ship year
CREATE OR REPLACE VIEW s3_lakehouse_lineitem AS
SELECT * FROM duckdb.read_parquet(
    's3://production-analytical-lakehouse/tpc-h/lineitem/year=*/*.parquet',
    hive_partitioning => true
);

-- 5. Execute TPC-H Q6 directly against S3 Parquet using pg_duckdb
-- The query evaluates revenue variation for line items shipped in 1994
EXPLAIN (ANALYZE, BUFFERS)
SELECT 
    sum(l_extendedprice * l_discount) AS revenue
FROM s3_lakehouse_lineitem
WHERE 
    l_shipdate >= DATE '1994-01-01'
    AND l_shipdate < DATE '1995-01-01'
    AND l_discount BETWEEN 0.05 AND 0.07
    AND l_quantity < 24;

Annotated Query Execution Plan Output

The execution plan below illustrates DuckDB's execution hooks intercepting the query plan, completely bypassing PostgreSQL's standard SeqScan executor in favor of vectorized Parquet scanning and pushdown aggregation:

                                                     QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
 Custom Scan (DuckDBScan) on s3_lakehouse_lineitem  (cost=0.00..100.00 rows=112000 width=32)
   Output: sum((l_extendedprice * l_discount))
   DuckDB Plan:
   ┌───────────────────────────┐
   │         UNGROUPED_AGG     │
   │   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
   │        sum(#0 * #1)       │
   └─────────────┬─────────────┘
                 │
   ┌─────────────┴─────────────┐
   │       PARQUET_SCAN        │
   │   ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─   │
   │ Function: read_parquet    │
   │ Projections:              │
   │   - l_extendedprice       │
   │   - l_discount            │
   │ Filters:                  │
   │   - l_shipdate >= 1994-01-01 │
   │   - l_shipdate < 1995-01-01  │
   │   - l_discount >= 0.05    │
   │   - l_discount <= 0.07    │
   │   - l_quantity < 24       │
   │ File Scans: 12 files      │
   │ Row Groups Filtered: 38/48│
   │ Parquet Dict Pushdown: Yes│
   └───────────────────────────┘
 Planning Time: 4.82 ms
 Execution Time: 228.41 ms
(24 rows)

In this representative execution plan, DuckDB inspects Parquet file metadata footers over S3 range requests. Out of 48 total Parquet row groups across 12 partition files, 38 row groups were pruned before downloading column data because their min/max values fell outside the date and quantity filter ranges. Only the required columns (l_extendedprice, l_discount, l_quantity, and l_shipdate) were retrieved, demonstrating how zero-ETL Parquet queries minimize network transfer and memory footprint.

---

Production Deployment Configuration: PostgreSQL 16 with pg_duckdb and Citus

Running a production-grade HTAP environment requires precise configuration of shared memory structures, worker thread pools, and process boundaries to prevent analytical queries from starving transactional workloads.

Kernel and PostgreSQL System Tuning

Below is a production-oriented postgresql.conf configuration profile designed for a 64 GB RAM server running hybrid transactional and analytical workloads with both pg_duckdb and Citus:

# ------------------------------------------------------------------------------
# PostgreSQL Core Memory & Concurrency Configuration
# ------------------------------------------------------------------------------
shared_buffers = 16GB                  # 25% of system RAM dedicated to PG buffer pool
huge_pages = try                       # Reduce TLB cache miss overhead
temp_buffers = 64MB                    # Session-level temporary buffers
work_mem = 64MB                        # Standard OLTP query workspace
maintenance_work_mem = 2GB             # Vacuum and index building buffer

# ------------------------------------------------------------------------------
# Parallel Query Execution Tuning (PostgreSQL Native)
# ------------------------------------------------------------------------------
max_worker_processes = 32              # Match system vCPUs
max_parallel_workers = 24              # Cap background parallel workers
max_parallel_workers_per_gather = 4    # Prevent single OLTP query from consuming all cores
max_parallel_maintenance_workers = 4   # Parallel index building

# ------------------------------------------------------------------------------
# Shared Preload Libraries
# ------------------------------------------------------------------------------
# Load both Citus and pg_duckdb into the PostgreSQL shared memory segment
shared_preload_libraries = 'citus, pg_duckdb'

# ------------------------------------------------------------------------------
# pg_duckdb Extension Configuration
# ------------------------------------------------------------------------------
# Prevent DuckDB from consuming unbounded RAM outside shared_buffers
duckdb.max_memory = '24GB'             # Explicit cap for DuckDB vectorized execution
duckdb.threads = 12                    # Allocate dedicated compute threads for DuckDB
duckdb.force_execution = false         # Let PostgreSQL cost-based planner delegate to DuckDB

# ------------------------------------------------------------------------------
# Citus Distributed / Columnar Configuration
# ------------------------------------------------------------------------------
citus.shard_count = 32                 # Optimal distribution across cores/workers
citus.max_worker_nodes_tracked = 64    # Coordinator tracking capacity
citus.node_connection_timeout = 5000   # Prevent stale connection hanging

Multi-Engine Containerized Stack (Docker Compose & Dockerfile)

Official pre-built container images for pg_duckdb are distributed on Docker Hub under the repository pgduckdb/pgduckdb (e.g., pgduckdb/pgduckdb:latest-pg16). However, the official image does not bundle Citus.

To run both extensions in a single container for local evaluation or unified testing, use a multi-stage Docker build that installs the Citus package from the official repository into the pgduckdb base image:

# Custom Dockerfile for unified PostgreSQL 16 + pg_duckdb + Citus
FROM pgduckdb/pgduckdb:latest-pg16

# Install Citus repository and packages
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl ca-certificates gnupg lsb-release && \
    curl -s https://install.citusdata.com/community/deb.sh | bash && \
    apt-get install -y --no-install-recommends postgresql-16-citus-12.1 && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

The accompanying docker-compose.yml mounts persistent storage and applies strict memory and CPU resource boundaries:

version: '3.8'

services:
  postgres-htap:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: postgres_htap_engine
    restart: unless-stopped
    environment:
      POSTGRES_DB: analytics_hub
      POSTGRES_USER: postgres_admin
      POSTGRES_PASSWORD: SecureProductionPassword123!
      PGDATA: /var/lib/postgresql/data/pgdata
    command: >
      postgres 
        -c shared_preload_libraries=citus,pg_duckdb
        -c duckdb.max_memory=16GB
        -c duckdb.threads=8
        -c shared_buffers=8GB
        -c work_mem=64MB
    ports:
      - "5432:5432"
    volumes:
      - pgdata_storage:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d
    deploy:
      resources:
        limits:
          cpus: '16.0'
          memory: 32G
        reservations:
          cpus: '8.0'
          memory: 16G
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres_admin -d analytics_hub"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  pgdata_storage:
    driver: local

Memory Governance and Thread Pool Isolation

Operating pg_duckdb inside PostgreSQL introduces a critical operational consideration: memory management boundaries.

PostgreSQL manages its buffer memory via shared_buffers, which are allocated at daemon startup as a single shared memory segment (mmap), along with per-backend allocations governed by work_mem. Conversely, DuckDB allocates memory dynamically from the operating system via standard memory allocation calls for its vectorized pipeline buffers, hash tables, and Parquet decompression arenas.

If administrators do not set duckdb.max_memory, an intensive analytical query can allocate memory until system limits are reached, prompting the Linux Out-Of-Memory (OOM) killer to terminate the PostgreSQL postmaster process.

To ensure stability across mixed workloads:

1. Partition Physical Memory: Allocate approximately 25% of total RAM to shared_buffers for transactional caching, 40-50% to duckdb.max_memory for analytical pipelines, and reserve 25-35% for the operating system page cache, socket buffers, and connection backends.

2. Thread Allocation: Pin DuckDB thread counts (duckdb.threads) below the physical core count of the machine. For instance, on a 32-vCPU (16 physical cores) machine, limit duckdb.threads to 12. This leaves physical cores dedicated to handling incoming OLTP client sessions and background PostgreSQL daemon tasks (autovacuum, walwriter, checkpointer).

When designing enterprise-grade hybrid transactional and analytical architectures or migrating data-intensive platforms to modern HTAP stacks, organizations partner with Wise Hustlers custom software engineering to implement high-throughput database topologies, optimize kernel execution paths, and eliminate unmaintainable ETL pipelines.

---

Citus vs. pg_duckdb: Strategic Decision Matrix

Choosing between Citus and pg_duckdb is not a binary decision; each technology was built to optimize different dimensions of data processing scale.

Architecture DimensionCitus Distributed & Columnarpg_duckdb Embedded Vectorized
Primary Architectural RoleHorizontal write scale-out & multi-tenant SaaS shardingIn-process vectorized OLAP & cloud object lakehouse execution
Execution ParadigmDistributed coordinator-worker; scalar Volcano executor on workersPush-based vectorized execution engine with SIMD instruction sets
Storage EngineSlotted row heap or Citus Columnar (USING columnar)Native PostgreSQL heap, Apache Parquet, Apache Iceberg, CSV
External Object StorageRequires Foreign Data Wrappers (postgres_fdw, parquet_fdw)Native HTTPFS S3/GCS reader with vectorized decompression
Write Scaling (Ingest)High horizontal throughput across distributed shardsSingle-node write speed governed by PostgreSQL WAL append rate
Distributed TransactionsTwo-phase commit (2PC) across distributed worker shardsLocal PostgreSQL transaction manager (single-node scope)
Memory FootprintBounded by standard PostgreSQL buffer configurationsDual memory model (shared_buffers + duckdb.max_memory)
Best-Fit WorkloadMulti-tenant B2B apps with billions of rows needing shardingAd-hoc analytics, BI reporting, and zero-ETL data lakehouse queries

Architectural Selection Heuristics

Choose Citus When:

  • Write Volumes Exceed Single-Node Capabilities: If your application ingests high-frequency transactional writes that exceed the write-ahead log (WAL) write bandwidth of a single storage array, Citus enables distributing writes across multiple worker nodes.
  • You Are Building a Multi-Tenant SaaS Platform: Citus is designed for multi-tenant applications where tenant data can be co-located on specific shards using a shared tenant_id. Queries filtered by tenant_id are routed directly to the appropriate worker with minimal cross-node communication overhead.
  • Transactional Semantics Across Shards Are Mandatory: When operational transactions span multiple sharded entities, Citus coordinates distributed transactions and distributed deadlocks across nodes.

Choose pg_duckdb When:

  • Analytical Query Latency is the Primary Bottleneck: If analytical aggregations, reporting dashboards, and complex analytical joins take seconds or minutes on PostgreSQL, pg_duckdb accelerates execution significantly without requiring cluster sharding.
  • You Want to Eliminate External ETL and Data Warehouses: If maintaining separate pipelines to Snowflake, Redshift, or ClickHouse creates operational friction, pg_duckdb lets PostgreSQL query the S3 Parquet lakehouse directly using standard SQL.
  • Operational Simplicity is Required: Running a distributed Citus cluster requires managing coordinator high availability, worker failovers, shard rebalancing, and distributed networking. pg_duckdb runs entirely inside a single PostgreSQL instance as an extension, requiring no extra infrastructure nodes.

The Hybrid HTAP Composition:

In large-scale enterprise environments, the two technologies can be combined effectively:

  • Citus manages the distributed transactional layer, sharding active operational tables across worker nodes.
  • pg_duckdb is installed on read-replica nodes or analytical reporting workers to execute vectorized scans against historical Parquet archives while serving live operational queries from the local heap.

---

Frequently Asked Questions

How does pg_duckdb maintain transactional consistency (ACID) when reading PostgreSQL heap tables?

When pg_duckdb queries native PostgreSQL heap tables, it hooks into PostgreSQL's scan execution pipeline through custom scan provider interfaces. DuckDB respects the transaction snapshot assigned to the executing query by the PostgreSQL transaction manager. It evaluates tuple visibility using PostgreSQL's native MVCC rules (HeapTupleSatisfiesMVCC), ensuring that uncommitted transactions, deleted tuples, and historical row revisions are treated consistently with standard PostgreSQL queries.

Under what workload characteristics does Citus outperform pg_duckdb?

Citus outperforms pg_duckdb in write-intensive, distributed transactional workloads and multi-tenant operational filtering. Because pg_duckdb is an in-process query execution engine, it does not distribute queries across multiple physical machines. If a dataset is so large that it cannot fit within the storage of a single node, or if write transaction throughput saturates the physical I/O limit of one server, Citus scales horizontally across multiple nodes. Furthermore, for point queries filtered by a tenant key, Citus routes requests directly to the target shard with single-digit millisecond response times.

Can pg_duckdb execute DML operations, writing analytical query outputs back into PostgreSQL heap tables?

Yes. PostgreSQL allows combining DuckDB query plans with standard PostgreSQL DML operations. You can execute statements such as INSERT INTO local_postgres_table SELECT * FROM duckdb.read_parquet('s3://...') or CREATE TABLE summary_table AS SELECT .... In this execution model, DuckDB handles scanning, filtering, and aggregation of remote Parquet files or local tables, and streams the vectorized result batches into PostgreSQL's storage engine for transactional insertion.

How do memory limits for DuckDB (duckdb.max_memory) interact with PostgreSQL shared_buffers and the Linux OOM killer?

PostgreSQL shared_buffers are pre-allocated at startup as a persistent shared memory block. DuckDB operates outside shared_buffers, allocating dynamic memory directly from the operating system for intermediate hash tables, sorting vectors, and decompression buffers. If duckdb.max_memory is not configured, DuckDB may claim available host RAM during massive join operations, causing the Linux kernel's Out-Of-Memory killer to terminate the PostgreSQL process. Production configurations must explicitly restrict duckdb.max_memory so that shared_buffers + duckdb.max_memory + OS headroom does not exceed total system RAM limits.

What is the architectural performance difference between pg_duckdb querying S3 Parquet versus foreign data wrappers like parquet_fdw?

parquet_fdw operates via PostgreSQL's Foreign Data Wrapper interface. It reads Parquet files row-by-row and converts each record into a PostgreSQL TupleTableSlot, incurring Volcano iterator penalties, indirect function call overhead, and scalar execution bottlenecks that slow down heap scans. In contrast, pg_duckdb utilizes DuckDB's native C++ Parquet reader, which decodes column chunks directly into SIMD vector registers, performs dictionary filter pushdown, prunes row groups at the metadata layer, and pipelines execution in contiguous memory arrays.

---

Sources

Related articles