Skip to content

2 · Bulk Insert & Plan Hygiene (bulk_insert)#

← All benchmarks · Related chapter: Chapter 3 · The 01:00 Herd

Insert 5,000 rows with mixed types (TEXT, INT4, NUMERIC(12,2), BOOLEAN, TIMESTAMPTZ), then audit distinct SQL shapes sent across 5 varying batch sizes (10, 37, 100, 250, 500) and 5 varying IN / = ANY($1) list lengths (3, 17, 50, 120, 300). pgdorm compiles insert_many() to UNNEST(...) WITH ORDINALITY and in_any() to = ANY($1) so PostgreSQL parses, plans, and caches one prepared statement regardless of cardinality.

Chart & metrics#

View Metric
Network Latency
ClientPG ServerNetwork
2. Bulk Insert & Plan Hygiene Insert rows in one batch 2. Bulk Insert & Plan Hygiene Insert rows in one batch Client PG Server Network pgdorm: 15.3 ms (Client 6.93 ms + Server 7.36 ms + Network 1.00 ms, 1 RTT) pgdorm SQLAlchemy 2: 42.6 ms (Client 27.9 ms + Server 11.8 ms + Network 3.00 ms, 3 RTT) SQLAlchemy 2 SQLModel: 42.9 ms (Client 28.1 ms + Server 11.8 ms + Network 3.00 ms, 3 RTT) SQLModel Tortoise ORM: 63.8 ms (Client 47.2 ms + Server 12.6 ms + Network 4.00 ms, 4 RTT) Tortoise ORM Django ORM: 74.1 ms (Client 63.3 ms + Server 7.84 ms + Network 3.00 ms, 3 RTT) Django ORM Peewee: 86.2 ms (Client 74.3 ms + Server 8.96 ms + Network 3.00 ms, 3 RTT) Peewee SQLDataclass: 101 ms (Client 71.2 ms + Server 26.6 ms + Network 3.00 ms, 3 RTT) SQLDataclass Piccolo ORM: 128 ms (Client 115 ms + Server 8.69 ms + Network 4.00 ms, 4 RTT) Piccolo ORM 0 63.8 ms 128 ms Default: Total Duration @ 1 ms/RTT (Client CPU + PG Server + Network). Hover bars for numbers.

ORM Instr (Client + PG) RTTs Server ms Sent Ins / IN Shapes ms (med)
pgdorm 235.1M (110.4M + 124.7M) 1 7.36 ms 264.3 KiB 1 / 1 17.44 ms
SQLModel 674.0M (391.9M + 282.1M) 3 11.82 ms 528.0 KiB 1 / 5 48.60 ms
SQLAlchemy 2 676.3M (393.3M + 283.0M) 3 11.76 ms 528.0 KiB 1 / 5 49.02 ms
Tortoise ORM 1.01B (684.0M + 330.1M) 4 12.63 ms 523.2 KiB 1 / 5 71.32 ms
SQLDataclass 1.15B (560.7M + 591.5M) 3 26.59 ms 459.1 KiB 1 / 5 77.09 ms
Django ORM 1.21B (1.05B + 161.0M) 3 7.84 ms 253.2 KiB 5 / 5 78.98 ms
Peewee 1.53B (1.16B + 367.2M) 3 8.96 ms 565.6 KiB 5 / 5 106.5 ms
Piccolo ORM 2.25B (1.86B + 392.3M) 4 8.69 ms 522.3 KiB 5 / 5 154.4 ms
Ferris' basement: Why 1 SQL shape protects prepared statements and plan caches

Multi-row VALUES ($1..$5), ($6..$10), ... and variable-length WHERE code IN ($1, ..., $N) emit a different SQL text for every distinct batch or list length — forcing auto-preparing drivers to parse and cache a separate prepared statement per length, splitting query logs, and creating separate pg_stat_statements entries for multi-row inserts. (Django 6.1+ also uses UNNEST on PostgreSQL under the hood, though its client-side parameter binding still produces 5 distinct wire shapes here.) With binary UNNEST and = ANY($1) parameters, pgdorm guarantees 1 insert shape and 1 lookup shape at the protocol level across every batch and list size.

Contender implementations#

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

pgdorm 0.10.0 (pgdorm-wire (Rust)) · 1 RTT · 110.4M instr · 17.44 ms · pgdorm_adapter.py

