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

推荐订阅源

L
LINUX DO - 最新话题
G
Google Developers Blog
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
F
Full Disclosure
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
Help Net Security
Help Net Security
The Hacker News
The Hacker News
IT之家
IT之家
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V
Visual Studio Blog
博客园 - 聂微东
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
Google DeepMind News
Google DeepMind News
Cloudbric
Cloudbric
N
News | PayPal Newsroom
A
About on SuperTechFans
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hugging Face - Blog
Hugging Face - Blog
M
MIT News - Artificial intelligence
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
罗磊的独立博客
K
Kaspersky official blog
The Cloudflare Blog
I
Intezer

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Race-Condition: How a Single SQL Line Eliminated 100 Lines of Retry and Lock Code
Allan Bontem · 2026-05-27 · via DEV Community

hat "rare" bug that looks intermittent but is actually deterministic. It is just waiting for your pods to scale.

I recently dealt with a textbook concurrency issue in a Java application running on multiple parallel instances, and the solution turned out to be much simpler than the workarounds we had piled on top of it. This is a walkthrough of the problem, the failed attempts, and the final fix, with code and diagrams so you can apply the same pattern.

The Setup

The application stack:

. Java with Quarkus and Hibernate (Panache)
. Oracle as the relational database
. Deployed on Kubernetes with 4 parallel pods consuming from a JMS queue
. Each message triggers the creation of a record inside a parent entity, with a sequential number that resets per parent

To keep things generic, think of it as "items inside an order":

. Each order can have multiple items
. Each item has a sequential number within the order (1, 2, 3, ...)
. The numbering restarts at 1 for every new order
. The primary key is composite: (order_id, item_number)

The application had been running this way for years with a single instance. When the deployment scaled to four pods, primary key violations started showing up in production, intermittent and hard to reproduce.

The Root Cause: SELECT MAX + 1

Here is the original code (simplified):

public Long nextItemNumber(Long orderId) {
    return em.createQuery(
            "select max(i.itemNumber) from Item i where i.orderId = :orderId",
            Long.class)
        .setParameter("orderId", orderId)
        .getSingleResultOrNull()
        .map(last -> last + 1L)
        .orElse(1L);
}

Enter fullscreen mode Exit fullscreen mode

A textbook SELECT MAX + 1 pattern. The problem: SELECT acquires no lock. Two pods can query at exactly the same moment, get the same value, and both try to insert the same number.

This worked for years with a single instance because there was no concurrency. The bug was always there. It just never had a chance to manifest.

First Attempt: Pessimistic Lock + Retry

The first fix tried to add coordination between the pods using a pessimistic lock on the parent row, plus a retry on the duplicate exception.

@Retry(maxRetries = 4, delay = 5, retryOn = DuplicateItemException.class,
       delayUnit = ChronoUnit.SECONDS)
@Transactional
public Item createItem(Long orderId, ItemPayload payload) {
    // 1) Lock the parent row
    em.createNativeQuery("""
        SELECT * FROM orders
        WHERE id = :id
        FOR UPDATE WAIT 5
        """)
        .setParameter("id", orderId)
        .getSingleResult();

    // 2) Get next number
    Long nextNumber = nextItemNumber(orderId);

    // 3) Insert the item
    try {
        return persist(Item.builder()
            .orderId(orderId)
            .itemNumber(nextNumber)
            .payload(payload)
            .build());
    } catch (PersistenceException e) {
        if (isUniqueViolation(e)) {
            throw new DuplicateItemException(e);
        }
        throw e;
    }
}

Enter fullscreen mode Exit fullscreen mode

It reduced the frequency of failures, but did not eliminate them. Under high concurrency:

. WAIT 5 would time out, throwing LockTimeoutException
. Retries piled up, with 5-second delays adding latency
. After exhausting all retries, the operation still failed
. Code complexity increased: a custom exception, retry annotation, unique-violation detection logic, error handling

The fundamental problem was still there: SELECT MAX + 1 is a "read then write" pattern, and the lock was only mitigating the symptom, not removing the race.

The Solution: Atomic UPDATE ... RETURNING

The final solution was to add a counter column on the parent table and use an atomic UPDATE ... RETURNING to generate the next number in a single operation.

Schema change

ALTER TABLE orders
ADD last_item_number NUMBER(4,0) DEFAULT 0 NOT NULL;

-- Backfill for existing rows
UPDATE orders o
SET o.last_item_number = (
    SELECT NVL(MAX(i.item_number), 0)
    FROM items i
    WHERE i.order_id = o.id
);
COMMIT;

Enter fullscreen mode Exit fullscreen mode

Semantics:

. The column stores the last number used (not "the next to use")
. New orders start at 0 (no items created)
. Each UPDATE increments and returns the new value, which is the number to assign

Code change

@Transactional
public Long nextItemNumber(Long orderId) {
    return ((Number) em.createNativeQuery("""
            UPDATE orders
            SET last_item_number = last_item_number + 1
            WHERE id = :orderId
            RETURNING last_item_number INTO :next
            """)
        .setParameter("orderId", orderId)
        .getSingleResult()).longValue();
}

