[aryan@dev]
← cd ~/work
Idekavan GroupTechnical Manager & Backend Engineer2025 - 2026

Eliminating Write Amplification & Row-Lock Convoys on a 49 GB PostgreSQL Table

How Django's bulk_update() CASE WHEN explosion, unleased 'idempotent' webhook retries, and a hidden 2.6 GB varchar_pattern_ops index generated 48% of primary WAL, and how we fixed all three.

4.1-8.2s bulk_update -> 0.12-2.55 ms
Reclaimed 3.1 GB of WAL-amplifying indexes
Eliminated 54 GB / 6-day temp-file sorts
PostgreSQLDjango ORMPythonCelery

When our primary PostgreSQL database started saturating disk I/O and WAL throughput on a 28.9M-row / 49 GB SMS ledger table and its companion 20.7M-row / 24 GB delivery-report webhook inbox, pg_stat_statements and pg_stat_user_tables pointed to three specific causes. The webhook table alone generated 48% of the primary database’s WAL with 0% HOT (Heap-Only Tuple) updates, and 29 of 38 delivery-report worker timeouts came from a single ORM call.

1. Django bulk_update() CASE WHEN explosion vs. unnest()

Symptom

Delivery-report workers updated batches of 1,000 ledger rows using Django’s Model.objects.bulk_update(objs, fields). In pg_stat_statements, those updates averaged 4.1s-8.2s (with spikes up to 238s), accounting for 29 of 38 worker statement timeouts. Constant-value UPDATE statements on the same table ran in 0.12-2.55 ms.

Cause

Django’s bulk_update() compiles a single UPDATE with one CASE WHEN id = %s THEN %s branch per row per column:

UPDATE sms_log
SET status = CASE WHEN id = 101 THEN 'delivered' WHEN id = 102 THEN ... END,
    delivered_at = CASE WHEN id = 101 THEN '2026-...' WHEN id = 102 THEN ... END,
    ...
WHERE id IN (101, 102, ...);

At 1,000 rows × 5-10 columns, each call emitted 104-465 KB of unique SQL text (up to 10,000 CASE branches). Because the SQL shape changed with every batch size, PostgreSQL had to reparse and replan every call, and the huge query strings evicted useful entries from pg_stat_statements.

There was also an error-masking bug: when one of these statements hit statement_timeout, our finally: block ran SET statement_timeout = DEFAULT on the already-aborted transaction connection. PostgreSQL rejected that cleanup statement with InFailedSqlTransaction, which overwrote and hid the original QueryCanceled error in error tracking.

Fix

Whenever a batch sets the same value across all rows, we switched to a single filter(id__in=...).update(...) instead of bulk_update. For per-row updates, we built a reusable bulk_update_via_unnest helper that passes typed PostgreSQL array parameters and joins against unnest(...):

UPDATE sms_log AS target
SET status = src.status,
    delivered_at = src.delivered_at
FROM unnest(%s::bigint[], %s::text[], %s::timestamptz[])
     AS src(id, status, delivered_at)
WHERE target.id = src.id;

The SQL string and parameter count stay constant regardless of batch size (10 rows or 1,000 rows), giving PostgreSQL a single cached plan and clean pg_stat_statements aggregation. We pinned the behavior with SQL-shape unit tests asserting zero CASE WHEN clauses and bounded query count.

2. “Idempotent” retries creating PK row-lock convoys, and “events born leased”

Symptom

During brief worker lag, delivery-report processing collapsed. Workers timed out on the single-row UPDATE webhook_event SET status = 'COMPLETED' WHERE id = %s at the end of the task instead of the heavier ledger update.

Cause

A periodic 1-minute sweep scanned webhook_event rows in state RECEIVED and published them to RabbitMQ without marking them as leased, on the assumption that re-publishing was safe because the worker’s _claim() step was idempotent.

