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

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Optimistic Locking in Postgres: Stop Losing Data to Race Conditions
The Practica · 2026-05-13 · via The Practical Developer

Your user opens an order edit page. Their coworker opens the same page. Both change the shipping address. Both hit Save.

The API handles the first request: reads the row, merges the patch, writes it back. The API handles the second request a millisecond later: reads the same original row (because the first write is not yet visible or because the ORM re-fetched the old state), merges a different patch, writes it back. The first user’s change is gone. No error. No log. Just a support ticket tomorrow that reads “my edit disappeared.”

This is not a theoretical race condition. It is the default behavior of most read-modify-write APIs. If your UPDATE statement sets columns to literal values derived from a previous SELECT, the last writer wins every time.

Pessimistic locking with SELECT ... FOR UPDATE fixes the overwrite, but it holds a row lock for the entire transaction. Under load that becomes contention, waits, and deadlocks. Optimistic locking fixes the same problem with zero lock time. The database does the collision detection; your API decides what to do about it.

This post shows the working pattern: a version column, a compare-and-swap UPDATE, a 409 response the client can retry, and a test that proves the race is closed.

The demo: a race condition in 20 lines

Here is the dangerous pattern, wrapped in Express and plain SQL. It looks correct until two requests arrive at the same time.

app.patch('/api/orders/:id', async (req, res) => {
  const { id } = req.params;
  const { shipping_address } = req.body;

  // DANGER: this read is not bound to the write.
  const { rows: [existing] } = await pool.query(
    'SELECT * FROM orders WHERE id = $1',
    [id]
  );

  if (!existing) return res.status(404).end();

  const merged = { ...existing, shipping_address };

  await pool.query(
    'UPDATE orders SET shipping_address = $1 WHERE id = $2',
    [merged.shipping_address, id]
  );

  res.json(merged);
});

Run two PATCH requests in parallel with different addresses. Both read the old row. Both write back different values. The last UPDATE clobbers the first. Postgres did exactly what it was told.

The fix is not “add a transaction.” A transaction around the read and write does not help unless the read holds a lock, which is what we are trying to avoid.

Add a version column

Optimistic locking stores a counter on every row. Every successful UPDATE increments it. The UPDATE clause includes a WHERE version = $knownVersion check. If the row changed since the read, the version no longer matches, zero rows are updated, and the application knows a collision happened.

ALTER TABLE orders ADD COLUMN version INTEGER NOT NULL DEFAULT 1;

-- Backfill existing rows with distinct values so they are not all 1.
UPDATE orders SET version = id WHERE version = 1;

Use an integer, not a timestamp. updated_at can collide if two writes happen in the same millisecond, and clock_timestamp() behavior across transaction boundaries is subtle. Integers are simple and deterministic.

The compare-and-swap update

The UPDATE now carries the version the client read:

UPDATE orders
SET shipping_address = $1,
    version = version + 1
WHERE id = $2
  AND version = $3
RETURNING *;

If RETURNING returns a row, the write succeeded and the version advanced. If it returns nothing, the row changed between read and write. The API returns a 409 Conflict, and the caller can retry from the top with fresh data.

Here is the safe API handler:

app.patch('/api/orders/:id', async (req, res) => {
  const { id } = req.params;
  const { shipping_address, expected_version } = req.body;

  if (typeof expected_version !== 'number') {
    return res.status(400).json({
      error: 'expected_version is required for optimistic locking',
    });
  }

  const { rows } = await pool.query(
    `UPDATE orders
     SET shipping_address = $1,
         version = version + 1
     WHERE id = $2
       AND version = $3
     RETURNING *`,
    [shipping_address, id, expected_version]
  );

  if (rows.length === 0) {
    return res.status(409).json({
      error: 'Conflict',
      detail: 'The order was modified by another request. Please re-fetch and retry.',
    });
  }

  res.json(rows[0]);
});

The client reads the order, remembers version, sends the patch including expected_version, and handles 409 by re-fetching and replaying the user’s intent on fresh data. This is exactly what idempotency keys solve for retries; if you already have an idempotency system, the retry is free. If not, the user sees a clear message instead of a silent overwrite.

Why not use SELECT ... FOR UPDATE?

Pessimistic locking works, but it keeps the row locked until commit. In a busy system that is expensive.

