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:
- Every lookup costs money. The registry vendors charge per call.
- The data is about real people's vehicles. Some lookup types return more detail than others, and anything that returns vehicle data in bulk is a privacy problem.
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:
- Anonymous visitors are keyed by IP address.
- API partners are keyed by their client id.
- Sales agents are keyed by their user id, not their IP, so agents working from one office network each get their own limit.
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:
- It does not care how many IPs the caller has. Every proxy walking the same series lands in the same set.
- Counting distinct values, not hits, keeps real users safe. Someone retrying their own number fifty times adds one member to the set.
- It is pure Redis. No database read, so it stays cheap even when it is under attack.
- It is scoped per partner channel, so heavy organic traffic on one partner cannot block another.
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 most detailed lookup now needs a real quote in progress. It is rejected unless the request names an existing, incomplete transaction.
- Each transaction gets a small budget of distinct registration numbers per day, the same distinct-set technique keyed by transaction id. One transaction cannot be reused to look up many vehicles.
- No allow-list exemption for that budget. The series guard skips internal callers, but the transaction budget applies to everyone, because the risk comes from the data returned, not from who is asking.
- Protection is on by default. A vendor without an explicit series configuration gets sensible defaults; turning it off takes an explicit
"enabled": false.
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
- Per-IP limits stop careless clients. Against residential proxies they do nothing.
- Key the limit on what is being enumerated. If identifiers are sequential, the sequence is the signal.
- Count distinct values with a set, not hits with a counter, so retries stay free.
- Be precise about windows: refreshing a TTL on every write quietly turns a fixed window into a block that never ends.
- Put a hard spend cap underneath everything.
- Decide fail-open or fail-closed per endpoint, and write down why.