Idempotency protects correctness, while lock queues still pile up. Under 5 minutes of queue lag, the sweep published ~5 duplicate messages per row. All 5 workers hit SELECT ... FROM webhook_event WHERE id = %s FOR UPDATE simultaneously, forming a PK row-lock convoy:

Worker 1: locks row #42 → updates sms_log → releases/re-acquires lock to mark COMPLETED
Worker 2: queued on row #42 FOR UPDATE
Worker 3: queued on row #42 FOR UPDATE
Worker 4: queued on row #42 FOR UPDATE
  └─ Even Worker 1 (the winner) times out waiting behind its own duplicates
     when trying to re-acquire the row lock to mark the event COMPLETED!

Fix: “events born leased”

First, we introduced QUEUED dispatch leases so the sweep would not re-publish a row before its lease expired. That stopped the convoy, but still paid a full INSERT (RECEIVED) followed immediately by an UPDATE (QUEUED) on every delivery report.

We removed that extra write by inserting events already leased:

  1. The webhook HTTP handler inserts new events already in QUEUED state with a shared lease_until = now() + interval timestamp.
  2. Immediately after commit, the handler publishes only the rows matching its own lease_until deadline.
  3. The background sweep only picks up rows whose lease_until < now() (crashed or lost deliveries).

This removed one non-HOT UPDATE (and 7 index tuple insertions) per delivery report under normal operation, while keeping recovery deterministic.

3. The hidden 2.6 GB varchar_pattern_ops index destroying HOT updates

Symptom

Even after fixing the write paths, the 20.7M-row / 24 GB webhook table still showed 0% HOT updates and accounted for 48% of all WAL on the primary database.

Cause

PostgreSQL can only perform a HOT update (updating a row in-place on the same heap page without touching any indexes) if no indexed column changes. Even when an indexed column does change (like status), every additional index on the table must insert a new index tuple. If an index’s key distribution is random, every insert dirties a different B-tree leaf page, forcing PostgreSQL to emit a full-page WAL image after each checkpoint.

Inspecting \d+ webhook_event revealed a 2.6 GB index nobody had explicitly written:

"webhook_event_dedup_hash_a1b2c3_like" btree (dedup_hash varchar_pattern_ops)

In Django on PostgreSQL, setting unique=True or db_index=True on a CharField automatically creates a second varchar_pattern_ops (_like) index to support LIKE 'prefix%' queries. Our dedup_hash column held a random SHA-256 hex digest that was only ever queried by exact equality. Every row insert and non-HOT update was dirtying random leaf pages in a 2.6 GB index nobody read.

Fix

  • Replaced unique=True on the CharField with an explicit models.UniqueConstraint(fields=["dedup_hash"], name=...) in Meta.constraints, which creates only the standard B-tree unique index and suppresses the _like twin.
  • Dropped the _like index and unused secondary indexes online via DROP INDEX CONCURRENTLY inside SeparateDatabaseAndState with atomic = False, reclaiming 3.1 GB of index space and sharply reducing primary WAL generation.
  • In a companion pass on our SKIP LOCKED campaign drainer, we aligned the ORDER BY clause with the partial index (campaign_log_id, released_at, id), eliminating 54 GB of PostgreSQL temp-file sorts over 6 days, pinned with EXPLAIN regression tests.

Takeaways

  • bulk_update() does not scale on large PostgreSQL tables. Once batches exceed a few dozen rows, CASE WHEN SQL bloat destroys plan caching and pg_stat_statements. Use unnest() with array parameters for constant SQL shape.
  • Re-publishing unleased work under lag turns a healthy worker pool into a PK row-lock convoy, even if handlers are idempotent. If work is dispatched immediately on ingest, consider inserting rows already leased.
  • Audit Django CharField(unique=True) indexes on high-churn Postgres tables. High-entropy hashes with auto-generated varchar_pattern_ops twin indexes amplify random B-tree page dirties and full-page WAL writes.
Discussion

Comments

Loading…

Leave a note

Comments are moderated before appearing publicly.