1. Home
  2. Blog
  3. Software Development

Software Development

API Rate Limiting Explained: Algorithms, Headers and Handling 429 Errors

Rate limits protect APIs from overload and abuse. Learn how the main algorithms behave, what a good 429 response looks like, and how clients should back off, using a simulation we ran.

8 min read
API rate limiting explained: algorithms, headers and handling 429 errors

Key takeaways

  • Rate limiting caps how many requests a client can make in a period of time.
  • The token bucket allows short bursts while enforcing an average rate.
  • A simple fixed window can let through double the limit at a window boundary.
  • Return 429 Too Many Requests with a Retry-After header, and have clients back off with jitter.

One buggy script calls your API in a tight loop. Without limits, it can slow the service for every other user, or run up a large cloud bill. API rate limiting is the guard rail that keeps a single client from taking more than its fair share.

To show how the common algorithms behave, we wrote small Python versions and fed them simulated request timings. The outputs below come from that run. They are teaching models, not production code, and real gateways have more features.

What is rate limiting?

Rate limiting counts requests per client and rejects, or delays, requests over an agreed limit, such as 100 requests per minute. A related idea, throttling, often means slowing requests down rather than rejecting them. A quota is usually a larger allowance over a longer period, such as 10,000 calls per month on a pricing plan.

Why APIs need it

  • Stability: traffic spikes cannot overwhelm databases or downstream services.
  • Fairness: one heavy client cannot starve the others.
  • Security: limits slow down brute-force login attempts and scraping.
  • Cost control: expensive operations, such as AI model calls, stay within budget.

Rate limiting is a core control in the OWASP API Security Top 10, under unrestricted resource consumption. Our API testing with Postman guide shows how to send the repeated requests needed to check it.

Token bucket

Picture a bucket that holds up to 5 tokens. Each request takes a token. Tokens refill at 1 per second, and the bucket never holds more than 5. If the bucket is empty, the request is rejected.

class TokenBucket:
    def __init__(self, capacity, refill_per_sec):
        self.capacity = capacity
        self.rate = refill_per_sec
        self.tokens = capacity
        self.last = 0.0

    def allow(self, now):
        elapsed = now - self.last
        self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

We sent 7 requests at once, then more later:

burst of 7 at t=0:  [True, True, True, True, True, False, False]
t=2.0:              [True, True, False]
t=10:               5 allowed of 10

The first 5 went through as a burst, then the bucket was empty. Two seconds later, 2 tokens had refilled, so 2 more requests passed. After a long pause, the bucket was full again but capped at 5. This burst-then-steady behaviour suits real traffic, which is why token buckets are common in API gateways. The leaky bucket is a close relative that processes requests at a fixed rate, smoothing output instead of allowing bursts.

Fixed window vs sliding window

A fixed window counter is the simplest approach: allow 10 requests per minute, and reset the counter when the minute changes. It has a known flaw at the boundary. We sent 10 requests at 59.9 seconds and 10 more at 60.0 seconds, with a limit of 10 per 60-second window:

fixed window allowed around boundary: 20 of 20
sliding log allowed around boundary:  10 of 20

The fixed window allowed all 20 requests in a tenth of a second, double the intended rate, because they fell into two different windows. A sliding log remembers the time of each recent request and counts those in the last 60 seconds, so it correctly allowed only 10.

The trade-off is memory. A sliding log stores a timestamp per request. The sliding window counter is a popular middle ground. It estimates the rate by blending the current and previous window counts, using little memory with good accuracy.

Algorithm comparison

Algorithm Bursts Accuracy Memory
Fixed window Up to 2x at boundaries Low Very low
Sliding log No Exact High
Sliding window counter Small Good Low
Token bucket Allowed up to capacity Good Low
Leaky bucket Smoothed out Good Low

What to limit by

  • API key or user ID: the fairest option for authenticated APIs.
  • IP address: useful for public endpoints, but many users can share one IP, and attackers can rotate them.
  • Endpoint: expensive operations, such as search, exports or login, deserve tighter limits.
  • Plan tier: free and paid customers often get different limits.

Login endpoints need special care. Limit both by account and by IP, so attackers cannot simply spread guesses across many IPs or many accounts.

