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

推荐订阅源

博客园_首页
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
Y
Y Combinator Blog
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
S
SegmentFault 最新的问题
IT之家
IT之家
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
WordPress大学
WordPress大学
博客园 - Franky
L
LangChain Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 叶小钗
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
雷峰网
雷峰网
腾讯CDC
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Help Net Security
Help Net Security
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
N
News and Events Feed by Topic
V2EX - 技术
V2EX - 技术
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Schneier on Security
Schneier on Security
博客园 - 聂微东
A
Arctic Wolf
H
Heimdal Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
C
Cyber Attacks, Cyber Crime and Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google DeepMind News
Google DeepMind News

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
Laravel RateLimiter and a race condition
Vladislav Ra · 2026-05-14 · via DEV Community

The standard rate-limiting pattern from the Laravel docs looks like this:

if (RateLimiter::tooManyAttempts('send-message:'.$user->id, $maxAttempts = 5)) {
    return 'Too many attempts!';
}

RateLimiter::hit('send-message:'.$user->id);

// Send message...

Enter fullscreen mode Exit fullscreen mode

It works fine. Right up until someone hits an endpoint capped at 5 requests per minute with 100 concurrent requests. Then all 100 get through.

I ran into this race condition while building rate limiting for captchaapi.eu, a PoW CAPTCHA API. Credit goes to @_newtonjob, who nailed it in 280 characters in a post on X:

Your Ratelimiting logic works until someone fires 100 concurrent requests on an endpoint that should be limited to 5 requests per minute.
The fix: Ensure you/your agents also check the incremented count returned by RateLimiter::hit() and that it doesn't exceed the max attempts.

Here's why it's a problem, the one-line fix, and what I took away from it.

Why is it a problem?

Walk through what happens on a single request:

  1. tooManyAttempts() reads the current count from cache
  2. Compares it against $maxAttempts
  3. Returns true or false
  4. If false, the code calls hit(), which increments the count

That's two independent cache calls. Between step 1 and step 4 there's a window, usually a few microseconds, where another request can read the same stale value, pass the check, and increment too.

At 100 concurrent requests it happens at scale:

  • Request 1 reads count = 0, passes the check (0 < 5), calls hit() → count = 1
  • Request 2 reads count = 0 (at the same instant), passes the check, calls hit() → count = 2
  • ...and so on for all 100

The counter ends up at 100, but all 100 requests already ran, and your backend just processed 100x the work you wanted. If the endpoint does something expensive (a PoW challenge, AI inference, an external API call), you just paid for 100 operations instead of 5.

Why the increment is atomic but the check isn't

If you crack open Laravel's source (Illuminate\Cache\RateLimiter::increment() in 12.x):

public function increment($key, $decaySeconds = 60, $amount = 1)
{
    $key = $this->cleanRateLimiterKey($key);

    $this->cache->add(
        $key.':timer', $this->availableAt($decaySeconds), $decaySeconds
    );

    $added = $this->withoutSerializationOrCompression(
        fn () => $this->cache->add($key, 0, $decaySeconds)
    );

    $hits = (int) $this->cache->increment($key, $amount);

    // ...

    return $hits;
}

Enter fullscreen mode Exit fullscreen mode

And hit() is just an alias for increment():

public function hit($key, $decaySeconds = 60)
{
    return $this->increment($key, $decaySeconds);
}

Enter fullscreen mode Exit fullscreen mode

The important part is $this->cache->increment($key, $amount). That's an atomic operation in the cache backend.

I use Redis in captchaapi.eu, where it maps to INCR (or INCRBY), one of the oldest, most battle-tested commands in Redis. It's atomic at the single-key write level: no two concurrent requests will read the same value, and each one gets a unique incremented result back. Memcached has an equivalent incr with the same guarantees.

Here's the key thing: hit() returns the count after the increment. The return value is atomic, deterministic, and unique for every concurrent caller.

$hits = RateLimiter::hit($key);
// With 100 concurrent requests you get return values 1, 2, 3, ..., 100
// (in random order, but each value exactly once)

Enter fullscreen mode Exit fullscreen mode

tooManyAttempts(), on the other hand, is a separate read. It can return a stale value, and the gap between that read and the next write is your race window.

