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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Last Watchdog
The Last Watchdog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog
L
LINUX DO - 最新话题
C
Check Point Blog
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
V
Vulnerabilities – Threatpost
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
S
Security @ Cisco Blogs
IT之家
IT之家
T
The Exploit Database - CXSecurity.com
The GitHub Blog
The GitHub Blog
D
Docker
Engineering at Meta
Engineering at Meta
AWS News Blog
AWS News Blog
S
Security Affairs
U
Unit 42
P
Palo Alto Networks Blog
V
Visual Studio Blog
Y
Y Combinator Blog
D
DataBreaches.Net
Forbes - Security
Forbes - Security
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
Security Latest
Security Latest
aimingoo的专栏
aimingoo的专栏
Simon Willison's Weblog
Simon Willison's Weblog
A
Arctic Wolf
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hacker News: Front Page
博客园 - 司徒正美
博客园 - Franky
宝玉的分享
宝玉的分享
TaoSecurity Blog
TaoSecurity Blog
Latest news
Latest news
Scott Helme
Scott Helme
MongoDB | Blog
MongoDB | Blog
量子位
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog

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
Designing a Rate Limiter for a Bit.ly Clone – My Jedi‑Level Token Bucket Adventure
Timevolt · 2026-06-19 · via DEV Community

Timevolt

The Quest Begins (The “Why”)

Picture this: I’m hunched over my laptop at 2 a.m., sipping cold brew, trying to get a tiny URL‑shortening service to survive a sudden traffic spike from a viral TikTok clip. The service works fine when a handful of devs ping it, but as soon as a few thousand requests hit per second, my naïve “count‑requests‑per‑IP‑and‑reset‑every‑minute” limiter starts throwing 429s like confetti at a New Year’s party—except the confetti is actually angry users.

I felt like Neo in The Matrix when he first sees the green code rain—except my code was a tangled mess of if‑else statements and I was about to get Agent Smith’d by a DDoS‑sized burst of traffic. The dragon I needed to slay wasn’t just “too many requests”; it was “bursty traffic that looks fine on average but destroys my service in spikes.”

After a couple of frustrating hours (and a meme‑worthy amount of coffee), I realized the problem wasn’t the amount of traffic—I needed a smarter way to smooth it out. Enter the token bucket algorithm, the Jedi mind trick of rate limiting.

The Revelation (The Insight)

The token bucket is simple, yet profoundly powerful:

  • Imagine a bucket that holds a fixed number of tokens (say, 100).
  • Tokens drizzle into the bucket at a steady rate (e.g., 10 tokens per second).
  • Each incoming request grabs a token; if the bucket is empty, the request gets throttled.

Why does this beat the old fixed‑window counter?

Approach How it Handles Burst Memory Cost Implementation Complexity
Fixed‑window (reset per minute) Allows up to N requests instantly at the start of each window → huge burst possible O(1) per client (just a counter) Very easy, but naive
Token bucket Allows a burst up to bucket size, then smooths to the refill rate → natural throttling O(1) per client (counter + timestamp) Slightly more code, but still trivial

The key insight? Buckets absorb bursts while still enforcing an average rate. It’s like having a lightsaber that can deflect a barrage of blaster bolts (the burst) but only lets a steady stream through (the average rate).

If you’ve ever watched Mad Max: Fury Road and seen the war rig plow through a sandstorm, you’ll get the analogy: the bucket is the rig’s fuel reserve—you can surge ahead when you have fuel, but you can’t exceed the rate at which you can refill it.

Wielding the Power (Code & Examples)

Let’s see the theory turn into code. I’ll use Node.js with Redis (because it’s fast, atomic, and shared across instances—perfect for a horizontally‑scaled shortener).

The Struggle (What NOT to Do)

// ❌ Naive fixed‑window limiter – the trap!
const LIMIT = 100;   // requests per minute
const WINDOW_MS = 60_000;

async function allowRequest(ip) {
  const key = `rate:${ip}`;
  const count = await redis.incr(key);
  if (count === 1) {
    await redis.expire(key, Math.ceil(WINDOW_MS / 1000)); // set TTL
  }
  return count <= LIMIT; // true = allow, false = block
}

Why this fails:

  • At second 0 of a minute, 100 requests slip through instantly.
  • At second 30, another 100 can slip through because the counter reset hasn’t happened yet.
  • Result: a client can burst 200 requests in 30 seconds—double the intended rate.

I spent three hours debugging why my service kept falling over during a load test, only to realize the counter was giving me a false sense of security. When I finally saw the pattern, I felt like Luke discovering the Force—“I feel it… the rate limiter is strong with this one.”