Enter fullscreen mode Exit fullscreen mode

That is the whole thing. Single statement, atomic by design.

Why It Works: The Mechanics of UPDATE Locking

There are three properties that make this pattern bulletproof:

1. UPDATE acquires an automatic X-lock

When you UPDATE a row in Oracle (and most relational databases), the engine automatically acquires an exclusive lock on that row. Two concurrent transactions targeting the same row serialize by design, without any explicit FOR UPDATE.

2. The lock is re-evaluated after waiting

When Pod B unblocks (because Pod A committed), Oracle re-evaluates SET counter = counter + 1 using the committed value. So Pod B sees 4 (committed by A) and produces 5. It does not use the value it saw before being blocked.

3. RETURNING is atomic with the update

The value returned is the post-update value, computed in the same statement. There is no window between "increment" and "read the new value" where another transaction could interfere.

Compare this with the SELECT MAX + 1 pattern, which separates the read and the write into two steps with no protection between them.

SELECT MAX + 1 UPDATE counter + 1 RETURNING
Acquires lock No Yes, automatic
Serializes? No Yes, on the row
Two pods can get same value Yes No
Detects conflict At INSERT (constraint violation) Never (no conflict possible)

Bonus Layer: Eliminating Redis Dependency

The same application had another counter being generated through Redis (INCR on a key formatted as "{order_id}/{item_number}"). This was used for a secondary sequential number inside each item.

That counter had similar problems:

. No transactional atomicity with the database: if the INSERT rolled back, the Redis INCR did not roll back. Result: gaps in the sequence (burned numbers).
. Manual reconciliation logic: a periodic check tried to detect divergence between Redis and the database and fix it. The reconciliation had bugs and missed certain edge cases.
. Critical dependency in the hot path: if Redis was unavailable, the consumer was stuck even when the database was healthy.

The same counter pattern applied to the secondary table eliminated all of that:

ALTER TABLE items
ADD last_subitem_number NUMBER(3,0) DEFAULT 0 NOT NULL;

Enter fullscreen mode Exit fullscreen mode

@Transactional
public Integer nextSubItemNumber(Long orderId, Long itemNumber) {
    return ((Number) em.createNativeQuery("""
            UPDATE items
            SET last_subitem_number = last_subitem_number + 1
            WHERE order_id = :orderId AND item_number = :itemNumber
            RETURNING last_subitem_number INTO :next
            """)
        .setParameter("orderId", orderId)
        .setParameter("itemNumber", itemNumber)
        .getSingleResult()).intValue();
}

Enter fullscreen mode Exit fullscreen mode

Redis is now used only for caching reference data, not for generating unique IDs in the transactional path.

What Got Removed

After applying the pattern in both layers, the following code disappeared:

. DuplicateItemException class
. @Retry annotation on the creation method
. Custom isUniqueViolation detection logic
. Try/catch wrapping the INSERT to convert exceptions
. Redis dependency for sequential generation (still used for caching)
. Reconciliation method that compared Redis state with the database (a routine with edge cases that needed maintenance)
. Configuration properties related to Redis TTL for these counters
. Approximately 100 lines of error handling and ceremony

The code that remained is more declarative and easier to reason about. The race condition is gone, not by mitigation but by design.

When NOT to Use This Pattern

This is not a silver bullet. The pattern works well when:

. The number you are generating belongs to a clear "parent" entity that already exists in the database
. The numbering is scoped to that parent (resets per parent)
. The transaction boundary fits naturally around the increment and the insert
. You can afford serialization on the parent row (concurrent creates within the same parent serialize)

It does not fit when:

. The ID needs to be generated before any database row exists (consider snowflake, UUID v7, or external sequence)
. You need globally unique IDs across all entities (use a sequence, not a counter)
. The serialization overhead on the parent row is unacceptable for your workload (rare, but possible in extreme scenarios where you would need application-level sharding anyway)

For the common case of "sequential numbers inside a parent entity in a multi-instance application," the counter column with atomic UPDATE is hard to beat.

Takeaways

A lot of race conditions in legacy systems trace back to SELECT MAX + 1 inherited from single-instance days. The cost of patching with explicit locks and retries is high and never fully resolves the underlying issue.

A well-placed counter column with UPDATE ... RETURNING is:

. Simpler: one SQL statement replaces a multi-step routine
. Safer: serialization is guaranteed by the database, not by application logic
. Faster: no retry latency, no lock timeout cascades
. More transparent: the intent is clear in the code

Relational databases were designed for this pattern decades ago. Before reaching for distributed locks, queues, or eventual consistency, it is worth checking whether the database already has the tools to solve the problem natively. In many cases, it does.

References

. Oracle documentation on UPDATE ... RETURNING INTO: docs.oracle.com
. Oracle row-level locking behavior: Concepts Guide
. Martin Kleppmann on the limits of distributed locks (Redlock): martin.kleppmann.com
. MicroProfile Fault Tolerance specification: microprofile.io


If you have dealt with similar concurrency issues in your projects, what was your solution? Did you go with a database-native approach or a distributed lock?