frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Testing Postgres race conditions with synchronization barriers

https://www.lirbank.com/harnessing-postgres-race-conditions
30•lirbank•1h ago

Comments

haliliceylan•1h ago
Thats not postgresql problem, thats your code

IMHO you should never write code like that, you can either do UPDATE employees SET salary = salary + 500 WHERE employee_id = 101;

Or if its more complex just use STORED PROCEDURE, there is no point of using database if you gonna do all transactional things in js

lirbank•52m ago
Fair point - atomic updates like SET salary = salary + 500 sidestep the race condition entirely for simple cases. The examples are intentionally simplified to isolate the concurrency behavior. The barrier pattern is more relevant when you have read-modify-write operations that involve application logic between the read and the write - those can't always collapse into a single UPDATE.
lirbank•43m ago
Here's a real-world example where atomic updates aren't an option - an order status transition that reads the current status from one table, validates the transition, and inserts into another:

await db().transaction(async (tx) => { await hooks?.onTxBegin?.();

  const [order] = await tx.select().from(orders)
    .where(eq(orders.id, input.id))
    .for("update");

  const [status] = await tx.select().from(orderStatuses)
    .where(eq(orderStatuses.orderId, input.id))
    .orderBy(desc(orderStatuses.createdAt))
    .limit(1);

  if (input.status === status.code)
    throw new Error("Status already set");

  await tx.insert(orderStatuses).values({ ... });
});

You need the transaction + SELECT FOR UPDATE because the validation depends on current state, and two concurrent requests could both pass the duplicate check. The hooks parameter is the barrier injection point from the article - that's how you test that the lock actually prevents the race.

erpellan•19m ago
The standard pattern to avoid select for update (which can cause poor performance under load) is to use optimistic concurrency control.

Add a numeric version column to the table being updated, read and increment it in the application layer and use the value you saw as part of the where clause in the update statement. If you see ‘0 rows updated’ it means you were beaten in a race and should replay the operation.