The 429 response

When a client goes over the limit, return HTTP 429 Too Many Requests, not 500 or 403. Include headers that tell the client what happened and when to try again. Our simulation produced this set for a client with no requests left:

HTTP/1.1 429 Too Many Requests
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30
Retry-After: 30

Retry-After is a standard HTTP header. The RateLimit-* headers come from an IETF draft, and many APIs use their own X-RateLimit-* variants. Whatever you choose, document it. For more on status codes, see our HTTP status codes cheat sheet.

Handling limits as a client

Retrying immediately after a 429 makes things worse. If thousands of clients do it at the same moment, they hit the server in synchronised waves. The fix is exponential backoff with jitter: wait longer after each failure, and add randomness.

def backoff(attempt, base=0.5, cap=30, rng=random.Random(4)):
    return round(min(cap, base * 2 ** attempt) * rng.random(), 2)

[backoff(a) for a in range(6)]
# [0.12, 0.1, 0.79, 0.62, 0.53, 6.43]

This is “full jitter”: a random wait between zero and an exponentially growing ceiling. The waits look irregular, and that is the point. Clients spread out instead of retrying together. We seeded the random generator so the output could be reproduced.

Client checklist: honour Retry-After when it is present, cap the number of retries, only retry requests that are safe to repeat, and watch the remaining-requests header so you can slow down before you hit the limit.

Distributed rate limiting

With several API servers behind a load balancer, each server counting on its own lets a client exceed the limit by spreading requests across them. Teams usually keep counters in a shared store such as Redis, with atomic operations or a short script so two servers cannot both take the last token. Gateways such as Kong, NGINX, Envoy and cloud API gateways provide this as configuration. We did not run a distributed setup for this article.

Testing rate limits

  • Send requests up to the limit and confirm they succeed.
  • Send one more and confirm a 429 with correct headers.
  • Wait for the reset time and confirm requests succeed again.
  • Check limits per key: one client’s usage must not block another.
  • Test the boundary between windows for the double-burst problem.
  • Use a load tool, as covered in load testing vs stress testing, to check behaviour under heavy concurrency.

In unit tests, inject the current time, as our simulation does with now, so tests never have to sleep.

Designing limits users can live with

Picking the numbers matters as much as picking the algorithm. Start from real traffic: look at how many requests your heaviest legitimate clients make per minute, and set limits comfortably above that. A limit that blocks normal use creates support tickets, not safety.

  • Publish the limits in your API documentation, per endpoint and per plan.
  • Warn before blocking. Headers showing remaining requests let well-behaved clients slow down on their own.
  • Offer alternatives to heavy polling, such as webhooks, bulk endpoints or larger pages.
  • Monitor 429 rates. A sudden rise can mean an attack, a buggy client release, or limits that are now too tight.
  • Grant exceptions deliberately, for example raised limits for a partner, recorded in configuration rather than hard-coded.

Also decide what happens to requests that arrive just over the limit. Some APIs briefly queue a small number of extra requests instead of rejecting them, which smooths out short spikes. Others give priority to essential endpoints, such as payments, over less critical ones like analytics, so that important traffic keeps flowing when the system is under pressure.

Final thoughts

Good rate limiting is a contract between API and client. The server picks a fair algorithm, usually a token bucket or sliding window, and explains its limits clearly with a 429 and Retry-After. The client respects those signals and backs off with jitter. Start with generous limits per API key, watch real usage, and tighten only where you need to.

Frequently asked questions

What is API rate limiting?

It is a limit on how many requests a client can make to an API in a given time, such as 100 per minute. Requests over the limit are rejected or delayed.

What does HTTP 429 mean?

429 Too Many Requests means the client has exceeded a rate limit. The response often includes a Retry-After header saying how long to wait.

What is the token bucket algorithm?

Each request uses a token from a bucket that refills at a steady rate up to a maximum. It allows short bursts while enforcing an average rate.

What is the difference between rate limiting and throttling?

Rate limiting usually rejects requests over the limit. Throttling often slows or queues them instead. The terms are frequently used interchangeably.

How should a client handle rate limits?

Respect Retry-After, retry with exponential backoff and jitter, cap the number of retries, and slow down when remaining requests run low.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →