惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
MyScale Blog
MyScale Blog
N
News and Events Feed by Topic
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
The Cloudflare Blog
博客园 - 聂微东
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
V
Visual Studio Blog
M
MIT News - Artificial intelligence
V
V2EX
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale
F
Full Disclosure
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
博客园 - 叶小钗
S
SegmentFault 最新的问题
博客园 - 三生石上(FineUI控件)
D
Docker
Engineering at Meta
Engineering at Meta
博客园 - Franky
aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
博客园 - 司徒正美
I
InfoQ
G
Google Developers Blog
L
LangChain Blog
F
Fortinet All Blogs
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
A
Arctic Wolf
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
L
LINUX DO - 热门话题
C
Cisco Blogs
Y
Y Combinator Blog
罗磊的独立博客

Hacker News

Introducing Claude Opus 4.7 Qwen Studio The Future of Everything is Lies, I Guess: Where Do We Go From Here? GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis Bonsai 1-bit WebGPU - a Hugging Face Space by webml-community Moving a large-scale metrics pipeline from StatsD to OpenTelemetry / Prometheus GitHub - Nightmare-Eclipse/RedSun: The Red Sun vulnerability repository GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - macOS26/Agent: Any AI, replaces Claude Code, Cursor, OpenClaw. Over 18 LLM providers (Claude, OpenAI, Gemini, Ollama, Zai, HF, Qwen) wired into a native Mac app that writes code, builds Xcode projects, bumps versions, manages git, automates Safari, use AppleScript, JS or Accessibility, extend Agent! w/ MCP Servers, run tasks from your iPhone via Messages. YouTube now lets you turn off Shorts I Made a Terminal Pager Burgers | マクドナルド公式 Commands — HackerNews CLI documentation ChatGPT for Excel PiCore - Raspberry Pi Port of Tiny Core Linux Live Nation illegally monopolized ticketing market, jury finds Google Broke Its Promise to Me. Now ICE Has My Data. Founding Engineer at Adaptional | Y Combinator CRISPR takes important step toward silencing Down syndrome’s extra chromosome GitHub - saffron-health/libretto: The AI toolkit for building reliable browser automations US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf] Retrofitting JIT Compilers into C Interpreters IPv6 – Google The Accursèd Alphabetical Clock Cybersecurity Looks Like Proof of Work Now Fragments: April 14 Cal.com Goes Closed Source: Why AI Security Is Forcing Our Decision | Cal.com - Scheduling Software for Online Bookings Laravel raised money and now injects ads directly into your agent When moving fast, talking is the first thing to break Too much Discussion of the XOR swap trick – Heather Cafe Introduction to Spherical Harmonics for Graphics Programmers The Grand Line Building a Z-Machine in the worst possible language High-Level Rust: Getting 80% of the Benefits with 20% of the Pain GitHub - duguyue100/midnight-captain: Inspired by Midnight Commander, tailored to my taste. How to build a `git diff` driver · Jamie Tanna | Software Engineer Center for Responsible, Decentralized Intelligence at Berkeley The Local Universe’s Expansion Rate Is Clearer Than Ever, but Still Doesn’t Add Up - A new synthesis of astronomical measurements confirms a persistent mismatch that could point to physics beyond current models The air throughout our homes is infused with microplastics. But there are things you can do to breathe less of them The disturbing white paper Red Hat is trying to erase from the internet – OSnews The Future of Everything is Lies, I Guess: Annoyances ‘Abhorrent’: the inside story of the Polymarket gamblers betting millions on war Productive procrastination — Max van IJsselmuiden maps, territory and LMs 447 Terabytes per Square Centimetre at Zero Retention Energy: Non-Volatile Memory at the Atomic Scale on Fluorographane Show HN: Pardonned.com – A searchable database of US Pardons 20 Years on AWS and Never Not My Job The Seasons are Wrong Artemis II crew splashes down near San Diego after historic moon mission We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs How a dancer with ALS used brainwaves to perform live On filing the corners off my MacBooks Installing every* Firefox extension OpenClaw’s memory is unreliable, and you don’t know when it will break Steve Blank Nowhere Is Safe Chimpanzees in Uganda locked in vicious 'civil war', say researchers watgo - a WebAssembly Toolkit for Go linux/Documentation/process/coding-assistants.rst at master · torvalds/linux GitHub - callumlocke/json-formatter: Makes JSON easy to read. Founding Product Engineer at Bild AI | Y Combinator A compelling title that is cryptic enough to get you to take action on it GitHub - Keychron/Keychron-Keyboards-Hardware-Design: Industrial design files for Keychron keyboards and mice. 100+ models with CAD assets in STEP, DXF, DWG, and PDF. Source-available, with commercial use allowed for original compatible accessories within the license terms. [ANNOUNCE] WireGuardNT v0.11 and WireGuard for Windows v0.6 Released 1D-Chess Helium Is Hard to Replace Cooperative Vectors Introduction | Evolve Keeping a Postgres queue healthy — PlanetScale Our response to the Axios developer tool compromise Do Americans read print books, e-books or audiobooks more? The Zettelkasten Method in Obsidian: A Practical Setup Guide Artemis II Is Competency Porn and We Are Starving For It WeakC4 Flight Viz — Cockpit View A Mexican surveillance giant you’ve never heard of is now watching the U.S. border Surelock: Deadlock-Free Mutexes for Rust RISC-V 101 – what is it and what does it mean for Canonical? | Ubuntu The Problem That Built an Industry How Much Linear Memory Access Is Enough? | Solidean Investigating Split Locks on x86-64 Simplest hash functions Sybilproof reputation mechanisms (2005) [pdf] What is a property? How Complex is my Code? Static code analysis in Kotlin — tools overview Toffoli gates are all you need PGLite evangelism dcmake: a new CMake debugger UI Clojure on Fennel part one: Persistent Data Structures Fragments: April 2 Python Release Python install manager 26.1 The Life and Death of the Book Review - Liberties Introducing Database Traffic Control — PlanetScale Bitcoin miners are losing $19,000 on every BTC produced as difficulty drops 7.8% God sleeps in the minerals Building slogbox Apple Silicon and Virtual Machines: Beating the 2 VM Limit Who was “Not Even Wrong” first? Pokemon Evolution Vs Darwinian Evolution The APL Programming Language Source Code
SQL: Incorrect by Construction
ingve · 2026-05-13 · via Hacker News

