Fixing PostgreSQL Locking During Batch Event Processing

How shorter transactions and conditional upserts reduced PostgreSQL batch lock contention, and the consistency trade-offs that followed.

  • PostgreSQL
  • Backend
  • Architecture
Before and after batch processing flows showing external lookups moved outside PostgreSQL transactions to shorten row-lock duration

The expensive part of a PostgreSQL lock is often the work performed while holding it. In this case, moving external reads and business decisions outside a batch transaction produced a large reduction in processing time—at the cost of a weaker cross-system consistency model.

An event consumer had become unpredictable under load. It processed records in batches, and overlapping batches sometimes waited seconds for PostgreSQL row locks. The natural response was to optimise the locking query. The more effective change was to ask why the transaction needed to hold locks while doing so much unrelated work.

The refactor replaced a locked read-modify-write cycle with precomputed input and a sorted batch of conditional PostgreSQL upserts. The observed improvement was substantial, but the resulting design also exposed ordering and data-freshness problems. Both halves of that story matter.

The original bottleneck

The consumer maintained one local row for each logical entity within a tenant. Several incoming records could belong to the same entity, and a business rule selected one as the representative record. That selection influenced the persisted entity state.

The original consumer read existing state from PostgreSQL, combined it with incoming records, and chose the representative before inserting or updating the row. To prevent simultaneous updates from invalidating the decision, it selected existing rows using SELECT ... FOR UPDATE.

The workload was batched. A configured limit was raised from 100 to 500 incoming records shortly before the refactor; that was a maximum, not a measured typical batch size. Workers could process overlapping entities concurrently.

This was not merely a slow SQL query. While row locks were held, the transaction also performed a blocking read from an external key-value store, with a timeout of up to 30 seconds, as well as further enrichment lookups and application-side merging.

Incoming batch
    ↓
BEGIN
    ↓
SELECT existing entity rows FOR UPDATE
    ↓
Blocking external lookup + enrichment
    ↓
Merge records and select representative
    ↓
Batch INSERT / UPDATE
    ↓
COMMIT

PostgreSQL held the selected rows’ locks until the transaction ended. The long external read is a plausible major contributor to the tail latency, although the measurements cannot isolate its exact contribution.

Why one overlapping row stalled a batch

Suppose two workers are processing batches that overlap on just one entity. If the first holds that row lock while waiting for external I/O, the second blocks when it reaches the shared entity. Other unrelated records within the second batch are delayed by its transaction boundary.

The old path also caught uniqueness violations and retried the entire batch, repeating the read, merge and write work. Concurrent insertion of a previously unseen entity was particularly vulnerable: there was no pre-existing row to lock. The historical code had a recursive retry path whose interaction with the outer transaction could theoretically cause self-blocking; whether that happened in production is unverified, so it is not used here to explain measured spikes.

The more general problem was coordination amplified by batch size and transaction duration, not the intrinsic cost of acquiring a row lock.

Change the ownership of the decision

The consumer was calculating its representative-record choice from locally stored and incoming records. An upstream reference-data system already maintained that decision.

One approach considered during review was to move the comparison into PostgreSQL’s conflict-update expression. But it would have made the final row depend on a decision inside SQL, complicating the application’s precomputed change hash and moving business logic into the persistence layer.

Instead, the selected design queried the authoritative system before starting the transaction. The consumer could then construct the desired row without locking the old one to derive that value.

Incoming batch
    ↓
Batched reference-data lookup
    ↓
Select representative + build desired rows
    ↓
Enrich and sort by entity key
    ↓
BEGIN
    ↓
Conditional PostgreSQL upsert batch
    ↓
COMMIT
    ↓
Journal trigger for changed rows

This moved all external calls out of the locked write window. It did not make the upstream lookup instantaneous or guaranteed fresh; those became separate operational concerns.

The actual PostgreSQL write

The replacement was not a single lock-free statement. It was a JDBC batch of individual INSERT ... ON CONFLICT DO UPDATE statements inside one transaction, with records sorted by conflict key for consistent lock ordering.

A reduced example using deliberately generic identifiers illustrates the mechanism:

INSERT INTO entity_state AS current_state (
    tenant_id,
    entity_id,
    representative_id,
    change_hash
)
VALUES ($1, $2, $3, $4)
ON CONFLICT (tenant_id, entity_id)
DO UPDATE SET
    representative_id = EXCLUDED.representative_id,
    change_hash = EXCLUDED.change_hash
WHERE current_state.change_hash != EXCLUDED.change_hash;

The production write updated additional fields and sometimes kept stored values when incoming fields were absent. The example shows the key mechanism without reproducing an internal schema.

There are three important details.

Locks still exist. PostgreSQL locks a conflicting row even if the WHERE condition later rejects the update, and that lock is held until commit. The gain comes from a much shorter transaction, not from the absence of row locking.

