All case studies

Rate limits that count correctly

Planit Traveler limits how often someone can try to sign in, register or comment. In development the limits worked. In production each one was about three times looser than it said.

Project
Planit Traveler, API
My part
Diagnosis, design, backend and tests
Built with
Django, PostgreSQL, Gunicorn
Status
In production since November 2026

The problem

The limits kept their counts in Django’s in-memory cache. That cache belongs to one process, and the development server is one process, so nothing looked wrong locally.

Production runs three Gunicorn workers. Each had its own count and none could see the others. A limit of five could allow fifteen, and the exact number depended on which worker happened to answer.

The rate limiting library ships a check that warns about unsuitable caches. It never ran, because only its middleware was installed and not the app that contains the check.

Constraints

  • Every limit had to keep its number. The fix was to make it true.
  • One server already ran PostgreSQL. A new service would be one more thing to secure, monitor and restart.
  • A broken counter must not stop people signing in.
  • A counter failure must not undo the request’s own database work.

The obvious fix, and why it failed

Django can keep its cache in the database, which every worker shares. It reads the count, adds one in Python and writes the result back. Two requests can read the same number, and one of them disappears.

Twenty simultaneous requests against a limit of five, ten times over:

Reproduced on 23 November 2026, PostgreSQL 15
CounterCounts lost, of 20Requests allowed
Django’s database cache5 to 11 lost5 to 10 allowed
One SQL statementNone lost5 allowed, every time
  1. Request A reads the count: 4.
  2. Before A has written anything, request B reads the same 4.
  3. A writes back 5.
  4. B also writes back 5. Two requests were counted as one, and both were allowed.

How it works now

The replacement is a small cache backend used only for rate limits. The library asks for two operations, and each one is a single SQL statement. Counting looks like this:

UPDATE ratelimit_counter
   SET count = count + %s
 WHERE key = %s AND expires_at > %s
RETURNING count
Counting a request. SQL from the cache backend, reformatted.

There is no separate read. PostgreSQL locks the row, adds to whatever is there and returns the result, so a second request waits for the first and gets the next number.

Starting a count is the harder half, because two requests can both be first:

INSERT INTO ratelimit_counter
       (key, count, expires_at)
VALUES (%s, %s, %s)
ON CONFLICT (key) DO UPDATE
   SET count = EXCLUDED.count,
       expires_at = EXCLUDED.expires_at
 WHERE ratelimit_counter.expires_at <= %s
RETURNING count
Starting or restarting a count. SQL from the cache backend, reformatted.

If no row exists, one is created. If the old window has expired, the row is reused. If the count is still live, the final condition leaves it alone, and the empty result tells the caller to count instead.

Decisions and tradeoffs

The database I already had
This costs one or two indexed queries on each limited request. For one server that is cheaper than running another service. With several servers and much more traffic I would look at Redis.
Allow when the counter fails
If the counter table is unavailable the request goes through and the error is logged. Limits are a second line of defense, and blocking everyone would turn a small fault into a sign-in outage.
Fixed windows
Someone can spend one window’s allowance at its end and the next one’s at its start. A sliding window would be tighter and would store more.

How it was tested

The main test starts 20 requests together and requires the numbers 1 to 20 to come back exactly once each, with five allowed:

def hit():
    usage = get_usage(
        request, group='race', key='ip',
        rate='5/m', method='POST',
        increment=True)
    return (usage['count'],
            usage['should_limit'])

results = run_concurrently([hit] * 20)
counts = sorted(count for count, _ in results)
allowed = sum(not limited
              for _, limited in results)

self.assertEqual(counts, list(range(1, 21)))
self.assertEqual(allowed, 5)
The concurrency test, trimmed. Python.
Run on 23 November 2026 against the main branch, PostgreSQL 15
SuiteCoversResult
Shared rate limits, backendConcurrency, several workers, expiry, isolation between visitors, counter failure16 of 16 passed

Outcome and limits

A limit now means what it says, whichever worker answers. The wider lesson was about the environment: a single-process development server can’t show a bug that needs two processes, so the tests now imitate several workers at once.

Next: Email that survives a crash