Skip to content

Chapter 17 — ETL, Lakehouse & Reverse ETL#

Act IV · Chapter 17 Month 6 · Tuesday 10:00 9 min readDifficulty 3 of 5

Zero-CSV ETL, Parquet archival, and Reverse ETL across PostgreSQL, Polars, and DuckDB.

__arrow_c_stream__ETL / EtLTReverse ETLDuckDB & Parquet
▶ Run it yourself · examples/144_arrow_duckdb_lakehouse.py
Month 6, Tuesday 10:00. The analytics team walks into the Lisbon office with DuckDB notebooks and a Parquet archive request.

Month 6, Tuesday 10:00. The analytics team walks into the Lisbon office with DuckDB notebooks and a Parquet archive request.

Duck: We need July's door scans in DuckDB for audit aggregations, a Parquet snapshot for long-term storage, and a clean way to push verified audit rows back into PostgreSQL!

Panda: Easy — build an ETL glue script! Export PostgreSQL to CSV, load CSV into DuckDB, export another CSV, and run a Python row-by-row INSERT loop for the write-back!

Ferris: Or pass one Apache Arrow C Stream pointer between PostgreSQL, Polars, and DuckDB. Zero CSV files, zero Python row loops.

Where pgdorm fits: ETL, ELT, EtLT, and Reverse ETL#

Most teams treat PostgreSQL as only an OLTP backend and bolt brittle CSV scripts or row-by-row loaders onto the side whenever data engineering enters the picture. Because pgdorm pairs a Rust PostgreSQL COPY BINARY engine with the Apache Arrow C Stream (__arrow_c_stream__) and 1-RTT pg_temp + MERGE pipelines, it covers all four modern data-movement paradigms natively:

Paradigm Flow How pgdorm runs it
ETL (Extract → Transform → Load) Clean, enrich, and type data in Polars or DuckDB first, then load into PostgreSQL. await pool.copy_from_arrow(Table, df) streams columnar Arrow buffers straight into PostgreSQL COPY BINARY with zero Python row objects.
ELT (Extract → Load → Transform) Land raw records into PostgreSQL first, then run relational joins, constraints, and upserts inside SQL. pipe.stage(TempStage, rows) + pg.merge(...) (Chapter 13) stages and merges inside PostgreSQL in 1 RTT.
EtLT (Extract → light transform → Load → heavy Transform) Do fast pre-load normalization (timestamps, decimals, bad-row filtering) in Python/Polars, load fast, and keep business-rule joins in PostgreSQL. Normalize in Polars (or filter malformed rows with on_error="ignore", Chapter 16), bulk-load via copy_from_arrow(), then transform with SQL MERGE / CTEs.
Reverse ETL (Analytics / Lakehouse → Operational PostgreSQL) Operationalize analytical outputs — audit rows, fraud flags, customer segments, pricing scores — from DuckDB / Parquet / Polars back into live OLTP tables. Pass a DuckDB relation or Polars DataFrame directly to pool.copy_from_arrow() for append-only write-back, or load into a pg_temp staging table and pg.merge() for transactional upserts.

In this chapter, Maya wires up a complete ETL + analytical extract + Parquet archive + Reverse ETL loop across PostgreSQL, Polars, and DuckDB in ~140 lines of Python — without writing a single CSV or instantiating a single Python row object on the data path.

The Panda's plan

Glue PostgreSQL, DuckDB, and Polars together with temporary CSV dumps and a hand-rolled parser script. Every hop converts numbers to text and back, silently drops Decimal(10, 2) precision into floats, mangles PostgreSQL arrays ({a,b}), and burns disk I/O writing temporary files nobody wants.

1. Architecture: zero-CSV ETL & Reverse ETL over Arrow#

ETL, Lakehouse & Reverse ETL over Arrow C Stream PostgreSQLOLTP source & target PolarsDataFrames & EtLT DuckDBAnalytical SQL & Parquet copy_to_arrow() ETL: copy_from_arrow() Arrow C Stream Parquet archive Reverse ETL: DuckDB relation → copy_from_arrow() → COPY BINARY All three engines exchange __arrow_c_stream__ pointers — zero CSV files and zero Python row loops.

First, an ETL / EtLT ingest step prepares a typed Polars DataFrame (Datetime("us", "UTC"), Decimal(10, 2), list[str]) and loads it into PostgreSQL's door_event_2026_07 partition via copy_from_arrow():

