bhylu.com

Advertisements

Cybersecurity Rate Limiting

Bound a synthetic login attempt stream with a deterministic clock.

How it works

Rate limiting restricts consumption over an interval. The key and time model matter: an IP-only rule can harm people behind one shared connection while missing distributed abuse. Account-sensitive controls need care to avoid making account lockout an easy denial of service. The example models a fixed window for one fictional client, not a distributed production limiter.

Run the code

Save the complete source as rate-limiting.py in a separate learning folder, then run python rate-limiting.py. The reviewed runtime is Python 3.12.14 with the standard library; no third-party packages are required. These are local examples, not browser playground programs. Apache, MySQL and PHP are not needed.

Download the complete source

Local lab setup

Example

rate-limiting.py

counts = {}
def allow(key, now):
    window = now // 60
    bucket = (key, window)
    counts[bucket] = counts.get(bucket, 0) + 1
    return counts[bucket] <= 3
assert [allow("demo", 10) for _ in range(4)] == [True, True, True, False]
assert allow("demo", 60)
print("fourth attempt denied; next window allowed")

Expected result

fourth attempt denied; next window allowed

Passing time as a value makes the boundary test repeatable. The fourth request is denied and a request in the next minute starts a new bucket. Fixed windows can permit a burst across the boundary. A real shared store needs atomic operations, key expiry, bounded memory and behaviour for store failure.

Technical reference: OWASP Cheat Sheet Series. Check the guidance for your actual platform and deployment.