The design of SQL and relational database systems makes it easy to accidentally introduce serious concurrency bugs. Below is a textbook money-transfer procedure in TSQL; Alice wants to send ten dollars to Bob, and to keep Alice from overdrafting her account, we first check that she has enough money. The code looks completely reasonable, but it has several critical bugs. Can you spot them?

DECLARE @balance INT;

SET @balance = (  
    SELECT balance  
    FROM accounts
    WHERE owner = 'alice'
);

IF @balance >= 10  
BEGIN  
    UPDATE accounts  
    SET balance = balance - 10  
    WHERE owner = 'alice';  
  
    UPDATE accounts  
    SET balance = balance + 10  
    WHERE owner = 'bob';  
END

Atomicity

First, if this procedure aborts midway through, we might transfer money from Alice’s account without transferring any to Bob. Alice won’t be happy about that, and we’ve destroyed money in the process. We want all of the transfers to succeed, or none of them; the fix is to wrap the procedure in a transaction:

BEGIN TRANSACTION;

DECLARE @balance INT;

SET @balance = (  
    SELECT balance  
    FROM accounts
    WHERE owner = 'alice'
);

IF @balance >= 10  
BEGIN  
    UPDATE accounts  
    SET balance = balance - 10  
    WHERE owner = 'alice';  
  
    UPDATE accounts  
    SET balance = balance + 10  
    WHERE owner = 'bob';  
END

COMMIT TRANSACTION;

TOCTOU

Are we done yet? Not quite. Suppose Alice fires off two transfers to Bob in parallel, T1 and T2. Let’s map out what happens:

  1. T1: Check Alice’s account balance
  2. T2: Check Alice’s account balance
  3. T1: Withdraw 10 from Alice’s account
  4. T2: Withdraw 10 from Alice’s account
  5. T1: Deposit 10 in Bob’s account
  6. T2: Deposit 10 in Bob’s account