examples/144_arrow_duckdb_lakehouse.py · etl_ingest_from_polars
async def etl_ingest_from_polars(pool: pg.Pool, dormitory_id: int) -> None:
    await pool.create_partition(
        DoorEvent,
        name="door_event_2026_07",
        for_values="FROM ('2026-07-01 00:00:00+00') TO ('2026-08-01 00:00:00+00')",
    )
    # ETL / EtLT: normalize & type raw scans in Polars, then bulk-load via COPY BINARY.
    initial_df = pl.DataFrame(
        {
            "scanned_at": pl.Series(
                [
                    datetime(2026, 7, 5, 9, 0, tzinfo=UTC),
                    datetime(2026, 7, 5, 9, 15, tzinfo=UTC),
                    datetime(2026, 7, 5, 10, 0, tzinfo=UTC),
                    datetime(2026, 7, 5, 10, 30, tzinfo=UTC),
                ],
                dtype=pl.Datetime("us", "UTC"),
            ),
            "dormitory_id": pl.Series([dormitory_id] * 4, dtype=pl.Int64),
            "room_number": ["304", "101", "203", "304"],
            "badge_code": ["TRUNK-01", "TRUNK-02", "TRUNK-03", "TRUNK-04"],
            "species_code": ["savanna", "pygmy", "forest", "mammoth"],
            "granted": [True, True, True, True],
            "weight_kg": [5400.0, 1850.0, 3200.0, 8100.0],
            "tariff_eur": pl.Series(
                [Decimal("120.00"), Decimal("45.00"), Decimal("85.00"), Decimal("250.00")],
                dtype=pl.Decimal(10, 2),
            ),
            "tags": [["savanna_wing"], ["bunk"], ["quiet_pod"], ["reinforced"]],
        }
    )
    loaded = await pool.copy_from_arrow(DoorEvent, initial_df)
    print(f"ETL ingest: loaded {loaded} door scans from Polars into PostgreSQL")
    # => ETL ingest: loaded 4 door scans from Polars into PostgreSQL

2. Extract → DuckDB analytics → Parquet archive → Reverse ETL#

Next, Maya extracts the partitioned table from PostgreSQL into DuckDB, runs analytical SQL, writes a Parquet snapshot (verified in Polars), and executes a Reverse ETL write-back straight from DuckDB into PostgreSQL — preserving Decimal(10, 2), UTC timestamps, and TEXT[] tag arrays end to end:

examples/144_arrow_duckdb_lakehouse.py · lakehouse_audit_and_reverse_etl
async def lakehouse_audit_and_reverse_etl(pool: pg.Pool, dormitory_id: int) -> None:
    # 1. Extract (PostgreSQL -> Arrow -> DuckDB): decode COPY BINARY in Rust with zero Python
    #    row objects, hand off the Arrow C Stream zero-copy, and register it in DuckDB.
    pg_stream = await pool.copy_to_arrow(
        pg.select(DoorEvent).order_by(DoorEvent.scanned_at.asc()),
        batch_size=2,
    )
    events_arrow = pa.table(pg_stream)
    con = duckdb.connect()
    duck_events = con.from_arrow(events_arrow)

    # 2. Analytical SQL in DuckDB over the in-memory Arrow buffers.
    report = con.sql(
        """
        SELECT
            species_code,
            COUNT(*) AS scans,
            CAST(ROUND(AVG(weight_kg), 1) AS DOUBLE) AS avg_kg,
            SUM(tariff_eur) AS total_eur
        FROM duck_events
        GROUP BY species_code
        ORDER BY total_eur DESC
        """
    )
    print("DuckDB analytical summary:")
    # => DuckDB analytical summary:
    for species_code, scans, avg_kg, total_eur in report.fetchall():
        print(f"  {species_code}: {scans} scan(s), {avg_kg} kg, EUR {total_eur}")
        # =>   mammoth: 1 scan(s), 8100.0 kg, EUR 250.00
        # =>   savanna: 1 scan(s), 5400.0 kg, EUR 120.00
        # =>   forest: 1 scan(s), 3200.0 kg, EUR 85.00
        # =>   pygmy: 1 scan(s), 1850.0 kg, EUR 45.00

    # 3. Lakehouse archive: write Parquet from DuckDB and verify it in Polars.
    with tempfile.TemporaryDirectory() as tmp:
        parquet_path = Path(tmp) / "july_scans.parquet"
        duck_events.write_parquet(str(parquet_path))
        archive_df = pl.read_parquet(parquet_path)
        heaviest = archive_df.sort("weight_kg", descending=True).row(0, named=True)
        print(
            f"Parquet archive verified in Polars: {archive_df.height} rows, "
            f"heaviest={heaviest['species_code']} ({heaviest['weight_kg']:.0f} kg)"
        )
        # => Parquet archive verified in Polars: 4 rows, heaviest=mammoth (8100 kg)

    # 4. Reverse ETL (DuckDB -> PostgreSQL): DuckDB relations implement __arrow_c_stream__, so
    #    copy_from_arrow writes curated analytical outputs straight back via COPY BINARY.
    curated_backfill = con.sql(
        f"""
        SELECT
            TIMESTAMPTZ '2026-07-06 08:00:00+00' AS scanned_at,
            CAST({dormitory_id} AS BIGINT) AS dormitory_id,
            '304' AS room_number,
            'AUDIT-SYNC-1' AS badge_code,
            'pygmy' AS species_code,
            TRUE AS granted,
            1900.0::DOUBLE AS weight_kg,
            CAST(45.00 AS DECIMAL(10, 2)) AS tariff_eur,
            ['reverse_etl', 'verified']::VARCHAR[] AS tags
        """
    )
    written = await pool.copy_from_arrow(DoorEvent, curated_backfill)
    (total_rows,) = await pool.one(pg.select(DoorEvent).columns(pg.count()))
    print(
        f"Reverse ETL: wrote {written} audited row from DuckDB back to PostgreSQL "
        f"(total={total_rows})"
    )
    # => Reverse ETL: wrote 1 audited row from DuckDB back to PostgreSQL (total=5)