BEGIN;
SELECT * FROM orders WHERE id = $1 FOR UPDATE;
-- ... application logic ...
UPDATE orders SET shipping_address = $1 WHERE id = $2;
COMMIT;

If the application logic involves calling another service, validating a payment, or rendering a PDF, that row is locked the entire time. Other requests for the same order wait. Under load, waits become deadlocks, and deadlocks become retries that add more load.

Optimistic locking assumes collisions are rare. It reads without a lock, does the work, and attempts the write. If a collision happens, the application retries. The database is never held hostage by a slow business rule.

Use pessimistic locking when contention is high and the operation is fast: decrementing inventory, deducting credits, assigning a sequential number. Use optimistic locking when contention is low and the operation is long: editing a CRM record, updating a project plan, saving a draft document.

Handling the retry loop

The simplest client retry is re-read, re-apply, re-submit. But if the client is a browser, pushing that logic to the server gives a cleaner API contract.

Here is a server-side wrapper that retries transparently up to a limit. The caller gets a normal 200 or a 409 if the collision rate is pathological.

async function patchOrderWithRetry(pool, id, patch, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const { rows } = await pool.query(
      'SELECT version, shipping_address FROM orders WHERE id = $1',
      [id]
    );

    if (rows.length === 0) {
      const e = new Error('Not found');
      e.status = 404;
      throw e;
    }

    const { version, shipping_address } = rows[0];
    const merged = { shipping_address, ...patch };

    const update = await pool.query(
      `UPDATE orders
       SET shipping_address = $1,
           version = version + 1
       WHERE id = $2
         AND version = $3
       RETURNING *`,
      [merged.shipping_address, id, version]
    );

    if (update.rows.length > 0) {
      return update.rows[0];
    }

    // Sleep with jitter so thundering retries do not amplify.
    const backoff = Math.min(100 * 2 ** attempt, 500);
    const jitter = Math.floor(Math.random() * 50);
    await new Promise((r) => setTimeout(r, backoff + jitter));
  }

  const e = new Error('Conflict');
  e.status = 409;
  throw e;
}

The retry limit matters. If three writers are slamming the same row in a tight loop, transparent retry hides a hot object. After the limit, surface the 409 so an operator or the user can investigate.

Testing that the race is closed

A unit test that calls the handler twice sequentially proves nothing. The bug only appears under concurrency. The test must fire both requests in parallel and assert that both changes are visible, or that one is rejected with a 409.

import assert from 'node:assert/strict';
import { fork } from 'node:child_process';

async function raceTest(pool, baseUrl) {
  // Seed one order.
  const { rows: [order] } = await pool.query(
    `INSERT INTO orders (shipping_address, version)
     VALUES ('Old Street', 1)
     RETURNING id, version`
  );

  // Fire two patches simultaneously.
  const a = fetch(`${baseUrl}/api/orders/${order.id}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      shipping_address: 'Address A',
      expected_version: order.version,
    }),
  });

  const b = fetch(`${baseUrl}/api/orders/${order.id}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      shipping_address: 'Address B',
      expected_version: order.version,
    }),
  });

  const [resA, resB] = await Promise.all([a, b]);

  const statuses = [resA.status, resB.status].sort();
  const bodies = await Promise.all([resA.json(), resB.json()]);

  // One must succeed, the other must conflict (or both succeed on retry).
  // For this test we expect exactly one 200 and one 409 without server retries.
  assert.deepStrictEqual(statuses, [200, 409]);

  // Verify the database holds the winner's write, not a merge or the original.
  const { rows: [final] } = await pool.query(
    'SELECT shipping_address, version FROM orders WHERE id = $1',
    [order.id]
  );

  assert.ok(
    final.shipping_address === 'Address A' || final.shipping_address === 'Address B',
    `unexpected final value: ${final.shipping_address}`
  );
  assert.strictEqual(final.version, 2);
}

Run with node --test or Jest using multiple workers. If the old code is in place, both requests return 200 and the final address is either A or B, whichever wrote last. With optimistic locking, exactly one writer wins, the other gets a 409, and the database version is 2.

Composite updates across tables

