Skip to main content

Check-Then-Act Is a Bug

Duplicate signups, oversold stock and lost updates, reproduced on Postgres under real concurrency. Which fixes work, and which don't.

Updated 27 min readMarkdown
Check-Then-Act Is a Bug

"If it doesn't exist, create it." "If there's stock, sell it." Both look correct, pass every test, and fail under concurrent requests. I measured how often on Postgres, and which fixes actually work.


Here's code that passes every test you'll write for it:

if not User.objects.filter(email=email).exists():
    User.objects.create(email=email)

It reads like a guarantee: one account per email. It isn't one. There is a gap between the check and the insert. If a second request for the same email runs its check inside that gap, it passes too, and both requests insert.

The same pattern shows up in stock checks, balance updates, coupon redemptions, seat bookings, and "one free trial per customer." It's called check-then-act, and it's a race condition.

I reproduced three versions of it on Postgres with real concurrent connections and counted the damage. Then I tried the fixes people usually reach for, including every transaction isolation level.

TL;DR: With 16 concurrent requests, naive check-then-act code created 61,374 duplicate users in 10 seconds, oversold 99.9% of the products that sold out, and lost 93% of wallet top-ups. With just 2 concurrent requests (a double-click) it still hit 97% of emails, 27% of sell-outs, and lost 47% of top-ups. Wrapping the code in a transaction fixed none of the three. REPEATABLE READ fixed two of the three, at about 10 retries per success. The fixes that move the check into the database were correct and the fastest of the correct options: ON CONFLICT handled 13× more signups per second than SERIALIZABLE.

Every number here is measured, not estimated. Each approach ran for 10 seconds against a real Postgres 16 server, and I repeated the whole benchmark twice. The anomaly counts come from counting rows in the tables afterwards. The exact scripts are in the "Run it yourself" section near the end.


The shape of the bug

Mermaid Diagram

Each request did the right thing based on what it saw. The problem is that what it saw was out of date by the time it acted. Tests send one request at a time, so they never hit this. Production traffic does.

The bug comes in three forms:

Race What the code does What goes wrong
Check-then-insert "If no user has this email, create one" Duplicate rows
Check-then-update "If stock > 0, sell one" Overselling, negative balances
Read-modify-write "Read the balance, add in code, save" Updates silently lost

How I tested it

  • Server: Postgres 16.15 on a 2-vCPU, 7 GB VM with near-default settings. Client and server ran on the same machine.

  • Load: pgbench with 16 concurrent clients, 10 seconds per approach. I ran the whole suite twice. Throughput differed between the two runs by a median of 5% (the worst case, the 2-client signup test, differed by 32%), and every approach was correct or broken in both runs alike.

  • Realistic handlers: each handler is a pgbench script that sends the same SQL an ORM sends. It reads, decides on the client (\if), then writes. So there's a real network round trip between the check and the act, just like in your app.

  • Frequent collisions on purpose:

    • Signups: every request in the same millisecond uses the same email.

    • Stock: products go on sale one after another with 10 units each, and all buyers pile onto the current one.

    • Wallet: every top-up goes to the same account.

  • Retries: pgbench retries serialization failures automatically (--max-tries). In your app, you write that retry loop yourself.

That's a stress test. Real traffic collides less often, so don't read the percentages as your production rate. Read them as "this happens." That's also why I reran the naive code with just 2 concurrent clients, the equivalent of a double-click.

One more point: in this test, the gap between check and act is a single round trip over a local socket, well under a millisecond. In a real signup handler, the gap often includes hashing the password, which is designed to be slow. In production the window is wider, not narrower.

Race 1: duplicate signups

The handler, as SQL (this is what exists() followed by create() sends):

select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
select count(*) as found from users where email = 'u' || :bucket \gset
\if :found = 0
insert into users (email) values ('u' || :bucket);
\endif

Here's what each approach produced over 10 seconds. In each run, about 9,812 distinct emails were attempted, each one by several clients at once:

Approach Duplicate users Emails that got a duplicate Signups/s Retries per signup
Check, then insert (no transaction) 61,374 96% 8,060 none
Same, inside a transaction (READ COMMITTED, the default) 46,536 95% 6,306 none
Same, REPEATABLE READ 48,538 96% 5,957 none
Same, with SELECT ... FOR UPDATE 39,736 91% 5,639 none
Same, SERIALIZABLE + retries 0 0 1,036 6.0
Advisory lock on the email, then check 0 0 6,138 none
Unique index + ON CONFLICT DO NOTHING 0 0 13,657 none