What just happened

  • Extract (PostgreSQL → DuckDB): pool.copy_to_arrow(...) decodes PostgreSQL binary COPY rows in Rust into Arrow RecordBatches with zero Python row objects; pa.table(pg_stream) takes ownership zero-copy via __arrow_c_stream__ so DuckDB (con.from_arrow(events_arrow)) can run analytical SQL and write july_scans.parquet directly over the same columnar memory buffers.
  • Lakehouse verification (Parquet → Polars): Polars reads july_scans.parquet directly and validates the archived schema and values (heaviest=mammoth (8100 kg)).
  • Reverse ETL (DuckDB → PostgreSQL): DuckDB's con.sql(...) relation itself implements __arrow_c_stream__. Passing curated_backfill straight to pool.copy_from_arrow(DoorEvent, curated_backfill) reads DuckDB's Arrow buffers in Rust and encodes them to PostgreSQL COPY FROM STDIN (FORMAT binary) — bringing door_event from 4 rows to 5 with zero intermediate Python dicts or model objects.

Maya's tip: Reverse ETL upserts vs. append-only loads

Append-only event/audit tables (like DoorEvent) can accept Reverse ETL writes directly via pool.copy_from_arrow(DoorEvent, duck_relation). When your Reverse ETL job updates existing operational rows (such as syncing customer churn scores or pricing tiers into Guest or Room), combine this chapter with Chapter 13: stream the DuckDB/Polars output into a temp=True staging table with tx.copy_from_arrow(Stage, duck_relation) and apply a single pg.merge(...).returning(pg.merge_action(), ...) inside the same transaction.

Ferris' basement: why __arrow_c_stream__ eliminates glue code

The Arrow PyCapsule Interface (__arrow_c_stream__) is a lightweight C-level protocol supported by pgdorm, polars, duckdb, and pyarrow. Instead of every pair of libraries writing bespoke adapters (or serializing through CSV/JSON), they exchange raw C pointers to columnar memory buffers. pgdorm does not even require pyarrow, polars, or duckdb as core dependencies — any library implementing the Arrow C Stream capsule works out of the box.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 6 statements in 5 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 21 statements omitted · full transcript in examples/__wire__/arrow_duckdb_lakehouse.sql

-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row

-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
  ($1, $2, $3, $4, $5, $6, $7, $8),
  ($9, $10, $11, $12, $13, $14, $15, $16),
  ($17, $18, $19, $20, $21, $22, $23, $24),
  ($25, $26, $27, $28, $29, $30, $31, $32),
  ($33, $34, $35, $36, $37, $38, $39, $40),
  ($41, $42, $43, $44, $45, $46, $47, $48),
  ($49, $50, $51, $52, $53, $54, $55, $56),
  ($57, $58, $59, $60, $61, $62, $63, $64),
  ($65, $66, $67, $68, $69, $70, $71, $72),
  ($73, $74, $75, $76, $77, $78, $79, $80),
  ($81, $82, $83, $84, $85, $86, $87, $88),
  ($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows

-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows

-- ── round trip 4 ──
COMMIT;

-- ── round trip 5 ──
SELECT COUNT(*)
FROM "door_event";
-- → 1 row

Shift report

  • Mapped ETL, ELT, EtLT, and Reverse ETL cleanly onto pgdorm primitives
  • Loaded typed Polars DataFrames into PostgreSQL via copy_from_arrow() (COPY BINARY)
  • Extracted PostgreSQL binary COPY straight into DuckDB via __arrow_c_stream__
  • Archived zero-copy Arrow tables to Parquet and verified them in Polars
  • Executed a Reverse ETL write-back directly from a DuckDB SQL relation into PostgreSQL

Try it yourself

Add a second curated row inside curated_backfill using UNION ALL in DuckDB and re-run the script. Watch copy_from_arrow write both Reverse ETL rows back into door_event_2026_07 in one binary COPY.

Go deeper: tests/integration/arrow/test_arrow.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"LAUNCH DAY! Put a FastAPI booking desk online, add a schema column at peak hour WITHOUT locking out guests, and hand Moby a test suite that catches every regression before it ships!"