bench/adapters/pgdorm_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._pool is not None
    return await self._pool.execute(pg.insert_many(BenchEvent, rows, by_name=True))


async def in_lookup_events(self, codes: list[int]) -> int:
    assert self._pool is not None
    rows = await self._pool.all(pg.select(BenchEvent).where(BenchEvent.code.in_any(codes)))
    return len(rows)

SQLAlchemy 2 2.1.9 (asyncpg) · 3 RTTs · 393.3M instr · 49.02 ms · sqlalchemy_adapter.py

bench/adapters/sqlalchemy_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._session_factory is not None
    dicts = event_dicts(rows)
    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 len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    assert self._session_factory is not None
    async with self._session_factory() as s:
        rows = (await s.scalars(select(_Event).where(_Event.code.in_(codes)))).all()
    return len(rows)

SQLModel 0.0.50 (asyncpg) · 3 RTTs · 391.9M instr · 48.60 ms · sqlmodel_adapter.py

bench/adapters/sqlmodel_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._session_factory is not None
    dicts = event_dicts(rows)
    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 len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    assert self._session_factory is not None
    async with self._session_factory() as s:
        rows = (await s.exec(select(_SMEvent).where(col(_SMEvent.code).in_(codes)))).all()
    return len(rows)

SQLDataclass 0.4.3 (psycopg3 (sync)) · 3 RTTs · 560.7M instr · 77.09 ms · sqldataclass_adapter.py

bench/adapters/sqldataclass_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._engine is not None
    payload = event_dicts(rows)
    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 len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    assert self._engine is not None
    with self._engine.connect() as conn:
        return int(
            conn.execute(
                select(func.count())
                .select_from(SdEvent.__table__)
                .where(SdEvent.__table__.c.code.in_(codes))
            ).scalar_one()
        )

Django ORM 6.1.3 (psycopg3) · 3 RTTs · 1.05B instr · 78.98 ms · django_adapter.py

bench/adapters/django_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._Event is not None
    objs = [
        self._Event(
            category=r.category,
            code=r.code,
            amount=r.amount,
            active=r.active,
            recorded_at=r.recorded_at,
        )
        for r in rows
    ]
    with transaction.atomic():
        self._Event.objects.bulk_create(objs)
    return len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    assert self._Event is not None
    return len(list(self._Event.objects.filter(code__in=codes)))

Tortoise ORM 1.1.9 (asyncpg) · 4 RTTs · 684.0M instr · 71.32 ms · tortoise_adapter.py

bench/adapters/tortoise_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    objs = [
        _TEvent(
            category=r.category,
            code=r.code,
            amount=r.amount,
            active=r.active,
            recorded_at=r.recorded_at,
        )
        for r in rows
    ]
    async with in_transaction():
        await _TEvent.bulk_create(objs)
    return len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    rows = await _TEvent.filter(code__in=codes)
    return len(rows)

Piccolo ORM 1.39.0 (asyncpg) · 4 RTTs · 1.86B instr · 154.4 ms · piccolo_adapter.py

bench/adapters/piccolo_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._engine is not None
    objs = [
        self._Event(
            category=r.category,
            code=r.code,
            amount=r.amount,
            active=r.active,
            recorded_at=r.recorded_at,
        )
        for r in rows
    ]
    async with self._engine.transaction():
        for i in range(0, len(objs), 6_000):
            await self._Event.insert(*objs[i : i + 6_000])
    return len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    rows = await self._Event.objects().where(self._Event.code.is_in(codes))
    return len(rows)

Peewee 4.5.3 (psycopg3) · 3 RTTs · 1.16B instr · 106.5 ms · peewee_adapter.py

bench/adapters/peewee_adapter.py
async def bulk_insert_events(self, rows: list[EventInput]) -> int:
    assert self._db is not None
    dicts = event_dicts(rows)
    with self._db.atomic():
        # 10k rows * 5 cols = 50,000 params (< 65,535 PG wire parameter limit).
        for batch in pw.chunked(dicts, 10_000):
            _PWEvent.insert_many(batch).execute()
    return len(rows)


async def in_lookup_events(self, codes: list[int]) -> int:
    return len(list(_PWEvent.select().where(_PWEvent.code.in_(codes))))