The Victory (Token Bucket Implementation)

// ✅ Token bucket limiter – the Jedi way
const BUCKET_SIZE = 100;   // max burst
const REFILL_RATE = 10;    // tokens per second

async function allowRequest(ip) {
  const key = `bucket:${ip}`;          // stores {tokens, lastRefill}
  const now = Date.now() / 1000;       // seconds as float

  // Lua script ensures atomic read‑modify‑write
  const lua = `
    local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens'))
    local last   = tonumber(redis.call('HGET', KEYS[1], 'last'))

    if tokens == nil then
      tokens = tonumber(ARGV[2])   // start full
      last   = tonumber(ARGV[1])
    end

    local refill = (tonumber(ARGV[1]) - last) * tonumber(ARGV[3])
    tokens = math.min(tonumber(ARGV[2]), tokens + refill)

    local allowed = 0
    if tokens >= 1 then
      tokens = tokens - 1
      allowed = 1
    end

    redis.call('HMSET', KEYS[1], 'tokens', tokens, 'last', tonumber(ARGV[1]))
    redis.call('EXPIRE', KEYS[1], 3600) // optional TTL to clean idle keys
    return allowed
  `;

  const result = await redis.eval(lua, 1, key, now, BUCKET_SIZE, REFILL_RATE);
  return result === 1; // true = allow
}

What’s happening?

  1. We fetch (or initialize) the bucket’s token count and the timestamp of the last refill.
  2. We compute how many tokens should have been added since last: (now - last) * REFILL_RATE.
  3. We cap the token count at BUCKET_SIZE (the burst limit).
  4. If there’s at least one token, we consume it and allow the request; otherwise we reject.
  5. We store the updated token count and timestamp back atomically via a Lua script—critical because multiple instances could race on the same key.

Trade‑offs I considered:

  • Redis vs. In‑memory maps: Going pure in‑memory would be faster per node, but would break consistency when you scale out. Redis gives us a single source of truth with sub‑millisecond latency—worth the extra network hop.
  • Lua script overhead: Some folks shy away from Lua because it feels “heavy.” In reality, the script runs in a few microseconds and guarantees atomicity without locking. The peace of mind is priceless.
  • Bucket size choice: Too small and you throttle legitimate bursts (think a user pasting 50 links at once). Too large and you lose smoothing power. I tuned ours by watching real traffic patterns—starting with BUCKET_SIZE = 2 * REFILL_RATE gave a nice balance.

Common Pitfalls (The Traps)

Trap Symptom Fix
Forgetting to update last timestamp Tokens never refill → permanent block after first burst Always write back last = now after refill calculation
Using separate GET/SET calls Race condition → token count can drift above bucket size Wrap logic in a Lua script (or use Redis transactions)
Setting a TTL that’s too short Idle users get their bucket wiped prematurely, causing unfair throttling on return Use a relatively long TTL (e.g., 1 hour) or refresh on each request

When I first missed the last update, my limiter acted like a lightsaber that turned off after the first swing—every request after the initial burst got 429’d. Fixing that felt like finally pulling the sword from the stone: click, and the power flowed freely again.

Why This New Power Matters

Now that I’ve got a token bucket guarding my shortener, the service laughs at traffic spikes that would have melted a fixed‑window limiter. I can:

  • Handle viral bursts without dropping legitimate requests.
  • Predict cost – the average request rate is bounded by REFILL_RATE, making capacity planning straightforward.
  • Scale horizontally – each node talks to the same Redis, so adding more API servers doesn’t require sharding the limiter logic.

In essence, I’ve turned my URL shortener from a fragile glass vase into a resilient, battle‑ready droid (think R2‑D2 dodging laser fire in Star Wars). The insight—absorb bursts with a bucket, then leak at a steady rate—isn’t just academic; it’s the difference between a service that survives the internet’s chaotic weather and one that cries for help at the first gust.

Your Turn – Embark on Your Own Quest

Grab a language of choice, spin up a Redis instance (or even a simple in‑memory map if you’re just experimenting), and implement a token bucket. Try to break it with a burst generator (hey, hey or wrk works). Then, tweak the bucket size and refill rate and watch how the behavior changes.

Challenge:

  1. Build a tiny URL‑shortener endpoint (/shorten) that calls your limiter before hitting the database.
  2. Add a dashboard that shows the current token count for a few test IPs (just for fun—don’t expose this in prod!).
  3. Share your results: what bucket size gave you the smoothest traffic flow? Did you hit any surprising edge cases?

Drop a link to your repo in the comments, and let’s compare notes. May your buckets stay full and your rate limits stay just right—happy coding! 🚀