The fix: one increment, check the return value

Drop the two-step pattern (tooManyAttemptshit) and do it in one:

$attempts = RateLimiter::hit('send-message:'.$user->id);

if ($attempts > $maxAttempts) {
    return 'Too many attempts!';
}

// Send message...

Enter fullscreen mode Exit fullscreen mode

Now with 100 concurrent requests:

  • Each request gets a unique count after the increment
  • The first 5 get values 1–5 and pass
  • The remaining 95 get values 6–100 and get rejected

No window, no race. Redis's atomic increment is the single source of truth, and hit() gives you that truth directly.

One subtle thing worth pointing out: in the original pattern, the increment happens after the check, so any overshoot stays in the counter ("the counter shows 6 even though we didn't want to allow request #6"). In the new pattern you increment every time and check the return value, so the counter might show 100. That's fine, because anything over the limit got rejected. The counter readout looks the same, but the security model is stricter.

hit() vs. increment(): which one?

They do the same thing. hit() is just increment() with amount = 1. Pick whichever reads better:

  • hit() for "register one event," the natural fit for rate limiting
  • increment() when you want to emphasize the atomic-counter aspect or bump by more than 1

In captchaapi.eu I went with increment() because it makes it obvious I care about the return value, not the side effect.

Where this doesn't help

One honest limitation: this protects against the race within a single Redis instance (or a Redis cluster, where each key lives on one shard). If you had Redis split across regions without coordination and an attacker fired requests at every region, INCR's atomicity wouldn't save you. You'd get 100 requests per region, times N regions.

For captchaapi.eu this is plenty, because the whole app runs against a single Redis (Hetzner Nuremberg). For multi-region distributed rate limiting you'd need something like a sliding window log or a token bucket with a centralized source of truth. Different topic.

The other limit: this is a fix for counter-level races. If an attacker rotates IPs (botnet, residential proxy), no per-IP rate limit will stop them. That's a fundamentally different problem, and in captchaapi.eu I handle it with the PoW challenge itself.

What I took away

A small fix, but a few things clicked for me that hadn't before.

1. "It works" is not the same as "it's secure." I had the original docs pattern running in production for a while and never saw a bug, because no attacker had shown up at captchaapi.eu yet. These races are quiet. Application logs say nothing, monitoring shows green, and you only find out the limit never actually held when someone with wrk -c 100 decides to take a look. Now any time I review code that rate-limits an expensive operation, I start with: "What happens if 100 requests arrive in the same microsecond?"

2. Return values from atomic operations are code you don't have to write. Redis hands you a unique sequence number for free with every atomic increment. You can use it for rejection, sure, but also for other business logic you'd otherwise solve with more code and more locks. Calling tooManyAttempts() and ignoring hit()'s return value means throwing away information Redis already gave you.

3. The standard pattern in the docs isn't always the best one. The Laravel docs still show tooManyAttempts() + hit() across every version from 8.x through 12.x. It isn't wrong. For most web apps (per-user limits, where users don't realistically make 100 concurrent requests) it's fine. But if you're building a public API where parallel abuse is the threat model, the docs aren't showing you the safest option. I read documentation a bit differently now: "Who's the assumed user here, and does their threat model match mine?"

4. X is where I pick up security gotchas. This particular fix reached me through a 280-character post from @_newtonjob, not through the docs or a security audit. Following Laravel folks who share concrete pattern-level bugs from real apps has done more for me than most security blog posts. Keep people in your feed who write "I hit X, fixed it like this." That's exactly the kind of pattern matching you need for your own code. Thanks, @_newtonjob.

TL;DR

// ❌ Race-prone — 100 concurrent requests will all get through
if (RateLimiter::tooManyAttempts($key, 5)) {
    return 'Too many!';
}
RateLimiter::hit($key);

// ✅ Race-safe — atomic increment + check the return value
if (RateLimiter::hit($key) > 5) {
    return 'Too many!';
}

Enter fullscreen mode Exit fullscreen mode

One line shorter, one problem gone. If you've got a Laravel rate limiter using the tooManyAttempts() + hit() pattern, go through it and rewrite to the single-call variant. Especially if you're protecting an endpoint where every call costs you something.