Wrapping the code in a transaction changed nothing, and neither did REPEATABLE READ or FOR UPDATE. That surprises people, so here's why each one fails:

  • READ COMMITTED (Postgres's default): each statement sees what was committed when the statement started. B's check runs before A commits, so B sees nothing.

  • REPEATABLE READ: B works from a snapshot taken at its start, so it can't see A's row at all. Postgres raises a serialization error only when two transactions modify the same existing row. Here, both insert new rows, so no conflict is detected.

  • SELECT ... FOR UPDATE: it locks the rows the query returns. The check returns zero rows, so there's nothing to lock.

SERIALIZABLE is the only isolation level that caught it. Postgres tracks what each transaction read (here: "there's no user with this email") and aborts one transaction when the reads and writes can't be put into a serial order. That gave zero duplicates. The cost was about 6 retries per signup, and throughput fell from 8,060 to 1,036 signups/s.

SERIALIZABLE also aborts signups that don't conflict

Part of that cost isn't from real conflicts. The authors of Postgres's SERIALIZABLE implementation wrote that "locks on B+-tree indexes are acquired at page granularity" (Ports & Grittner, 2012), and the docs warn that coarser locks raise the rate of serialization failures. So two signups for different emails that land on the same index page can abort each other. The result below fits that explanation.

I measured it with SERIALIZABLE signups where no two requests ever used the same email:

New keys are... Transactions retried Signups/s
Adjacent in the index (time-ordered) 71% 1,353
Random, spread across the index 0.3% 6,844

Real email addresses are closer to random. Time-ordered keys are the bad case: sequential order numbers, timestamps, UUIDv7.

The fix: let the database decide

create unique index users_email_idx on users (email);

insert into users (email) values ($1) on conflict (email) do nothing;

This was the fastest correct approach, at 13,657 signups/s, because it sends one statement instead of two. It never retries and it never waits on a lock it doesn't need.

The unique index also protects you from code you haven't written yet. When I ran the naive handler against the unique index, it couldn't create a single duplicate. The losing request got this error instead:

ERROR:  duplicate key value violates unique constraint "users_email_idx"

Catch that error (SQLSTATE 23505) and treat it as "already registered." Two refinements, both tested:

  • Emails are case-insensitive in practice. Use create unique index ... on users (lower(email)), and then on conflict ((lower(email))) do nothing.

  • If the rule only applies to some rows, use a partial unique index. For example, "one active subscription per user" becomes create unique index on subscriptions (user_id) where status = 'active'.

Your framework already warns you about this:

  • Rails documents that find_or_create_by "is not atomic" and that you "end up with two similar records." It points to create_or_find_by, which relies on a unique constraint.

  • Django's get_or_create docs say that without uniqueness enforced at the database level, it "is prone to a race-condition which can result in multiple rows with the same parameters being inserted simultaneously."

When no constraint fits: an advisory lock

Some rules can't be written as a constraint. "At most 3 devices per account" is one example. For those, make the competing requests wait in line:

select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
begin;
select pg_advisory_xact_lock(hashtext('u' || :bucket));
select count(*) as found from users where email = 'u' || :bucket \gset
\if :found = 0
insert into users (email) values ('u' || :bucket);
\endif
commit;

This gave zero duplicates at 6,138 signups/s. pg_advisory_xact_lock is released automatically at commit. Two rules for using it:

  • Every code path that writes must take the same lock. A lock that only one code path takes protects nothing.

  • Lock on the narrowest key you can, such as the account id (pg_advisory_xact_lock(account_id)). hashtext is an internal Postgres function; any stable hash to an integer works. A hash collision only makes two unrelated requests wait for each other.

For rules about overlapping ranges, such as "no double-booked rooms," Postgres has a constraint for that too: an exclusion constraint, exclude using gist (room_id with =, during with &&) (it needs the btree_gist extension).

Mermaid Diagram

Race 2: overselling

product = Product.objects.get(id=pid)
if product.stock > 0:
    Product.objects.filter(id=pid).update(stock=F("stock") - 1)
    Order.objects.create(product_id=pid)

Look at the decrement: it's already atomic. F("stock") - 1 becomes stock = stock - 1, which is the textbook fix for lost updates. It doesn't help here, because the decrement is safe but the check is stale. The SQL:

select coalesce(min(id), 0) as pid from products where id >= :pid and stock > 0 \gset
select coalesce((select stock from products where id = :pid), 0) as stock \gset
\if :stock > 0
update products set stock = stock - 1 where id = :pid;
insert into orders (product_id) values (:pid);
\endif

The first line just finds the product currently on sale. The check is the second line.

Each run sold out about 1,360 products (10 units each) with the naive code:

Approach Sell-outs that oversold Extra units sold per sell-out Units sold/s Retries per sale
Check, then decrement (no transaction) 99.9% 10.5 2,784 (51% oversold) none
Same, inside a transaction (READ COMMITTED) 99.9% 11.8 2,414 (54% oversold) none
Same, REPEATABLE READ 0 0 507 11.3
Same, SERIALIZABLE + retries 0 0 476 11.4
Lock the row with SELECT ... FOR UPDATE, then check 0 0 1,114 none
One conditional UPDATE ... WHERE stock > 0 0 0 1,680 none

With the naive code, 99.9% of products oversold, by 10.5 units on average. Products with 10 units in stock sold about 20. Stock went as low as −15: with 16 buyers, up to 15 can pass the check after the last unit is gone. With only 2 buyers, 27% of sell-outs still oversold by one unit.

REPEATABLE READ and SERIALIZABLE both fixed it. Postgres refuses to update a row that changed after your snapshot was taken, and raises could not serialize access due to concurrent update. The cost was about 11 retries per sale on a hot product, and throughput dropped to about 507 units/s.

SELECT ... FOR UPDATE also fixed it, with no retries: buyers queue on the row lock, and each one checks fresh stock once it gets the lock.

The fix: put the check inside the UPDATE

select coalesce(min(id), 0) as pid from products where id >= :pid and stock > 0 \gset
with sold as (
  update products set stock = stock - 1
  where id = :pid and stock > 0
  returning id)
insert into orders (product_id) select id from sold;

If no row comes back, the product is sold out. This approach had zero oversells at 1,680 units/s, which is 3.3× faster than REPEATABLE READ. In Django it's Product.objects.filter(id=pid, stock__gt=0).update(stock=F("stock") - 1), which returns the number of rows updated.

It's safe even in the default READ COMMITTED level because of what Postgres does when two UPDATEs hit the same row. From the docs: the second updater "will wait for the first updating transaction to commit or roll back," and then the command's WHERE clause "is re-evaluated to see if the updated version of the row still matches the search condition."

Mermaid Diagram

The safety net: a CHECK constraint

alter table products add constraint stock_not_negative check (stock >= 0);

When I ran the naive handler with this constraint in place, it oversold zero units. The racing request failed instead:

ERROR:  new row for relation "products" violates check constraint "stock_not_negative"

Add the constraint even if you use the atomic UPDATE. It catches the next code path someone writes without knowing the rule.

Mermaid Diagram

Race 3: lost updates

account = Account.objects.get(id=1)
account.balance += 1
account.save()

save() writes the value your code computed, not "add 1." If two requests read the same balance, the second save overwrites the first. The SQL:

select balance from accounts where id = 1 \gset
update accounts set balance = :balance + 1 where id = 1;
insert into ledger (account_id, amount) values (1, 1);

Each top-up also wrote a ledger row, so I could compare what the ledger recorded with what the balance showed:

Approach Top-ups lost Top-ups saved/s Retries per top-up
Read, add in code, save (no transaction) 93% 149 none
Same, inside a transaction (READ COMMITTED) 93% 121 none
Same, REPEATABLE READ 0 815 10.4
Same, SERIALIZABLE + retries 0 749 10.7
Optimistic: save only WHERE version = ... 0 534 86% of saves conflicted
Lock the row with SELECT ... FOR UPDATE, then add 0 1,852 none
SET balance = balance + 1 0 1,900 none

With the naive code, the ledger recorded 22,583 top-ups, and the balance showed 1,486. That's 93% of the money gone, with no error anywhere. With just 2 concurrent clients, 47% was still lost.

The atomic version is the simplest fix and was the fastest: update accounts set balance = balance + 1 where id = 1. It's what Django's F() expressions are for. The docs describe this exact race: "the work of the first thread will be lost."

Which fix fits depends on the logic:

  • SELECT ... FOR UPDATE (1,852/s) is the tool when you must read, decide in code, then write, for example "reject the withdrawal if it would exceed the daily limit." Keep that transaction short, because every other request for that row waits on it.

  • Optimistic locking (a version column, saving only WHERE version = :version_you_read) lost nothing. But with 16 clients on one row, 86% of saves conflicted and would need a retry. It's a good fit for rows that are rarely edited at the same time, like two people editing the same record. It's a poor fit for a hot counter.

  • REPEATABLE READ and SERIALIZABLE were correct at about 10 retries per top-up, and less than half the throughput of the atomic update.

What isolation levels actually buy you

Here is every isolation result from above in one table, measured on Postgres 16:

Duplicate signups Overselling Lost updates
READ COMMITTED (default) ❌ 95% of emails ❌ 99.9% of sell-outs ❌ 93% lost
REPEATABLE READ ❌ 96% of emails ✅ 0, with retries ✅ 0, with retries
SERIALIZABLE ✅ 0, with retries ✅ 0, with retries ✅ 0, with retries
FOR UPDATE in READ COMMITTED ❌ 91% of emails (nothing to lock) ✅ 0 ✅ 0

Three things to take from it:

  1. A transaction on its own prevents none of these. BEGIN/COMMIT makes your writes all-or-nothing. It does not stop another request from acting on the same stale read.

  2. REPEATABLE READ protects existing rows, not missing ones. It refuses to update a row that changed under you, but it can't stop two transactions from each inserting a row the other didn't see.

  3. SERIALIZABLE works only if you retry. Postgres will abort transactions with SQLSTATE 40001, and you must re-run the whole transaction, reads included. Anything with side effects inside it, such as sending an email or calling a payment API, has to be safe to run twice.

These results are Postgres-specific. For example, MySQL/InnoDB's REPEATABLE READ does not prevent lost updates, according to the Hermitage isolation tests. Don't carry this table over to another database.

Choosing a fix

Mermaid Diagram

Prefer the green boxes. They put the rule in the database, where it holds for every code path: the one you're writing, the admin script someone writes next year, and the retry your load balancer sends when a request times out.

Spotting it in code review

Look for any of these patterns between two database calls:

  • exists(), count(), or find_by followed by create/insert.

  • if record.some_field ... followed by save() or an update.

  • record.field += n followed by save().

  • A comment like "this can't happen because we check first."

For each one, ask: what happens if two requests run this line at the same time? If the answer is "something bad," move the check into the write (ON CONFLICT, WHERE stock > 0, SET n = n + 1), back it with a constraint, or lock the row.

Run it yourself

You need Postgres and a pgbench from version 15 or newer (the retry option --max-tries was added in 15). I ran everything on 16. Set PGHOST, PGPORT, PGUSER and PGDATABASE to point at a scratch database, then run:

psql -f setup.sql
./run_bench.sh 1 && ./run_bench.sh 2   # ~5 minutes each; appends to results.csv
./safety_nets.sh                        # the naive handlers against constraints
./ser_false_positive.sh                 # SERIALIZABLE with non-conflicting keys
setup.sql: the tables
-- setup.sql: tables for the three races (tested on Postgres 16).
drop table if exists users, products, orders, accounts, ledger cascade;

-- Race 1: duplicate signups
create table users (
  id         bigint generated always as identity primary key,
  email      text not null,
  created_at timestamptz not null default now()
);
create index users_email_idx on users (email);   -- a plain index: "we check in code"

-- Race 2: overselling
create table products (id int primary key, stock int not null);
create table orders (
  id         bigint generated always as identity primary key,
  product_id int not null,
  created_at timestamptz not null default now()
);

-- Race 3: lost updates
create table accounts (id int primary key, balance bigint not null, version int not null default 0);
create table ledger (
  id         bigint generated always as identity primary key,
  account_id int not null,
  amount     int not null
);
bench/*.sql: every handler, exactly as benchmarked
-- ===== bench/signup.sql =====
-- Signup handler: "if no user has this email, create one".
-- Every request in the same millisecond uses the same email (a double-clicked button, x16).
select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
select count(*) as found from users where email = 'u' || :bucket \gset
\if :found = 0
insert into users (email) values ('u' || :bucket);
\endif

-- ===== bench/signup_for_update.sql =====
-- The usual reflex: "add FOR UPDATE". But there is no row to lock yet.
select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
begin;
select coalesce((select id from users where email = 'u' || :bucket limit 1 for update), 0) as found \gset
\if :found = 0
insert into users (email) values ('u' || :bucket);
\endif
commit;

-- ===== bench/signup_advisory.sql =====
-- Same check-then-act, but requests for the same email queue up on a lock first.
select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
begin;
select pg_advisory_xact_lock(hashtext('u' || :bucket));
select count(*) as found from users where email = 'u' || :bucket \gset
\if :found = 0
insert into users (email) values ('u' || :bucket);
\endif
commit;

-- ===== bench/signup_upsert.sql =====
-- Needs: create unique index on users (email). The database decides; no check in code.
select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
insert into users (email) values ('u' || :bucket) on conflict (email) do nothing;

-- ===== bench/stock.sql =====
-- Buy handler: "if stock > 0, sell one".
-- Products go on sale one after another, 10 units each; all buyers pile onto the current one.
-- (:pid persists per client, so the "which product is on sale" lookup stays cheap.)
select coalesce(min(id), 0) as pid from products where id >= :pid and stock > 0 \gset
select coalesce((select stock from products where id = :pid), 0) as stock \gset
\if :stock > 0
update products set stock = stock - 1 where id = :pid;
insert into orders (product_id) values (:pid);
\endif

-- ===== bench/stock_for_update.sql =====
-- Same handler, but the product row is locked before the check.
begin;
select coalesce(min(id), 0) as pid from products where id >= :pid and stock > 0 \gset
select coalesce((select stock from products where id = :pid for update), 0) as stock \gset
\if :stock > 0
update products set stock = stock - 1 where id = :pid;
insert into orders (product_id) values (:pid);
\endif
commit;

-- ===== bench/stock_atomic.sql =====
-- The check moves into the UPDATE's WHERE clause: one statement, no window.
select coalesce(min(id), 0) as pid from products where id >= :pid and stock > 0 \gset
with sold as (
  update products set stock = stock - 1
  where id = :pid and stock > 0
  returning id)
insert into orders (product_id) select id from sold;

-- ===== bench/wallet.sql =====
-- Top-up handler: read the balance, add 1, save (what `acct.balance += 1; acct.save()` sends).
select balance from accounts where id = 1 \gset
update accounts set balance = :balance + 1 where id = 1;
insert into ledger (account_id, amount) values (1, 1);

-- ===== bench/wallet_for_update.sql =====
-- Same read-modify-write, but the row is locked when it is read.
begin;
select balance from accounts where id = 1 for update \gset
update accounts set balance = :balance + 1 where id = 1;
insert into ledger (account_id, amount) values (1, 1);
commit;

-- ===== bench/wallet_atomic.sql =====
-- Let the database do the arithmetic on the current value.
begin;
update accounts set balance = balance + 1 where id = 1;
insert into ledger (account_id, amount) values (1, 1);
commit;

-- ===== bench/wallet_optimistic.sql =====
-- Optimistic locking: save only if nobody changed the row since we read it.
-- 0 rows updated = conflict; a real app re-reads and tries again.
select balance, version from accounts where id = 1 \gset
with saved as (
  update accounts set balance = :balance + 1, version = version + 1
  where id = 1 and version = :version
  returning id)
insert into ledger (account_id, amount) select id, 1 from saved;

-- ===== bench/ser_adjacent.sql =====
-- SERIALIZABLE signup where no two requests ever share an email (client id in the key),
-- but new keys are adjacent in the index (time-ordered).
select (extract(epoch from clock_timestamp()) * 1000)::bigint as bucket \gset
begin isolation level serializable;
select count(*) as found from users where email = 'u' || :bucket || '-' || :client_id \gset
\if :found = 0
insert into users (email) values ('u' || :bucket || '-' || :client_id);
\endif
commit;

-- ===== bench/ser_random.sql =====
-- Same, with random keys spread across the index (collisions: practically none).
\set k random(1, 1000000000)
begin isolation level serializable;
select count(*) as found from users where email = 'r' || :k \gset
\if :found = 0
insert into users (email) values ('r' || :k);
\endif
commit;
run_bench.sh: runs every approach and counts the damage
#!/usr/bin/env bash
# run_bench.sh: run every race and fix with 16 concurrent clients for 10 s each,
# then count the damage. Usage: ./run_bench.sh <run-number>   (appends to results.csv)
# Connection comes from the usual PGHOST/PGPORT/PGUSER/PGDATABASE environment variables.
set -euo pipefail
cd "$(dirname "$0")"
RUN=${1:-1}
PSQL=${PSQL:-psql}; PGBENCH=${PGBENCH:-pgbench}
CLIENTS=${CLIENTS:-16}; SECONDS_PER_TEST=${SECONDS_PER_TEST:-10}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }
[ -f results.csv ] || echo "run,scenario,variant,tps,processed,failed,retried,retries,metrics" > results.csv
mkdir -p logs gen

# The isolation-level variants are the plain handler wrapped in BEGIN ... COMMIT; nothing else changes.
wrap() {  # wrap <scenario> <isolation level>
  local out="gen/$1_${2// /_}.sql"
  { echo "begin isolation level $2;"; grep -v '^--' "bench/$1.sql"; echo "commit;"; } > "$out"
  echo "$out"
}

reset() {
  case $1 in
    signup)
      q -c "truncate users restart identity" -c "drop index if exists users_email_idx"
      if [ "$2" = unique ]; then q -c "create unique index users_email_idx on users (email)"
      else q -c "create index users_email_idx on users (email)"; fi ;;
    stock)
      q -c "truncate products, orders restart identity" \
        -c "insert into products select g, 10 from generate_series(1, 20000) g" ;;
    wallet)
      q -c "truncate accounts, ledger restart identity" -c "insert into accounts values (1, 0, 0)" ;;
  esac
  q -c "vacuum analyze" -c "checkpoint"
}

measure() {
  case $1 in
    signup) q -F ';' -c "
      select 'rows=' || count(*), 'distinct=' || count(distinct email),
             'duplicates=' || (count(*) - count(distinct email)),
             'dup_emails=' || (select count(*) from (select 1 from users group by email having count(*) > 1) d)
      from users" ;;
    stock) q -F ';' -c "
      select 'sellouts=' || count(*) filter (where stock <= 0),
             'oversold_sellouts=' || count(*) filter (where stock < 0),
             'oversold_units=' || coalesce(sum(-stock) filter (where stock < 0), 0),
             'min_stock=' || min(stock),
             'orders=' || (select count(*) from orders),
             'units_sold=' || sum(10 - stock)
      from products" ;;
    wallet) q -F ';' -c "
      select 'credited=' || (select coalesce(sum(amount), 0) from ledger),
             'balance=' || balance,
             'lost=' || ((select coalesce(sum(amount), 0) from ledger) - balance)
      from accounts where id = 1" ;;
  esac
}

run() {  # run <scenario> <variant> <script> [reset option]
  local scenario=$1 variant=$2 script=$3
  reset "$scenario" "${4:-}"
  local log="logs/run${RUN}_${scenario}_${variant}.log"
  $PGBENCH -n -c "$CLIENTS" -j 2 -T "$SECONDS_PER_TEST" --max-tries=1000 -D pid=1 -f "$script" > "$log" 2>&1
  local tps processed failed retried retries
  tps=$(grep -oP 'tps = \K[0-9.]+' "$log" | tail -1)
  processed=$(grep -oP 'actually processed: \K[0-9]+' "$log")
  failed=$(grep -oP 'number of failed transactions: \K[0-9]+' "$log" || echo 0)
  retried=$(grep -oP 'number of transactions retried: \K[0-9]+' "$log" || echo 0)
  retries=$(grep -oP 'total number of retries: \K[0-9]+' "$log" || echo 0)
  local metrics; metrics=$(measure "$scenario")
  echo "$RUN,$scenario,$variant,$tps,$processed,$failed,$retried,$retries,$metrics" | tee -a results.csv
}

for s in signup stock wallet; do
  run $s autocommit       bench/$s.sql
  run $s read_committed   "$(wrap $s 'read committed')"
  run $s repeatable_read  "$(wrap $s 'repeatable read')"
  run $s serializable     "$(wrap $s 'serializable')"
done
run signup for_update       bench/signup_for_update.sql
run signup advisory_lock    bench/signup_advisory.sql
run signup unique_upsert    bench/signup_upsert.sql unique
run stock  for_update       bench/stock_for_update.sql
run stock  atomic_update    bench/stock_atomic.sql
run wallet for_update       bench/wallet_for_update.sql
run wallet atomic_update    bench/wallet_atomic.sql
run wallet optimistic       bench/wallet_optimistic.sql
# Not a stampede: just two concurrent requests (a double-click), same naive handlers.
CLIENTS=2 run signup autocommit_2_clients bench/signup.sql
CLIENTS=2 run stock  autocommit_2_clients bench/stock.sql
CLIENTS=2 run wallet autocommit_2_clients bench/wallet.sql
safety_nets.sh: the naive handlers against a unique index and a CHECK constraint
#!/usr/bin/env bash
# safety_nets.sh: the same naive handlers, but with a constraint in the table.
# The race still happens; the database now refuses the bad write instead of storing it.
set -uo pipefail
cd "$(dirname "$0")"
PSQL=${PSQL:-psql}; PGBENCH=${PGBENCH:-pgbench}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }

echo "== signup.sql with a unique index"
q -c "truncate users restart identity" -c "drop index if exists users_email_idx" \
  -c "create unique index users_email_idx on users (email)"
$PGBENCH -n -c 16 -j 2 -T 3 -f bench/signup.sql 2>&1 | grep -m1 -oP 'ERROR: .*' || true
q -c "select 'duplicates: ' || (count(*) - count(distinct email)) from users"

echo "== stock.sql with check (stock >= 0)"
q -c "truncate products, orders restart identity" \
  -c "insert into products select g, 10 from generate_series(1, 20000) g" \
  -c "alter table products add constraint stock_not_negative check (stock >= 0)"
$PGBENCH -n -c 16 -j 2 -T 3 -D pid=1 -f bench/stock.sql 2>&1 | grep -m1 -oP 'ERROR: .*' || true
q -c "select 'oversold units: ' || coalesce(sum(-stock) filter (where stock < 0), 0) from products"
q -c "alter table products drop constraint stock_not_negative"

# Restore the plain index the main benchmark starts from.
q -c "drop index users_email_idx" -c "create index users_email_idx on users (email)"
ser_false_positive.sh: SERIALIZABLE retries with adjacent vs. random keys
#!/usr/bin/env bash
# ser_false_positive.sh: SERIALIZABLE signups that never truly conflict.
# How many get retried anyway, with adjacent keys vs random keys?
set -euo pipefail
cd "$(dirname "$0")"
PSQL=${PSQL:-psql}; PGBENCH=${PGBENCH:-pgbench}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }
for v in ser_adjacent ser_random; do
  for run in 1 2; do
    q -c "truncate users restart identity" \
      -c "insert into users (email) select 'r' || (random() * 1e9)::bigint from generate_series(1, 200000)" \
      -c "vacuum analyze users" -c "checkpoint"
    echo "== $v run $run"
    $PGBENCH -n -c 16 -j 2 -T 10 --max-tries=1000 -f bench/$v.sql 2>&1 \
      | grep -E "actually processed|transactions retried|^tps"
  done
done

The bottom line

Check-then-act code is correct only as long as nothing changes between the check and the act. Under concurrent requests, something always does. In this benchmark, the naive versions corrupted data with as few as two concurrent requests, and they never raised an error. You find out from a customer, an accountant, or a duplicate-account report.

The reflexes people reach for mostly don't work. A transaction doesn't stop the race. FOR UPDATE can't lock a row that doesn't exist. REPEATABLE READ catches two of the three races, but not duplicate inserts. SERIALIZABLE catches all three, as long as you retry, and here it cost up to 13× in throughput.

What works is to stop asking the database a question and then acting on the answer. Tell it the rule instead: a unique index, a WHERE clause on the UPDATE, a CHECK constraint, n = n + 1. Those fixes were correct in every run, and they were also the fastest. Write the rule into the database once, and every request that runs at the same moment has to follow it.


Published via ZyVOP — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.

About the author

  • One platform to write, cross-post to Dev.to, Medium, WordPress, Hashnode, and Bluesky, and protect your SEO with canonical links. Zero paywalls and full content ownership.

Reproducing duplicate signups and oversold stock directly on Postgres makes it obvious why application-level existence checks always lose under concurrent load. Pushing uniqueness constraints and atomic updates into the database is way cleaner than adding retries on top.

ZZyVOP10h ago

Exactly. The database should enforce critical invariants rather than relying on application-level checks that can become stale under concurrency. I'd use constraints and atomic updates as the first line of defense, keeping retries for cases where they're genuinely needed, such as serialization failures. This keeps the application logic much simpler.