lirbank•15m ago
Good point. The barrier pattern from the article applies to both approaches - whether you're using pessimistic locks or optimistic version checks, it's good to verify that the concurrency handling actually works. Barriers let you test that your version check correctly rejects the stale update, the same way they test that your lock prevents the race.
codys•12m ago
Seems you could use a single SQL statement for that particular formulation. Something like this, using CTEs is possible, but alternately one can reformat them as subqueries. (note: not sure how the select of orders is intended to be used, so the below doesn't use it, but it does obtain it as an expression to be used)

    WITH
     o AS (
      SELECT FROM orders
      WHERE orders.id = $1
     ),
     os AS (
      SELECT FROM orderStatuses
      WHERE orderStatuses.orderId = $1
      ORDER BY DESC orderStatuses.createdAt
      LIMIT 1
     )
     INSERT INTO orderStatuses ...
     WHERE EXISTS (SELECT 1 FROM os WHERE os.code != $2)
     RETURNING ...something including the status differ check...
Does something like this work with postgres's default behavior?
scottlamb•11m ago
It'd be interesting to see a version of this that tries all the different interleavings of PostgreSQL operations between the two (or N) tasks. https://crates.io/crates/loom does something like this for Rust code that uses synchronization primitives.
lirbank•5m ago
Interesting! The barrier approach is more targeted: you specify the exact interleaving you want to test rather than exploring all of them. Trade-off is you need to know which interleavings matter, but you get deterministic tests that run against a real database instead of a simulated runtime. Exploring exhaustive interleaving testing against a real Postgres instance could be a fun follow-up - I'd be curious if it's practical.
anvevoice•6m ago
One pattern I've found useful alongside this: Postgres advisory locks (pg_advisory_xact_lock) for cases where the contention isn't row-level but logic-level. For example, if two requests try to create the "first" resource of a type - there's no existing row to SELECT FOR UPDATE against.

Advisory locks let you serialize on an arbitrary key (like a hash of the entity type + parent ID) without needing a dummy row or separate lock table. They auto-release on transaction end, so no cleanup.

The barrier testing approach from the article would work nicely here too - inject the barrier between acquiring the advisory lock and the subsequent insert, then verify the second transaction blocks until the first commits.

14-year-old Miles Wu folded origami pattern that holds 10k times its own weight

https://www.smithsonianmag.com/innovation/this-14-year-old-is-using-origami-to-design-emergency-s...
219•bookofjoe•3h ago•37 comments

Study: Self-generated Agent Skills are useless

https://arxiv.org/abs/2602.12670
59•mustaphah•57m ago•30 comments

Suicide Linux (2009)

https://qntm.org/suicide
46•icwtyjj•1h ago•24 comments

Testing Postgres race conditions with synchronization barriers

https://www.lirbank.com/harnessing-postgres-race-conditions
30•lirbank•1h ago•12 comments

Show HN: Wildex – we built Pokémon Go for real wildlife

https://apps.apple.com/us/app/wildex-identify-plants-animals/id6748092158
21•AnujNayyar•1h ago•11 comments

What your Bluetooth devices reveal

https://blog.dmcc.io/journal/2026-bluetooth-privacy-bluehood/
243•ssgodderidge•7h ago•84 comments

Visual Introduction to PyTorch

https://0byte.io/articles/pytorch_introduction.html
59•0bytematt•3d ago•4 comments

Turing Labs (YC W20) Is Hiring – Founding GTM Sales Hacker

1•turinglabs•1h ago

PCB Rework and Repair Guide [pdf]

https://www.intertronics.co.uk/wp-content/uploads/2017/05/PCB-Rework-and-Repair-Guide.pdf
55•varjag•2d ago•8 comments

Show HN: Jemini – Gemini for the Epstein Files

https://jmail.world/jemini
170•dvrp•16h ago•37 comments

State of Show HN: 2025

https://blog.sturdystatistics.com/posts/show_hn/
30•kianN•2h ago•3 comments

Show HN: Free Alternative to Wispr Flow, Superwhisper, and Monologue

https://github.com/zachlatta/freeflow
21•zachlatta•1h ago•8 comments

Qwen3.5: Towards Native Multimodal Agents

https://qwen.ai/blog?id=qwen3.5
343•danielhanchen•12h ago•161 comments

The Long Tail of LLM-Assisted Decompilation

https://blog.chrislewis.au/the-long-tail-of-llm-assisted-decompilation/
18•knackers•3h ago•3 comments

WebMCP Proposal

https://webmachinelearning.github.io/webmcp/
111•Alifatisk•5h ago•56 comments

Neurons outside the brain

https://essays.debugyourpain.com/p/you-are-not-just-your-brain
20•yichab0d•3h ago•8 comments

How to take a photo with scotch tape (lensless imaging) [video]

https://www.youtube.com/watch?v=97f0nfU5Px0
77•surprisetalk•5h ago•3 comments

History of AT&T Long Lines

https://telephoneworld.org/long-distance-companies/att-long-distance-network/history-of-att-long-...
52•p_ing•5h ago•25 comments

Chiplets Get Physical: The Days of Mix-and-Match Silicon Draw Nigh

https://www.eejournal.com/article/chiplets-get-physical-the-days-of-mix-and-match-silicon-draw-nigh/
11•transpute•2d ago•2 comments

Ghidra by NSA

https://github.com/NationalSecurityAgency/ghidra
276•handfuloflight•2d ago•152 comments

Use protocols, not services

https://notnotp.com/notes/use-protocols-not-services/
234•enz•3h ago•71 comments

Kim Dotcom says Palantir allegedly hacked

https://twitter.com/KimDotcom/status/2023165849721536672
19•hooch•27m ago•6 comments

Privilege is bad grammar

https://tadaima.bearblog.dev/privilege-is-bad-grammar/
131•surprisetalk•4h ago•121 comments

I want to wash my car. The car wash is 50 meters away. Should I walk or drive?

https://mastodon.world/@knowmadd/116072773118828295
1353•novemp•15h ago•837 comments

Fff.nvim – Typo-resistant code search

https://github.com/dmtrKovalenko/fff.nvim
17•neogoose•2h ago•1 comments

Show HN: Simple org-mode web adapter

https://github.com/SpaceTurth/Org-Web-Adapter
49•turth•5h ago•4 comments

Looks: A Halide Mark III Preview

https://www.lux.camera/mark-iii-looks/
66•patrikcsak•2d ago•17 comments

Show HN: 2D Coulomb Gas Simulator

https://simonhalvdansson.github.io/2D-Coulomb-Gas-Tools/index_gpu.html
16•swesnow•2h ago•4 comments

Ministry of Justice orders deletion of the UK's largest court reporting database

https://www.legalcheek.com/2026/02/ministry-of-justice-orders-deletion-of-the-uks-largest-court-r...
461•harel•8h ago•311 comments

Running My Own XMPP Server

https://blog.dmcc.io/journal/xmpp-turn-stun-coturn-prosody/
194•speckx•8h ago•120 comments