Note how T2 checks the balance before T1 has withdrawn any money from Alice’s account—so when T2 finally withdraws, the account might become overdrafted. This is a Time-of-check to time-of-use (TOCTOU) bug: The precondition changes between when we check it and when we act on it.

The fix is to lock Alice’s account until the transaction completes. We can change the isolation level so locks are acquired automatically, or lock the account row by hand:

BEGIN TRANSACTION;

DECLARE @balance INT;

SET @balance = (  
    SELECT balance
    -- This is roughly equivalent
    -- to SELECT FOR UPDATE
    FROM accounts WITH (UPDLOCK)
    WHERE owner = 'alice'
);

IF @balance >= 10  
BEGIN  
    UPDATE accounts  
    SET balance = balance - 10  
    WHERE owner = 'alice';  
  
    UPDATE accounts  
    SET balance = balance + 10  
    WHERE owner = 'bob';  
END

COMMIT TRANSACTION;

The UPDLOCK hint takes a row-level lock on Alice’s account when the SELECT runs; other transactions that want to modify Alice’s account will block until the lock is released.

Deadlocks

What if Alice and Bob both try to transfer money to each other at the same time? Let’s map out the transactions again:

  1. T1: Acquire a lock on Alice’s account
  2. T2: Acquire a lock on Bob’s account
  3. T1: Check Alice’s account balance
  4. T2: Check Bob’s account balance
  5. T1: Withdraw 10 from Alice’s account
  6. T2: Withdraw 10 from Bob’s account
  7. T1: Can’t update Bob’s account because it’s locked by T2
  8. T2: Can’t update Alice’s account because it’s locked by T1

T1 waits for T2’s lock on Bob; T2 waits for T1’s lock on Alice—we’re stuck in a deadlock. The fix is to acquire all locks upfront1:

BEGIN TRANSACTION;

DECLARE @balance INT;

SELECT owner
FROM accounts WITH (UPDLOCK)  
WHERE owner IN ('alice', 'bob');

SET @balance = (  
    SELECT balance
    FROM accounts
    WHERE owner = 'alice'
);

IF @balance >= 10  
BEGIN  
    UPDATE accounts  
    SET balance = balance - 10  
    WHERE owner = 'alice';  
  
    UPDATE accounts  
    SET balance = balance + 10  
    WHERE owner = 'bob';  
END

COMMIT TRANSACTION;

Conclusion

We’ve fixed the concurrency bugs in the original code, but in the process it grew about 50%, and became harder to read. Sure, you could argue that there are other, more idiomatic ways to fix this code2, but the point still stands: A SQL program that looks completely reasonable can be riddled with serious bugs.

If you’re building a social media site, it might not be the end of the world if a user likes a post twice, but if a system fails to record that a patient received a dose of medicine, it might have fatal consequences. For systems where correctness matters, we need better tools.

Proposed solution

I want an alternative to SQL that adopts Rust’s approach of fearless concurrency—that is, make the correct behavior the default, and provide “unsafe” escape hatches if necessary. Some concrete suggestions:

  • Make transactions atomic by default; if the user wants to save an intermediate “checkpoint” state they would have to say so explicitly.
  • Let the user manage locks themselves, and make sure the correct locks are acquired before mutating a database object.
  • Use static analysis to detect potential deadlocks; this is a tricky problem and a subject of ongoing research. Deterministic database systems could be one possible solution.

This system will come with other trade-offs; for example, it might end up with lower throughput than modern SQL systems. But that’s fine—we still have SQL for use cases where correctness is less important.


  1. The astute reader might have noticed that I did not include an ORDER BY clause when acquiring the row locks. You might think an ORDER BY is necessary to acquire locks in the right order, but here’s a “fun” fact: Locks are usually acquired in the order rows are read by the database, and not in the order they appear in the result. This means preventing all deadlocks can be impractical, or even impossible. ↩︎

  2. I intentionally wrote the example code the way a beginner might. More experienced users would probably reach for solutions like:

    • Updating and checking the balance in a single UPDATE
    • Using [check constraints][check-constraints] to ensure an account balance can never be negative.
     ↩︎