Menu

1 / 2

Catching PostgreSQL Double-Spends in 60ms on the Wire Protocol (Without Touching App Code)

DEV Community: rust·Voskan Voskanyan·about 22 hours ago
#uHkP522X
#devtorust#devto#dev#balance#pgloom
Reading 0:00
15s threshold

Imagine a classic wallet withdrawal endpoint in Go, Python, Node, or Rust. Everything is wrapped inside a database transaction:

tx , _ := pool . Begin ( ctx ) defer tx . Rollback ( ctx )

var balance int64 _ = tx . QueryRow ( ctx , "SELECT balance FROM wallets WHERE id = $1" , walletID ) . Scan ( & balance ) if balance < amount { return ErrInsufficientFunds }

_ , _ = tx . Exec ( ctx , "UPDATE wallets SET balance = balance - $1 WHERE id = $2" , amount , walletID ) _ = tx . Commit ( ctx )

Enter fullscreen mode

Exit fullscreen mode

Your unit tests pass. Your sequential integration tests pass. Code review looks clean.

Then in production, a mobile client retries on a flaky network or a webhook fires twice in the same millisecond. Wallet 1 starts with balance = 100 . Both POST /withdraw requests for 100 return 200 OK . The database now says balance = -100 .

Why? Because PostgreSQL defaults to READ COMMITTED , where each statement sees a snapshot of data committed before that statement began.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.