// notes · security

Rate limiting what is asked, not who asks

How a lookup endpoint went from per-IP limits to counting distinct identifiers per series in Redis, after an enumeration scrape that rotated IP addresses walked straight past the first design.

The endpoint

An insurance quote starts with a vehicle registration number. The user types it, the backend asks a third-party vehicle registry API for the vehicle's details, and the form fills itself in. It is the most convenient step in the funnel, and it sits on a public page that anonymous visitors can call.

Two things make that endpoint worth protecting:

I built the protection in four steps over about 20 months. Each step exists because the previous one was not enough.

Step 1: classic counters

The first version was the standard design: count requests per key per hour and per day in Redis, and return 429 when a counter passes its limit.

def limit_exceeded(key, limit, ttl):
    hits = cache.get_or_set(key, 0, timeout=ttl)
    if hits >= limit:
        return True
    cache.incr(key)
    return False

The interesting part was choosing the key:

Limits live in each vendor's configuration and are editable from the admin, so changing a limit needs no deploy.

Step 2: a hard spend cap

Counters protect against one noisy caller. They do not bound the total. Step 2 added a monthly (or daily) budget per vendor: the number of calls already made in the window is counted from the API log table, cached for a few seconds, and once it reaches the cap, every caller gets a 429.

It is a blunt instrument, and that is the point. Whatever happens to the finer limits, the bill cannot exceed the cap. The same release added an IP allow-list for internal tools and a block-list for known bad sources.

Step 3: the scrape that rotated IPs

Then someone enumerated the endpoint. The traffic looked like this (illustrative values):

MH12AB0001   from 203.0.113.17
MH12AB0002   from 198.51.100.240
MH12AB0003   from 192.0.2.88
MH12AB0004   from 203.0.113.191
...

Every request came from a different residential IP, so no per-IP counter ever passed 1. The limits from step 1 were working exactly as designed and were useless.

The way out was to stop asking who is calling and look at what is being asked. Indian registration numbers are issued in sequence within a series: the state, the RTO code and a letter group, followed by a running number. An enumeration walks the running number inside one series. A real user looks up one vehicle, maybe two, and retries the same number when they mistype something else.

So the new guard counts distinct registration numbers per series, using a Redis set per series and time window:

def series_blocked(redis, series, reg, limit, ttl):
    key = f"series:{channel}:{series}:{window}"
    if redis.sismember(key, reg):     # retry: free
        return False
    if redis.scard(key) >= limit:    # series is full
        return True
    redis.sadd(key, reg)
    if redis.ttl(key) < 0:          # first entry starts the window
        redis.expire(key, ttl)
    return False

A few properties make this work:

Extracting the series needed care. Most numbers look like MH12AB1234, but Bharat-series numbers look like 22BH1234AA, and some older Delhi numbers have a single-digit RTO code. The parser takes everything up to the running number and, if a value does not match any known shape, falls back to the cleaned input so the key is still stable.

Step 4: tighten what the data is worth

The series guard caught the walking pattern. The last step looked at the data instead of the traffic:

The bug in the first series guard

The first version of the series guard called EXPIRE on every new member. That turned a fixed window into a sliding one that never closed: as long as new numbers kept arriving in a busy series, the set never expired, and once it was full the series stayed blocked indefinitely, real users included.

The fix is two lines, and both are in the snippet above: set the TTL only when the set is created, and never add a blocked number to the set. A blocked burst then cannot grow the set or extend the window, and the series opens again when the window ends.

Failing open, on purpose

If Redis is unreachable, the series and transaction checks allow the request and log the error. That was a deliberate trade-off: the lookup is the first step of the quote funnel, and a Redis blip should not stop every customer from buying a policy. A Redis outage long enough to matter is an incident in its own right, and every failure is logged.

For a login endpoint I would choose the opposite. Fail-open is right only when the thing you protect is cheaper than the thing you would break.

Watching for false positives

Every trip is logged with the series, the partner channel, the window and the source IP. That log answers the only question that matters after deploying a new limit: is it blocking scrapers or customers? The forensic helpers used to investigate the scrape also changed on the way: exports now need an explicit output path instead of silently writing to a world-readable temp directory.

Takeaways