Skip to content

6 · PostgreSQL ↔ Polars Bridge (arrow_polars)#

← All benchmarks · Related chapter: Chapter 16 · The Polar Bears Arrive

Export 20,000 rows from PostgreSQL into a polars.DataFrame, and ingest 20,000 rows from Polars back into PostgreSQL. pgdorm decodes and encodes PostgreSQL COPY BINARY into columnar Arrow arrays inside Rust (skipping Python row objects), then hands the resulting Apache Arrow RecordBatches to Polars zero-copy via __arrow_c_stream__.

Chart & metrics#

View Metric
Network Latency
ClientPG ServerNetwork
6. PostgreSQL <-> Polars Bridge Export & Ingest 20,000 rows 6. PostgreSQL <-> Polars Bridge Export & Ingest 20,000 rows Client PG Server Network Export (PG -> Polars) Ingest (Polars -> PG) pgdorm pgdorm: 18.0 ms (Client 8.25 ms + Server 8.75 ms + Network 1.00 ms, 1 RTT) pgdorm: 39.1 ms (Client 6.50 ms + Server 30.6 ms + Network 2.00 ms, 2 RTT) SQLAlchemy 2 SQLAlchemy 2: 76.3 ms (Client 64.8 ms + Server 8.47 ms + Network 3.00 ms, 3 RTT) SQLAlchemy 2: 183 ms (Client 135 ms + Server 43.6 ms + Network 4.00 ms, 4 RTT) Tortoise ORM Tortoise ORM: 73.5 ms (Client 63.3 ms + Server 8.22 ms + Network 2.00 ms, 2 RTT) Tortoise ORM: 272 ms (Client 220 ms + Server 47.9 ms + Network 4.00 ms, 4 RTT) SQLModel SQLModel: 164 ms (Client 148 ms + Server 12.6 ms + Network 3.00 ms, 3 RTT) SQLModel: 182 ms (Client 135 ms + Server 43.3 ms + Network 4.00 ms, 4 RTT) Django ORM Django ORM: 52.7 ms (Client 41.8 ms + Server 9.90 ms + Network 1.00 ms, 1 RTT) Django ORM: 312 ms (Client 275 ms + Server 34.4 ms + Network 3.00 ms, 3 RTT) Peewee Peewee: 66.7 ms (Client 55.9 ms + Server 9.80 ms + Network 1.00 ms, 1 RTT) Peewee: 397 ms (Client 348 ms + Server 45.2 ms + Network 4.00 ms, 4 RTT) SQLDataclass SQLDataclass: 66.0 ms (Client 52.5 ms + Server 10.5 ms + Network 3.00 ms, 3 RTT) SQLDataclass: 471 ms (Client 318 ms + Server 149 ms + Network 4.00 ms, 4 RTT) Piccolo ORM Piccolo ORM: 64.5 ms (Client 49.9 ms + Server 12.5 ms + Network 2.00 ms, 2 RTT) Piccolo ORM: 554 ms (Client 514 ms + Server 33.1 ms + Network 7.00 ms, 7 RTT) 0 81.9 ms 164 ms 0 277 ms 554 ms Default: Total Duration @ 1 ms/RTT (Client CPU + PG Server + Network). Hover bars for numbers.

ORM Exp Instr (C + PG) Exp Peak Py Exp RTTs Ing Instr (C + PG) Ing Peak Py Ing RTTs
pgdorm 216.3M (91.0M + 125.3M) 8.7 KiB 1 395.0M (101.6M + 293.4M) 7.0 KiB 2
Django ORM 740.2M (603.6M + 136.5M) 12.56 MiB 1 5.12B (4.53B + 587.7M) 17.45 MiB 3
Piccolo ORM 852.7M (738.3M + 114.5M) 12.78 MiB 2 9.42B (7.89B + 1.53B) 20.26 MiB 7
SQLDataclass 898.5M (757.0M + 141.6M) 7.47 MiB 3 4.96B (2.67B + 2.29B) 14.21 MiB 4
Peewee 926.2M (799.6M + 126.6M) 10.64 MiB 1 5.88B (5.11B + 772.9M) 29.19 MiB 4
SQLAlchemy 2 1.06B (939.4M + 116.1M) 12.55 MiB 3 3.04B (1.95B + 1.08B) 18.73 MiB 4
Tortoise ORM 1.08B (960.0M + 115.5M) 13.29 MiB 2 4.41B (3.10B + 1.30B) 12.31 MiB 4
SQLModel 2.21B (2.09B + 119.0M) 44.49 MiB 3 3.07B (1.94B + 1.12B) 18.73 MiB 4
Ferris' basement: Why Polars ingest is 8×–24× fewer CPU instructions

Peer ORMs must convert 20,000 columnar Polars rows into 20,000 Python dicts or model instances, encode each parameter, and ship chunked multi-row INSERTs across the wire. pgdorm's copy_from_arrow() reads the Arrow C Stream buffers directly inside Rust and streams binary COPY FROM STDIN (FORMAT binary) straight into PostgreSQL — peaking at 7.0 KiB of Python heap instead of 12.31 MiB–29.19 MiB. (Arrow buffers and the temporary COPY decode buffer live in compact native Rust memory outside Python tracemalloc.)

Contender implementations#

Every tab below is AST-extracted directly from bench/adapters/ — zero hand-copied snippets.

pgdorm 0.10.0 (pgdorm-wire (Rust)) · Export 91.0M (1 RTT) · Ingest 101.6M (2 RTTs) · pgdorm_adapter.py

bench/adapters/pgdorm_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    assert self._pool is not None
    stream = await self._pool.copy_to_arrow(
        pg.select(BenchEvent).order_by(BenchEvent.bench_event_id.asc())
    )
    return pl.DataFrame(stream)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._pool is not None
    return await self._pool.copy_from_arrow(BenchEvent, df)

