Architecture & Reliability
Preventing Race Conditions in PostgreSQL: A Real-World Case Study
Keeping notification counts, previews, and delivery records consistent under concurrent review
Owen Velasco · Applied AI & Software Engineer | AI Applications, Automation Platforms, APIs & Enterprise Integrations · Dec 4, 2026 · 4 min read
In Credit Watch, an email summary had to answer three questions. How many items did this message cover? Which items could the reader see in the preview? Which rows should the database record as emailed afterward? I worked through two bugs that made those answers diverge. The first came from an API result limit. The second came from a person updating an item while the database prepared the message.
The difference matters in a review queue. A person can have an item in progress long after it appeared in an email. I want the open-workload count to include that item. I also want the next message to cover only records eligible for that particular notification. Giving those counts separate definitions made it possible to reason about what the application should do when a review changes mid-run.
The database gives the message a defined population and releases its lock before the external send.
Count the claim where it lives
The first problem was a mismatch between the API read and the database write. The database could claim a set larger than the application's read returned. The application counted a capped response and generated a preview from it. Completion still knew about the whole claim. An email could therefore say it covered one population while the database recorded a larger one.
The pull-request code moved retention and counting into PostgreSQL. The caller gets a count of the retained claim and a bounded preview. Preview size is a presentation choice. It places no upper bound on the number of rows the notification can cover. This is a useful distinction when an API pages or limits responses. The length of one page proves how many rows came back, and a separate contract is needed to establish how many satisfy the selection.
Fetching every page would address the cap. It would also add requests and require a coherent view across the reads while people were still updating items. The database already owned the claim and completion logic, so it was a better place to establish and count the associated membership.
A lock only protects the callers that take it
The retention routine took an advisory lock scoped to the organization. The human review update did not take that lock. Under PostgreSQL’s default Read Committed isolation, successive commands can observe different committed states. Wrapping a sequence in a transaction does not give all of its reads one stable view of the underlying data. Advisory locks also rely on cooperating code paths. Taking one in the notifier could not stop an update that ignored it. PostgreSQL transaction isolation · PostgreSQL advisory locks
In one controlled reproduction, a reviewer resolved an item after the count. The preview ran later and left the item out, so a summary could say it covered one row and display none. In another, an item was resolved after the step that released ineligible rows, left out of the count, and reopened before completion. The completion path could still mark that item as emailed for the claim. The discrepancy was in the stored outcome as well as the email.
The fix under review used the same transaction-scoped organization lock in claim, retention, completion, and review. Each path took the organization lock before acquiring row locks. A consistent order matters because a path that first holds a row while waiting for the organization lock can otherwise contend with a path that holds the organization lock while waiting for that row. Retention also derives the count and preview in the same statement that determines membership. Once a row is removed from that claim, reopening it does not put it back.
Draw the line at SMTP
Here is the shape of the protocol in pseudocode. The names and domain data are illustrative.
retain transaction:
take organization lock
discard ineligible claim members
derive retained membership, count, and preview together
commit
send email using that count and preview
completion transaction:
take organization lock
record outcome against eligible retained claim members
commit
The transaction ends before SMTP. Holding the lock while waiting on the network would make a slow email provider block human review. Ending it earlier leaves a real delivery boundary. A message can be accepted by the provider while its response is lost, or the process can stop before saving the outcome. Database consistency alone cannot settle either case.
For a system extending this design, I would use a durable claim identity for completion and make repeated completion requests harmless. A provider that supports a delivery lookup or an idempotency key may make some uncertain sends reconcilable. Without that evidence, I would preserve the unknown outcome for review. A local claim ID alone cannot make plain SMTP deduplicate a retry.
Test the order that causes the bug
We reproduced the race with two PostgreSQL sessions and advisory-lock barriers. Pausing one session at a known point let the other commit a review change before the first continued. That made both the count-versus-preview discrepancy and the resolved-then-reopened case repeatable. The API-boundary check separately exercised a claim larger than one capped read.
I would keep those checks focused on invariants. Every preview row belongs to the counted population. Completion records no row outside the retained claim. A person can continue reviewing items while the sender waits on its network call. The changes discussed here were pushed to a pull request and tested against PostgreSQL, with the migration unapplied in the available record. The concurrency result establishes what the branch was designed to fix. Production rollout remained a separate step.
PostgreSQL · concurrency · advisory locks · outbox
Related articles
Related work
More of the systems behind this writing is on the Work and Contact pages.