10 · Reverse ETL via DuckDB (reverse_etl_duckdb)#
← All benchmarks · Related chapter: Chapter 17 · ETL, Lakehouse & Reverse ETL
Extract 10,000 events from PostgreSQL into an in-process DuckDB analytical query (GROUP BY into 200 SKU/category summary buckets) and write the curated summaries back into PostgreSQL (updating 100 existing buckets and inserting 100 new buckets, returning verified totals). pgdorm streams COPY BINARY straight into Arrow C Stream → DuckDB → COPY BINARY into pg_temp → MERGE … RETURNING without materializing 10,000 Python row dicts.
Chart & metrics#
| ORM | Instr (Client + PG) | Peak Py | RTTs | Server ms | ms (med) |
|---|---|---|---|---|---|
| pgdorm | 262.8M (184.3M + 78.5M) | 81.6 KiB | 5 | 6.34 ms | 24.94 ms |
| Django ORM | 574.2M (480.1M + 94.1M) | 6.27 MiB | 5 | 8.49 ms | 48.59 ms |
| Piccolo ORM | 651.7M (566.8M + 84.9M) | 6.38 MiB | 6 | 9.52 ms | 50.93 ms |
| Peewee | 676.5M (582.4M + 94.0M) | 5.31 MiB | 4 | 7.54 ms | 54.74 ms |
| SQLDataclass | 734.8M (628.0M + 106.9M) | 3.72 MiB | 8 | 8.01 ms | 61.91 ms |
| Tortoise ORM | 739.8M (646.2M + 93.6M) | 6.92 MiB | 7 | 7.90 ms | 58.47 ms |
| SQLAlchemy 2 | 827.6M (740.4M + 87.2M) | 6.52 MiB | 6 | 12.69 ms | 69.57 ms |
| SQLModel | 1.41B (1.32B + 83.5M) | 22.50 MiB | 6 | 10.47 ms | 112.0 ms |
Ferris' basement: Zero-CSV, zero-dict lakehouse round trips
Because both pgdorm and DuckDB speak the Arrow C Stream interface natively, 10,000 rows flow from PostgreSQL COPY BINARY into DuckDB and the 200 aggregated buckets flow right back into a pg_temp staging table with only 81.6 KiB of peak Python heap (compared to multi-MiB row/dict ORM loops). Notice the honest RTT trade-off: pgdorm takes 5 RTTs (copy_to_arrow + tx.stage + 2-RTT COPY FROM STDIN + MERGE … RETURNING) versus sync peers' 4 RTTs (INSERT … ON CONFLICT), trading 1 extra RTT and slightly higher server-side staging time for lower client CPU and near-zero Python GC pressure.
Contender implementations#
Every tab below is AST-extracted directly from bench/adapters/ — zero hand-copied snippets.
pgdorm 0.10.0 (pgdorm-wire (Rust)) · 5 RTTs · 184.3M instr · 24.94 ms · pgdorm_adapter.py
_MERGE_SUMMARY_STMT = (
pg.merge(BenchSkuSummary)
.using(BenchSummaryStage)
.on(BenchSkuSummary.bucket_key)
.when_matched_update(by_name=True)
.when_not_matched_insert(by_name=True)
.returning(
BenchSkuSummary.bucket_key,
BenchSkuSummary.event_count,
BenchSkuSummary.total_amount,
)
)
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._pool is not None
stmt = pg.select(BenchEvent).order_by(BenchEvent.bench_event_id.asc())
events_arrow = pa.table(await self._pool.copy_to_arrow(stmt))
with duckdb.connect() as con:
events_rel = con.from_arrow(events_arrow)
curated = con.sql(reverse_etl_duckdb_sql(buckets_per_cat))
assert events_rel is not None
async with self._pool.transaction() as tx:
await tx.stage(BenchSummaryStage, [], analyze=False)
await tx.copy_from_arrow(BenchSummaryStage, curated)
async with tx.pipeline(commit=True) as pipe:
h_merged = pipe.add(_MERGE_SUMMARY_STMT)
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in h_merged.all()]
SQLAlchemy 2 2.1.9 (asyncpg) · 6 RTTs · 740.4M instr · 69.57 ms · sqlalchemy_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._session_factory is not None
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
stmt = pg_insert(_SkuSummary).values(dicts)
upsert = stmt.on_conflict_do_update(
index_elements=[_SkuSummary.bucket_key],
set_={
"event_count": stmt.excluded.event_count,
"total_amount": stmt.excluded.total_amount,
"avg_amount": stmt.excluded.avg_amount,
},
).returning(_SkuSummary.bucket_key, _SkuSummary.event_count, _SkuSummary.total_amount)
async with self._session_factory() as s, s.begin():
rows = (await s.execute(upsert)).all()
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in rows]
SQLModel 0.0.50 (asyncpg) · 6 RTTs · 1.32B instr · 112.0 ms · sqlmodel_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._session_factory is not None
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
stmt = pg_insert(_SMSkuSummary).values(dicts)
upsert = stmt.on_conflict_do_update(
index_elements=[col(_SMSkuSummary.bucket_key)],
set_={
"event_count": stmt.excluded.event_count,
"total_amount": stmt.excluded.total_amount,
"avg_amount": stmt.excluded.avg_amount,
},
).returning(
col(_SMSkuSummary.bucket_key),
col(_SMSkuSummary.event_count),
col(_SMSkuSummary.total_amount),
)
async with self._session_factory() as s, s.begin():
rows = (await s.execute(upsert)).all()
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in rows]
SQLDataclass 0.4.3 (psycopg3 (sync)) · 8 RTTs · 628.0M instr · 61.91 ms · sqldataclass_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
events_df = await self.export_events_to_polars()
rows = duckdb_aggregate_dicts(events_df, buckets_per_cat)
assert self._engine is not None
tbl = SdSkuSummary.__table__
with self._engine.begin() as conn:
stmt = pg_insert(tbl).values(rows)
stmt = stmt.on_conflict_do_update(
index_elements=[tbl.c.bucket_key],
set_={
"event_count": stmt.excluded.event_count,
"total_amount": stmt.excluded.total_amount,
"avg_amount": stmt.excluded.avg_amount,
},
)
conn.execute(stmt)
out = conn.execute(
select(tbl.c.bucket_key, tbl.c.event_count, tbl.c.total_amount).order_by(
tbl.c.bucket_key
)
).all()
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in out]
Django ORM 6.1.3 (psycopg3) · 5 RTTs · 480.1M instr · 48.59 ms · django_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._SkuSummary is not None
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
objs = [self._SkuSummary(**d) for d in dicts]
with transaction.atomic():
self._SkuSummary.objects.bulk_create(
objs,
update_conflicts=True,
unique_fields=["bucket_key"],
update_fields=["event_count", "total_amount", "avg_amount"],
)
rows = list(
self._SkuSummary.objects.order_by("bucket_key").values_list(
"bucket_key", "event_count", "total_amount"
)
)
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in rows]
Tortoise ORM 1.1.9 (asyncpg) · 7 RTTs · 646.2M instr · 58.47 ms · tortoise_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
objs = [_TSkuSummary(**d) for d in dicts]
async with in_transaction() as conn:
await _TSkuSummary.bulk_create(
objs,
on_conflict=["bucket_key"],
update_fields=["event_count", "total_amount", "avg_amount"],
using_db=conn,
)
rows = (
await _TSkuSummary.all()
.using_db(conn)
.order_by("bucket_key")
.values_list("bucket_key", "event_count", "total_amount")
)
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in rows]
Piccolo ORM 1.39.0 (asyncpg) · 6 RTTs · 566.8M instr · 50.93 ms · piccolo_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._engine is not None
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
objs = [self._SkuSummary(**d) for d in dicts]
async with self._engine.transaction():
rows = (
await self._SkuSummary.insert(*objs)
.on_conflict(
target=self._SkuSummary.bucket_key,
action="DO UPDATE",
values=[
self._SkuSummary.event_count,
self._SkuSummary.total_amount,
self._SkuSummary.avg_amount,
],
)
.returning(
self._SkuSummary.bucket_key,
self._SkuSummary.event_count,
self._SkuSummary.total_amount,
)
)
return [
(str(r["bucket_key"]), int(r["event_count"]), Decimal(r["total_amount"])) for r in rows
]
Peewee 4.5.3 (psycopg3) · 4 RTTs · 582.4M instr · 54.74 ms · peewee_adapter.py
async def reverse_etl_duckdb(self, buckets_per_cat: int) -> list[SummaryRow]:
assert self._db is not None
events_df = await self.export_events_to_polars()
dicts = duckdb_aggregate_dicts(events_df, buckets_per_cat)
with self._db.atomic():
rows = list(
_PWSkuSummary.insert_many(dicts)
.on_conflict(
conflict_target=[_PWSkuSummary.bucket_key],
preserve=[
_PWSkuSummary.event_count,
_PWSkuSummary.total_amount,
_PWSkuSummary.avg_amount,
],
)
.returning(
_PWSkuSummary.bucket_key,
_PWSkuSummary.event_count,
_PWSkuSummary.total_amount,
)
.tuples()
.execute()
)
return [(str(k), int(cnt), Decimal(tot)) for k, cnt, tot in rows]