What if saving an order also updates line items, billing, and audit logs? You need a single version that protects the whole aggregate. Options:

  1. Version on the parent only. Update orders.version + 1 inside a transaction, then insert/update children without version checks. The parent version guarantees no other process mutated the order while you worked. This is the normal pattern.

  2. Version on every child table. Needed only if children have independent concurrent lifecycles. Most systems do not need this complexity.

  3. Use a xmax trick for child tables. Postgres exposes the internal xmax system column, which holds the ID of the deleting transaction (0 for current rows). It changes on every UPDATE, so SELECT xmax, * FROM line_items gives you a free optimistic lock token without adding a column. This is elegant but non-portable and harder to reason about. Prefer explicit version columns for application code.

-- Parent-only version is usually enough.
BEGIN;
UPDATE orders SET version = version + 1 WHERE id = $1 AND version = $2;
-- inserts/updates to line_items, billing, etc.
COMMIT;

If the parent UPDATE affects zero rows, roll back and return 409. No child work happens after a stale read.

The xmax alternative: free locking with system columns

If you cannot add a column to a legacy table, xmax is a usable escape hatch. It is not a user column; it is the transaction ID of the tuple’s deleting or updating transaction. It changes on every UPDATE or DELETE.

SELECT xmax, * FROM orders WHERE id = 42;
-- returns xmax = 0, id = 42, shipping_address = 'Old Street'

-- later, another session updates the row.

SELECT xmax, * FROM orders WHERE id = 42;
-- returns xmax = 123456, ...

You can pass xmax as the optimistic lock token the same way you pass version. The UPDATE still increments xmax implicitly. The client re-reads and compares.

The downsides: xmax is not part of your schema, so it is invisible to ORM mappings. It wraps around in long-lived databases. It is implementation-specific to Postgres. Do not build a cross-database product on it. Use it only as a short-term patch on a table you cannot migrate yet.

When optimistic locking is the wrong choice

Optimistic locking fails when collisions are frequent. A counter that every request hits, a seat inventory table during a flash sale, or a rate-limit bucket: these are high-contention objects. With optimistic locking, almost every write collides, and retries burn CPU without making progress.

For those cases, use a single atomic operation that does the math server-side:

UPDATE inventory
SET quantity = quantity - $1
WHERE id = $2
  AND quantity >= $1;

If quantity changed under you, the WHERE clause fails. But the check is part of the business rule, not a separate version token. A retry is unnecessary because the operation is self-contained and atomic.

Similarly, UPDATE ... SET counter = counter + 1 needs no lock token; Postgres makes the increment atomic. Optimistic locking is for read-modify-write sequences where the new value depends on external input or complex logic, not for arithmetic deltas.

Production guardrails

Add the version to your API contract. Every GET response should include it. Every PATCH or PUT should require it. If an old client forgets to send it, fail fast with a 400. Silent fallback to last-write-wins is the bug you are trying to eliminate.

// Include version in every read response.
res.json({
  id: order.id,
  shipping_address: order.shipping_address,
  version: order.version,
});

Add a metric for 409 responses. A low rate means the system is healthy. A spike means a hot object or a client bug that re-submits without re-reading.

if (update.rows.length === 0) {
  conflictCounter.inc({ resource: 'orders' });
  return res.status(409).json({ ... });
}

Set an alert on 409 rate per endpoint. A sudden jump is often the first symptom of a UI that auto-saves drafts and does not refresh state between edits.

The practical workflow

When a read-modify-write API loses data under concurrency:

  1. Identify the read and the write. If they are separate queries, the race exists.
  2. Add an integer version column, default 1, backfill with unique values.
  3. Change UPDATE to WHERE id = $1 AND version = $2, add version = version + 1, and RETURNING.
  4. Return 409 when zero rows are updated.
  5. Make the client re-read and retry, or add server-side retry with a limit.
  6. Test with parallel requests, not sequential ones.
  7. Alert on 409 rate to detect pathological contention.

The fix is usually three lines of SQL and a status code. The hard part is admitting that the overwrite was there all along.

A note from Yojji

Patterns like optimistic locking, compare-and-swap updates, and safe retry loops are the kind of backend precision work that separates a prototype from a production-grade system. Most teams only discover the gap after silent data loss shows up in support tickets.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. Their engineers build custom web applications and scalable microservices with the same attention to data integrity, concurrency safety, and operational observability that keeps systems correct under real traffic.