Preventing Abuse in a URL Shortener: Rate Limits, Malware and Expiry
Protect a URL shortener from spam and phishing: rate limiting, URL validation, Safe Browsing checks, link scanning, enumeration defence and expiry cleanup.
Published November 27, 2026
Any public URL shortener will be abused within days of launch. Spammers use short links to hide phishing pages and malware, bots mass-create links, and scrapers enumerate codes to discover private documents. If you do not plan for this, your domain ends up on blocklists and every link you serve, including legitimate ones, starts showing browser warnings.
The concept
Abuse prevention works in layers. At creation time: authenticate or rate-limit creators, validate and normalise URLs, and check destinations against threat intelligence like Google Safe Browsing. After creation: rescan links periodically (a page can turn malicious later), react to abuse reports quickly, and be able to disable a link globally within seconds.
On the read side, make codes non-sequential and long enough that guessing valid ones is impractical, rate-limit redirect requests per IP to slow enumeration, and consider an interstitial warning page for links flagged as suspicious rather than redirecting straight away.
The abuse pipeline
- Rate limit link creation per user, API key and IP
- Validate scheme (http/https only), length and hostname
- Block destinations on your own domain and known shorteners (redirect chains)
- Check Safe Browsing / threat feeds before saving
- Rescan periodically and on abuse reports; disable instantly via cache purge
Rate limiting with a token bucket
A token bucket allows short bursts but enforces an average rate. Store buckets in Redis so every API instance shares the same limits.
-- KEYS[1]=bucket key ARGV: capacity, refill_per_sec, now_ms
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local cap, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local tokens = tonumber(b[1]) or cap
local ts = tonumber(b[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)
local allowed = tokens >= 1
if allowed then tokens = tokens - 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000))
return allowed and 1 or 0Threats and defences
| Threat | Defence |
|---|---|
| Phishing / malware destinations | Safe Browsing lookup at create time, periodic rescans, abuse reporting |
| Bulk link creation by bots | Auth, per-key and per-IP rate limits, CAPTCHA for anonymous use |
| Code enumeration | Random 7+ character codes, redirect rate limits, no sequential IDs |
| Redirect loops and chains | Reject URLs pointing to your own or other shortener domains |
| javascript: and data: URLs | Allow only http and https schemes |
| Stale links to dead or hijacked domains | Expiry policies and periodic health checks |
Takedown flow
Practical examples
Validate URLs before saving
Reject unsafe schemes, overly long URLs, and self-referencing links.
from urllib.parse import urlsplit
BLOCKED_HOSTS = {"sho.rt", "bit.ly", "tinyurl.com"}
def validate(url: str) -> str:
if len(url) > 2048:
raise ValueError("URL too long")
parts = urlsplit(url.strip())
if parts.scheme not in ("http", "https") or not parts.hostname:
raise ValueError("Only http/https URLs are allowed")
if parts.hostname.lower().rstrip(".") in BLOCKED_HOSTS:
raise ValueError("Shortening other short links is not allowed")
return parts.geturl()Safe Browsing Lookup API request
Check a batch of URLs against Google's threat lists.
POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY
{
"client": {"clientId": "my-shortener", "clientVersion": "1.0"},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE"],
"platformTypes": ["ANY_PLATFORM"],
"threatEntryTypes": ["URL"],
"threatEntries": [{"url": "http://example.test/login"}]
}
}Expire and clean up links
A nightly job disables expired links in batches and purges cache keys.
UPDATE links SET is_active = FALSE
WHERE expires_at < NOW() AND is_active = TRUE
LIMIT 10000; -- MySQL syntax; repeat until 0 rowsCommon mistakes
- Allowing anonymous unlimited link creation from day one.
- Checking a URL once at creation and never again.
- Not being able to disable a link everywhere quickly because of long cache TTLs or 301 redirects.
- Following and fetching user URLs from your servers without SSRF protection when generating previews.
- Ignoring abuse reports; slow responses get the whole domain blocklisted.
Key takeaways
- Layer defences: rate limits, validation, threat checks, rescans and fast takedowns.
- Only allow http/https and block shortener-to-shortener chains.
- Random, long-enough codes plus redirect rate limits defeat enumeration.
- Keep cache TTLs short enough that disabling a link takes effect quickly.
FAQ
Should I show a preview page before redirecting?
For flagged or anonymous links it is a good safety net. Some shorteners let users add + to a link to see the destination first.
How do I fetch destination titles safely?
Use an SSRF-hardened HTTP client that blocks private IP ranges, limits redirects and response sizes, and runs with short timeouts.
What rate limits are reasonable?
It depends on the product, but something like 10 links per minute for anonymous users and a few hundred per minute per API key is a common starting point.