Unchanged inputs avoid downstream work. A row-level AFTER INSERT OR UPDATE trigger populated a durable journal for further processing. When the hash matched, the conflict update was skipped and the update trigger did not fire. The hash was calculated from the application’s constructed input; it was not a database version and did not guarantee freshness.

Lock ordering matters. Sorting by the conflict key made overlapping upsert batches acquire locks in a consistent order. Other write paths and backfills later needed additional fixes for incompatible lock orders. This design reduced contention, but did not eliminate all possible deadlocks.

What the measurements showed

Before and after the deployment, the team compared multi-day periods divided into 12-hour observation windows. The measurements are observational, not a controlled load benchmark. An increase in configured batch size shortly beforehand and a separate downstream scaling change shortly afterwards also limit some causal claims.

Measurement Before After
Batch-count-weighted mean processing time ~674 ms ~17 ms
Unweighted mean of 12-hour window means ~1,132 ms ~18 ms
Mean of window-level p95 measurements ~2,290 ms ~46 ms
Average concurrently waiting database queries ~0.276 ~0.049

The weighted batch-time comparison is approximately 39× lower, and the average count of waiting queries approximately 82% lower. The timing of the step change and the lock-wait metric support the diagnosis.

One extreme pre-deployment observation window disproportionately affected the unweighted figures. Excluding that window, the mean of window means was about 584 ms instead of 1,132 ms, still roughly 32× the 18 ms post-deployment mean. The central result—an order-of-magnitude reduction—does not depend on presenting the most dramatic ratio.

These figures measure application processing of a polled batch, including lookups and writes. They do not establish peak throughput, average batch occupancy or the capacity of the downstream journal. The 500-record batch limit cannot be treated as the actual number processed in every batch.

The consistency trade-off

The old design coordinated around locally stored state. The new design depended on an asynchronously updated reference-data service, whose reads were eventually consistent. Events belonging to the same logical entity could also be processed on different partitions because partitioning followed the incoming record rather than the parent entity.

There was no version or timestamp check in the upsert. Its predicate compared only the change hash. That makes this race possible:

Worker A reads representative = X  (older view)
Worker B reads representative = Y  (newer view)
Worker B commits Y
Worker A commits X                  ← stale value wins

PostgreSQL serialises conflicting writes, but it cannot determine which external answer is more recent. The frequency of this exact overwrite race has not been established.

The consumer also fell back to selecting a representative from the current batch when the reference-data lookup returned no matching entity—or when the lookup failed. A batch-local choice could be inconsistent with the full upstream entity state.

In the first release, the consumer processed an entity only if the selected representative appeared in the incoming batch. Because upstream state and events were updated asynchronously, that assumption was not always valid: some entity rows were skipped.

This is not evidence that the original locking strategy was preferable. It means the refactor traded expensive local coordination for cross-system freshness and convergence obligations that required further work.

What we had to fix afterwards

The initial latency improvement held, but subsequent changes addressed shortcomings revealed by production traffic:

  • Missing rows: events and upstream reference data could cross, leaving no record eligible to write. Follow-up changes introduced diagnostics and a fallback insertion path for missing entities.
  • Selection ambiguity: ties and repeated incoming records needed deterministic matching and more careful handling of the latest update within a batch.
  • Stale deletions: an outdated upstream representation could cause deletion of a still-valid local entity, requiring a separate correction.
  • Deadlocks elsewhere: backfills and other writers could acquire locks in a different order. Later changes standardised ordering or split transactions, with the associated atomicity trade-offs.
  • Hash-guard limitations: when a write preserved some stored fields while hashing only the constructed input, equal hashes could conceal a needed state change. A later correction addressed a reset operation that would otherwise be skipped.

These are meaningful correctness costs, not footnotes. The refactor had no general scheduled reconciliation mechanism for the representative choice, so later incoming events or explicit backfills were sometimes needed to repair discrepancies.

One downstream journal-latency elevation began before the deployment, and its recovery coincided with a separate scaling change. It would therefore be misleading to present that downstream graph as a result of the lock refactor.

Lessons from the refactor

Move slow work out of transactions. A row lock is not inherently a problem. Holding it during remote I/O, application computation and batch-wide decisions is.

Short transactions are not lock-free transactions. Conditional upserts still lock conflicting rows; predictable key order and limited transaction scope reduce their impact.

Optimising coordination can weaken consistency. Replacing a local locked decision with an eventually consistent upstream answer requires explicit reasoning about out-of-order events, stale writes and repair mechanisms.

Measure the whole system, but attribute carefully. Application batch latency and lock waits improved markedly. That does not prove proportional throughput growth, nor does it justify crediting unrelated downstream changes.

Conclusion

The lasting improvement came from changing where the decision was made and how long database locks were held. The consumer stopped performing blocking external reads during its PostgreSQL transaction, constructed its output beforehand, and used sorted, conditional upserts to persist it.

The measurable reduction in processing time was large. The subsequent consistency fixes were real as well. The useful principle is not “replace locks with upserts”; it is minimise what must happen while data is locked, and make the consistency contract of anything moved outside the transaction explicit.