SQLAlchemy 2 2.1.9 (asyncpg) · Export 939.4M (3 RTT) · Ingest 1.95B (4 RTTs) · sqlalchemy_adapter.py

bench/adapters/sqlalchemy_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    assert self._session_factory is not None
    async with self._session_factory() as s:
        rows = (
            (
                await s.execute(
                    select(
                        _Event.bench_event_id,
                        _Event.category,
                        _Event.code,
                        _Event.amount,
                        _Event.active,
                        _Event.recorded_at,
                    ).order_by(_Event.bench_event_id)
                )
            )
            .mappings()
            .all()
        )
    return pl.DataFrame(rows)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._session_factory is not None
    dicts = df.to_dicts()
    chunk_size = PG_MAX_PARAMS // 5
    async with self._session_factory() as s, s.begin():
        for i in range(0, len(dicts), chunk_size):
            await s.execute(insert(_Event), dicts[i : i + chunk_size])
    return df.height

SQLModel 0.0.50 (asyncpg) · Export 2.09B (3 RTT) · Ingest 1.94B (4 RTTs) · sqlmodel_adapter.py

bench/adapters/sqlmodel_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    assert self._session_factory is not None
    async with self._session_factory() as s:
        rows = (await s.exec(select(_SMEvent).order_by(col(_SMEvent.bench_event_id)))).all()
    return pl.DataFrame([r.model_dump() for r in rows])


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._session_factory is not None
    dicts = df.to_dicts()
    chunk_size = PG_MAX_PARAMS // 5
    async with self._session_factory() as s, s.begin():
        for i in range(0, len(dicts), chunk_size):
            await s.execute(insert(_SMEvent), dicts[i : i + chunk_size])
    return df.height

SQLDataclass 0.4.3 (psycopg3 (sync)) · Export 757.0M (3 RTT) · Ingest 2.67B (4 RTTs) · sqldataclass_adapter.py

bench/adapters/sqldataclass_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    assert self._engine is not None
    with self._engine.connect() as conn:
        rows = load_all(
            conn,
            select(SdEvent.__table__).order_by(SdEvent.__table__.c.bench_event_id),
            SdEvent,
        )
    return pl.DataFrame(
        {
            "category": [r.category for r in rows],
            "code": pl.Series([r.code for r in rows], dtype=pl.Int32),
            "amount": pl.Series([r.amount for r in rows], dtype=pl.Decimal(12, 2)),
            "active": [r.active for r in rows],
            "recorded_at": pl.Series(
                [r.recorded_at for r in rows], dtype=pl.Datetime("us", "UTC")
            ),
        }
    )


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._engine is not None
    payload = df.to_dicts()
    chunk = max(1, _PG_MAX_PARAMS // 5)
    with self._engine.begin() as conn:
        for i in range(0, len(payload), chunk):
            insert_many(conn, SdEvent, payload[i : i + chunk])
    return df.height

Django ORM 6.1.3 (psycopg3) · Export 603.6M (1 RTT) · Ingest 4.53B (3 RTTs) · django_adapter.py

bench/adapters/django_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    assert self._Event is not None
    rows = list(
        self._Event.objects.order_by("bench_event_id").values(
            "bench_event_id", "category", "code", "amount", "active", "recorded_at"
        )
    )
    return pl.DataFrame(rows)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._Event is not None
    objs = [self._Event(**row) for row in df.iter_rows(named=True)]
    with transaction.atomic():
        self._Event.objects.bulk_create(objs)
    return df.height

Tortoise ORM 1.1.9 (asyncpg) · Export 960.0M (2 RTT) · Ingest 3.10B (4 RTTs) · tortoise_adapter.py

bench/adapters/tortoise_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    rows = (
        await _TEvent.all()
        .order_by("bench_event_id")
        .values("bench_event_id", "category", "code", "amount", "active", "recorded_at")
    )
    return pl.DataFrame(rows)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    objs = [_TEvent(**row) for row in df.iter_rows(named=True)]
    async with in_transaction():
        await _TEvent.bulk_create(objs)
    return df.height

Piccolo ORM 1.39.0 (asyncpg) · Export 738.3M (2 RTT) · Ingest 7.89B (7 RTTs) · piccolo_adapter.py

bench/adapters/piccolo_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    rows = await self._Event.select(
        self._Event.bench_event_id,
        self._Event.category,
        self._Event.code,
        self._Event.amount,
        self._Event.active,
        self._Event.recorded_at,
    ).order_by(self._Event.bench_event_id)
    return pl.DataFrame(rows)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._engine is not None
    objs = [self._Event(**row) for row in df.iter_rows(named=True)]
    async with self._engine.transaction():
        # 6,000 rows * 5 cols = 30,000 params (< asyncpg's 32,767 int16 parameter limit).
        for i in range(0, len(objs), 6_000):
            await self._Event.insert(*objs[i : i + 6_000])
    return df.height

Peewee 4.5.3 (psycopg3) · Export 799.6M (1 RTT) · Ingest 5.11B (4 RTTs) · peewee_adapter.py

bench/adapters/peewee_adapter.py
async def export_events_to_polars(self) -> pl.DataFrame:
    rows = list(_PWEvent.select().order_by(_PWEvent.bench_event_id).dicts())
    return pl.DataFrame(rows)


async def ingest_events_from_polars(self, df: pl.DataFrame) -> int:
    assert self._db is not None
    dicts = df.to_dicts()
    with self._db.atomic():
        for batch in pw.chunked(dicts, 10_000):
            _PWEvent.insert_many(batch).execute()
    return df.height