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

推荐订阅源

D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
T
The Blog of Author Tim Ferriss
罗磊的独立博客
The Register - Security
The Register - Security
IT之家
IT之家
D
Docker
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
L
LangChain Blog
J
Java Code Geeks
博客园 - 三生石上(FineUI控件)
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
Kaspersky official blog
Latest news
Latest news
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
人人都是产品经理
人人都是产品经理
C
CERT Recently Published Vulnerability Notes
The Hacker News
The Hacker News
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
MongoDB | Blog
MongoDB | Blog
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
DataBreaches.Net
Project Zero
Project Zero
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Check Point Blog
S
Schneier on Security
NISL@THU
NISL@THU
T
Tor Project blog
P
Proofpoint News Feed
N
News and Events Feed by Topic
Last Week in AI
Last Week in AI
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 最新话题
Help Net Security
Help Net Security
Blog — PlanetScale
Blog — PlanetScale

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
Rate Limiting Like a Jedi: Mastering the Token Bucket with Redis
Timevolt · 2026-06-16 · via DEV Community

The Quest Begins (The “Why”)

Picture this: I’m huddled over my laptop at 2 a.m., eyes glazed, watching the metrics dashboard flash red like the Death Star’s super‑laser charging up. Our API is getting hammered by a burst of traffic from a misbehaving mobile client, and every request is punching straight through to the database. The DB starts to groan, latency spikes, and suddenly we’re serving 500s like they’re going out of style.

I’d tried slapping a simple per‑process counter on each server—just increment a variable in memory and reject when it crosses a threshold. It felt like trying to stop a horde of Stormtroopers with a cardboard shield. When we scaled out to three instances, each node had its own limit, so the effective ceiling tripled, and we still got slammed. Worse, when a node restarted, the counter reset and we opened the floodgate again.

I needed a solution that felt like wielding the Force: one unified view of traffic that works no matter how many instances we spin up, survives restarts, and doesn’t require a PhD in distributed systems to understand. That’s when I remembered the token bucket algorithm—an old school trick that, when paired with Redis, becomes a lightsaber for rate limiting.

The Revelation (The Insight)

The token bucket is beautifully simple: imagine a bucket that holds a fixed number of tokens. Tokens leak in at a steady rate (the refill rate). Each request consumes a token; if the bucket is empty, the request is rejected. If the bucket has tokens, we let the request through and remove one.

What makes this a game‑changer for backend services?

Property Naïve per‑process counter Token bucket + Redis
Global view No – each instance has its own limit Yes – single source of truth in Redis
Survives restarts Lost – counter resets to zero Persisted – Redis holds the bucket state
Burst handling Poor – you either allow too much or too little Configurable burst via bucket size
Complexity Trivial but broken Small Lua script, still easy to reason about
Performance O(1) in‑memory, but inaccurate O(1) Redis call (still lightning fast)

The critical insight was realizing that we don’t need to reinvent the wheel; we just need to store the bucket’s state somewhere that all nodes can atomically update. Redis gives us that with O(1) operations and built‑in expiration, plus we can wrap the logic in a Lua script to guarantee atomicity (no race conditions between checking the token count and decrementing it).

In movie terms, it’s like Neo finally seeing the Matrix code: once you spot the underlying pattern (tokens flowing in and out), the chaos of traffic spikes becomes predictable and controllable.

Wielding the Power (Code & Examples)

The Struggle: A Broken Per‑Instance Counter

# flask app – before (the dark side)
from flask import Flask, request, abort
import time

app = Flask(__name__)
REQUEST_LIMIT = 100          # max requests per window
WINDOW_SECONDS = 60
_counters = {}               # ip -> (count, reset_time)

def allow(ip):
    now = time.time()
    count, reset = _counters.get(ip, (0, now + WINDOW_SECONDS))
    if now > reset:          # window expired
        count, reset = 0, now + WINDOW_SECONDS
    if count >= REQUEST_LIMIT:
        return False
    _counters[ip] = (count + 1, reset)
    return True

@app.route('/api/data')
def data():
    if not allow(request.remote_addr):
        abort(429, description="Too many requests")
    return {"msg": "here be dragons"}

What went wrong?

  • Each Flask worker gets its own _counters dict.
  • When we horizontally scale behind a load balancer, the limit multiplies.
  • Restarting the wipes the dict clean—boom, free‑for‑all.

The Victory: Token Bucket Powered by Redis

First, we install redis and redis-py. Then we write a tiny Lua script that does the check‑and‑consume atomically:

-- token_bucket.lua
local key = KEYS[1]               -- e.g. "rate_limit:user_id:123"
local capacity = tonumber(ARGV[1])-- bucket size (burst)
local refill_rate = tonumber(ARGV[2]) -- tokens per second
local now = tonumber(ARGV[3])     -- current Unix timestamp (float)

local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = tonumber(bucket[1]) or capacity
local last_refill = tonumber(bucket[2]) or now

-- refill based on elapsed time
local delta = math.max(0, now - last_refill)
tokens = math.min(capacity, tokens + delta * refill_rate)

if tokens < 1 then
    -- not enough tokens -> reject
    return {0, tokens}   -- allowed=0, tokens left (may be fractional)
end

tokens = tokens - 1
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
redis.call('EXPIRE', key, math.ceil(capacity / refill_rate) + 2) -- auto‑clean
return {1, tokens}       -- allowed=1, tokens left

Now the Python side becomes a breeze:

import time
import redis
from flask import Flask, request, abort

app = Flask(__name__)
r = redis.Redis(host='redis', port=6379, db=0)

LUA_SCRIPT = """
-- (paste the Lua script above)
"""
SCRIPT_SHA = r.script_load(LUA_SCRIPT)

def allow(user_id, capacity=100, refill_rate=10):
    """
    Returns True if request is allowed.
    capacity   = max burst size (tokens)
    refill_rate = tokens added per second
    """
    now = time.time()
    allowed, tokens_left = r.evalsha(
        SCRIPT_SHA,
        1,
        f"rate_limit:{user_id}",
        capacity,
        refill_rate,
        now
    )
    return bool(allowed)

@app.route('/api/data')
def data():
    user_id = request.args.get('uid', 'anon')
    if not allow(user_id, capacity=100, refill_rate=10):
        abort(429, description="Too many requests – slow down, young Padawan")
    return {"msg": "Data fetched, Force is with you"}

Why this beats the naive approach:

  • Atomicity – The Lua script guarantees that the check‑and‑decrement happens as one indivisible Redis operation, eliminating the classic “check‑then‑act” race condition.
  • Global visibility – All API servers read/write the same key, so the limit truly applies across the cluster.
  • Automatic cleanup – The EXPIRE call removes stale keys after they’re idle, preventing memory leaks.
  • Configurable burst – Want to allow a short spike? Just raise capacity. Need a smoother throttle? Lower refill_rate.

Common Traps (The “Dark Side” Temptations)

  1. Forgetting to make the script atomic – If you split the GET and SET into two separate Redis calls, you open a window where two requests could both see tokens > 0 and both decrement, over‑consuming the bucket. Always wrap the logic in Lua (or use Redis 7’s FCALL with EVALSHA).

  2. Using a TTL that’s too short – If you expire the key after, say, 30 seconds while your refill rate is 5 tokens/sec, a quiet user could have their bucket wiped before it refills, causing false rejections. Set the TTL to something like capacity / refill_rate + safety_margin.

  3. Storing tokens as integers when you need fractional refill – If your refill rate isn’t an integer divisor of a second (e.g., 2.5 tokens/sec), you’ll lose precision. Store tokens as a floating‑point number (Redis can handle it) and only compare against >= 1 for allowance.

Why This New Power Matters

Armed with a Redis‑backed token bucket, I could finally sleep through the night without waking up to pager‑duty alerts. Our API now gracefully absorbs traffic spikes, returns helpful 429 responses with proper Retry-After headers, and the database stays happy.

More importantly, this pattern is a building block. Once you have a reliable, distributed rate limiter, you can layer on:

  • Per‑user, per‑API‑key, or per‑IP limits just by changing the key.
  • Adaptive throttling where you adjust capacity or refill_rate based on real‑time load metrics.
  • Global quotas for expensive downstream services (payment gateways, third‑party APIs) by sharing the same bucket across multiple micro‑services.

It’s like obtaining a lightsaber: you start deflecting blaster bolts, and soon you’re cutting through the doors of the Death Star itself.

Your Turn – A Mini‑Quest

Grab a Redis instance (Docker’s redis:alpine works fine), drop the Lua script in, and try implementing a rate limiter for a simple endpoint. Experiment:

  • What happens if you set capacity to 10 and refill_rate to 1?
  • How does the behavior change when you hammer the endpoint with 50 concurrent requests via hey or wrk?
  • Can you add a Retry-After header based on the tokens left and refill rate?

Share your results, the weird edge cases you hit, and maybe a meme of Yoda saying, “Rate limit, you must.”

May your buckets stay full, and your APIs stay resilient. Happy hacking! 🚀