--- title: "Check-Then-Act Is a Bug" author: "Emma Clements" published: "2026-12-02T05:31:57.740Z" updated: "2026-12-02T05:31:57.740Z" url: "https://zyvop.com/check-then-act-is-a-bug-k14hk" canonical: "https://zyvop.com/check-then-act-is-a-bug-k14hk" tags: ["backend","concurrency","postgres","Race Conditions","databases"] --- # 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. ![Cover image]() _"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: ```python 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 sequenceDiagram participant A as Request A participant DB as Postgres participant B as Request B rect rgba(232, 89, 12, 0.12) A->>DB: Any user with ana@example.com? DB-->>A: No B->>DB: Any user with ana@example.com? DB-->>B: No A->>DB: INSERT ana@example.com B->>DB: INSERT ana@example.com Note over A,B: Two accounts, one email end ``` 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): ```sql 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 ```sql 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: ```text 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: ```sql 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 %%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#2f9e44"}}}}%% xychart-beta title "Signups/s with zero duplicates (higher is better)" x-axis ["SERIALIZABLE", "Advisory lock", "ON CONFLICT"] y-axis "signups per second" 0 --> 16000 bar [1036, 6138, 13657] ``` ## Race 2: overselling ```python 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: ```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 ```sql 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 sequenceDiagram participant A as Buyer A participant DB as Product row, stock = 1 participant B as Buyer B rect rgba(47, 158, 68, 0.12) A->>DB: UPDATE ... SET stock = stock - 1 WHERE stock > 0 Note over DB: Locked by A, new stock = 0 B->>DB: UPDATE ... SET stock = stock - 1 WHERE stock > 0 Note over B,DB: B waits for A's lock A->>DB: COMMIT Note over DB: B re-checks stock > 0 on the new row: false DB-->>B: 0 rows updated, sold out end ``` ### The safety net: a CHECK constraint ```sql 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: ```text 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 %%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#1971c2"}}}}%% xychart-beta title "Units sold/s with zero oversells (higher is better)" x-axis ["SERIALIZABLE", "REPEATABLE READ", "FOR UPDATE", "Conditional UPDATE"] y-axis "units per second" 0 --> 2000 bar [476, 507, 1114, 1680] ``` ## Race 3: lost updates ```python 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: ```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 flowchart TD Q{"What must stay true?"} Q -->|"No duplicates"| U["Unique index
+ ON CONFLICT"] Q -->|"A number stays in range"| C["UPDATE ... WHERE stock > 0
+ CHECK constraint"] Q -->|"Add or subtract"| A["SET n = n + x"] Q -->|"Read, decide in code, write"| L{"Same row edited
often at once?"} L -->|"Yes, a hot row"| F["SELECT ... FOR UPDATE
in a short transaction"] L -->|"Rarely"| O["Version column
(optimistic locking)"] Q -->|"A rule no constraint
can express"| S["Advisory lock,
or SERIALIZABLE + retries"] classDef q fill:#fff3bf,stroke:#f08c00,color:#000 classDef db fill:#d3f9d8,stroke:#2f9e44,color:#000 classDef lock fill:#d0ebff,stroke:#1971c2,color:#000 classDef last fill:#ffe3e3,stroke:#e03131,color:#000 class Q,L q class U,C,A db class F,O lock class S last ``` 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: ```bash 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 ```sql -- 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 ```sql -- ===== 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 ```bash #!/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 (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 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