Abuse, expiry and analytics without slowing redirects
Keep the redirect to one lookup: record clicks without waiting, count unique visitors with HyperLogLog and know its error, check links for abuse at creation and in the background, limit scanners by what they produce, and answer expired links with status codes and headers that caches cannot misuse.
Contentsand lesson path
On this page
- Why it matters
- Click analytics: from a counter row to an event pipeline
- Unique visitors with HyperLogLog
- Abuse: decide at creation, keep the redirect's check cheap
- Expiry without surprises
- Check your understanding
- Apply it
- Review prompt
Lessons of URL Shortener Design
- Scoping and estimating a link shortener Worked example · 20 min
- Code generation and the data model Worked example · 25 min
- A redirect path that serves 100k reads per second Worked example · 25 min
- Abuse, expiry and analytics without slowing redirects Concept · 15 min
- Shortener design check Knowledge check · 6 questions
What you will learn
- Scale the redirect path with caching and replicas, and move click analytics and abuse checks off the critical path.
Prerequisites: Requirements & Estimation, Caching Strategies, Unique ID Generation
01. Why it matters
After lesson 3, a redirect at lnk.example is a cache lookup and a 302. Every other feature wants a step in that request: count the click, count a new visitor, check the target for phishing, check expiry. At 100,000 redirects a second, each step adds latency to every click, and each remote call ties the redirect to another system: if analytics is down, are links down too?
The question for each feature is the same: what must be decided before the browser gets its 302, and what can happen a few seconds or minutes later? This lesson works through click analytics, unique visitors, abuse and expiry with that question. The code needs Python 3.10 or newer and its standard library.
02. Click analytics: from a counter row to an event pipeline
The first idea is a counter row per link, incremented inside the redirect. It is exact, simple, and fine at a few clicks a second spread over many links. It breaks on the links that matter most. A viral campaign link sends thousands of updates a second to one row, which turns into a queue of writers waiting on each other; every redirect now waits for a database write; and an analytics outage becomes a redirect outage.
The principle is that the redirect only records that a click happened; counting happens later. The handler puts a small event (code, time, a visitor key, referring site) into a bounded in-memory buffer without waiting, returns the 302, and a background shipper sends batches to a durable log such as Kafka. A stream job reads the log and keeps counts per link per minute and per day; dashboards read those counts. Statistics may lag by minutes, which the requirements allow. The key detail is without waiting: if the shipper is stuck, the handler must drop the event, not the redirect.
python3 - <<'PY'
import queue
events = queue.Queue(maxsize=10_000) # about 2 s of one server's clicks (5,000/s)
stats = {"served": 0, "dropped": 0}
def redirect(code: str, visitor: str) -> str:
try:
events.put_nowait((code, visitor)) # never waits
except queue.Full:
stats["dropped"] += 1 # count the loss and move on
stats["served"] += 1
return "302 Found"
# The shipper that drains the buffer to the broker is down: nothing is taken out.
for i in range(25_000):
redirect("aZ3kP9q", f"v{i}")
print(stats, "buffered:", events.qsize())
PY{'served': 25000, 'dropped': 15000} buffered: 10000Every redirect was served, and the 15,000 lost events were counted, so the dashboard can flag that period as incomplete. That loss is the conscious price of keeping the broker off the hot path. Appending events to a local file that a log agent ships survives a process crash, at the cost of disk. Downstream, a log such as Kafka is usually read at least once, so a consumer may see an event twice after a restart: give each event an ID and make the counting idempotent (see delivery guarantees and idempotent consumers). The log also keeps events only for its retention period, so a consumer that falls further behind loses them.
When not to do this: if advertisers pay per click, an approximate, best-effort count is not acceptable. Then each click needs a durable record before the redirect returns, or a reconciliation against the load balancer's own logs, and you pay for it in latency or in batch work.
03. Unique visitors with HyperLogLog
Total clicks are a sum, which adds up across servers and days. Unique visitors are not: to count them exactly, you must remember every visitor key you have seen for that link and day, so memory grows with the audience. HyperLogLog (HLL) trades a little accuracy for fixed memory. It hashes each key; the first p bits of the hash choose one of m = 2^p registers, and the register keeps the largest position of the first 1-bit seen in the rest of the hash. Long runs of leading zeros are rare, so a register that has seen a run of 12 suggests many distinct keys. Combining all registers gives the estimate. Flajolet and co-authors (2007) showed that its standard error is about 1.04 / √m; Redis's version uses up to 12 KB and states a standard error of 0.81%. Save this version of the paper's algorithm as hll.py:
"""HyperLogLog after Flajolet et al. (2007), with a 64-bit hash. Standard library."""
import hashlib
import math
class HLL:
def __init__(self, p: int = 14, salt: bytes = b"") -> None:
self.p, self.m, self.salt = p, 1 << p, salt # m = 2**p registers
self.reg = bytearray(self.m)
def add(self, item: str) -> None:
h = hashlib.blake2b(item.encode(), digest_size=8, key=self.salt).digest()
x = int.from_bytes(h, "big")
j = x >> (64 - self.p) # the first p bits choose a register
w = x & ((1 << (64 - self.p)) - 1) # the other 64 - p bits
rho = (64 - self.p) - w.bit_length() + 1 # position of the first 1-bit
self.reg[j] = max(self.reg[j], rho)
def count(self) -> float:
alpha = 0.7213 / (1 + 1.079 / self.m) # the paper's constant for m >= 128
raw = alpha * self.m * self.m / sum(2.0 ** -r for r in self.reg)
zeros = self.reg.count(0)
if raw <= 2.5 * self.m and zeros: # few items: use linear counting
return self.m * math.log(self.m / zeros)
return raw
def merge(self, other: "HLL") -> "HLL":
"""The sketch of the union: the larger value of each register."""
out = HLL(self.p, self.salt)
out.reg = bytearray(map(max, self.reg, other.reg))
return outNow count one popular link's visitors for a week, keeping one sketch per day, and compare with exact sets:
python3 - <<'PY'
import random
from hll import HLL
rng = random.Random(42)
sketches, exact = [], []
for day in range(7): # one link, a week of clicks, many from returning visitors
sketch, seen = HLL(14), set()
for _ in range(60_000): # clicks per day
visitor = f"v{rng.randrange(day * 20_000, day * 20_000 + 50_000)}"
sketch.add(visitor)
seen.add(visitor)
sketches.append(sketch)
exact.append(seen)
print(f"day {day + 1}: exact {len(seen):,} estimate {sketch.count():,.0f}")
week = sketches[0]
for sketch in sketches[1:]:
week = week.merge(sketch)
union = set().union(*exact)
print(f"sum of the 7 daily counts: {sum(len(s) for s in exact):,}")
print(f"week: exact {len(union):,} merged estimate {week.count():,.0f}")
print(f"memory: exact set of 16-byte IDs {len(union) * 16:,} bytes, "
f"sketch {len(week.reg):,} bytes")
PYday 1: exact 35,003 estimate 35,025
day 2: exact 34,902 estimate 34,263
day 3: exact 34,909 estimate 34,831
day 4: exact 34,913 estimate 35,016
day 5: exact 34,949 estimate 34,772
day 6: exact 34,814 estimate 34,360
day 7: exact 34,833 estimate 34,639
sum of the 7 daily counts: 244,323
week: exact 149,325 merged estimate 149,356
memory: exact set of 16-byte IDs 2,389,200 bytes, sketch 16,384 bytesEach daily estimate is within 2% of the truth, from 16 KiB of registers; Redis keeps the same 16,384 registers at 6 bits each, 12,288 bytes. The weekly number shows why sketches matter beyond memory. Adding the seven daily counts gives 244,323, because a visitor who returns on four days is counted four times. Merging the sketches, register by register, gives the sketch of the union, 149,356 against an exact 149,325. Each merged register is the larger of the two, because a register records the longest run seen among all keys routed to it, whoever saw them; so the same merge combines sketches from many servers, as long as all use the same number of registers and the same hash. Redis offers it as PFMERGE.
A standard error is a typical error, not a guarantee. The next run repeats one count with 60 different hash keys (it takes about 20 seconds):
python3 - <<'PY'
import math
from hll import HLL
n, trials = 100_000, 60 # 100,000 distinct visitors, 60 independent hash keys
errors = []
for t in range(trials):
sketch = HLL(14, salt=t.to_bytes(4, "big"))
for i in range(n):
sketch.add(f"visitor-{i}")
errors.append(sketch.count() / n - 1)
rms = math.sqrt(sum(e * e for e in errors) / trials)
print(f"m = 16,384: measured rms error {rms:.2%}; the paper predicts "
f"1.04/sqrt(m) = {1.04 / math.sqrt(16_384):.2%}")
print(f"largest error in {trials} runs: {max(errors, key=abs):+.2%}")
PYm = 16,384: measured rms error 0.85%; the paper predicts 1.04/sqrt(m) = 0.81%
largest error in 60 runs: +2.33%The typical error matches the paper, and one run in 60 was off by 2.3%, nearly three times as much, which is why lesson 1's requirement says about 2%. HLL answers one question, how many distinct keys, so it is the wrong tool for exact totals such as a click counter, and it cannot list who visited. Use a counter for totals and keep raw events briefly if someone needs the list.
04. Abuse: decide at creation, keep the redirect's check cheap
A public shortener attracts people who want to hide a phishing or malware address behind a trusted-looking link. Fetching and inspecting every target on every click could add seconds to the hot path. Instead, check a URL when the link is created. The cheapest checks come first: accept only http and https targets (no javascript: or data:), refuse links to lnk.example itself, which could loop, and cap the length. Then query reputation services such as Google's Web Risk API (which says it cannot guarantee its lists are accurate), with tighter creation limits for anonymous users. Then rescan in the background, because a page that was clean at creation can turn malicious later. A link found to be bad gets status: disabled, which the redirect already reads in the record, so the check on the hot path costs nothing extra. A doubtful link can redirect to a warning page instead.
Scanning the code space is the other abuse. Lesson 2 kept the space sparse, so even by year five a random guess hits a link only about one time in 480; the defence is to make guesses scarce. A scan produces many unknown-code answers from one client network, while a viral link produces many requests for one existing code from everywhere. So limit unknown-code answers per client network, with a token bucket or similar (see why limit and where to enforce), and alert on the share of 404s. A limit on all requests per network would also block an office of thousands behind one address clicking a campaign.
05. Expiry without surprises
Lesson 2 made expiry exact by checking expires on every read, and kept expired codes as tombstones. Two details remain on the response side. Cached copies carry expires, and the redirect server checks it on every hit, so a cached entry cannot outlive the link. And the status code for an expired link needs care. RFC 9110 describes 410 Gone as likely permanent, common for limited-time promotions, and says to use 404 when the server does not know whether the condition is permanent. Both 404 and 410 are heuristically cacheable, so a browser or CDN may keep them without any header.
At lnk.example, owners may renew a link during a grace period before cleanup. Such a link answers 404 with Cache-Control: no-store, so a renewal works at the next click. After cleanup, when the tombstone makes the end final, 410 is accurate, and an explicit max-age lets caches keep it for as long as you choose.
06. Check your understanding
07. Apply it
Transfer the ideas to a different product: a podcast host that wraps each episode's audio file in a tracking redirect and bills advertisers per unique listener per week.
- Which numbers must be exact, which may be approximate, and what that means for the click path (best-effort buffer, local log, or a durable write before the redirect)?
- How are weekly unique listeners counted without double counting across days?
- One abuse that matters here, such as inflated downloads, and where you detect it.
- Finish the skill's design doc for lnk.example with the same three decisions and the failure mode of each off-path component.
08. Review prompt
Without looking back: why does a counter row per link fail on viral links? What must the redirect handler never do with a click event? How does HyperLogLog estimate distinct visitors, how large is its error, and why do sketches merge while counts do not add? Why check links at creation and later? Which limit targets scanners? When is 410 right?
References
- Flajolet, Fusy, Gandouet and Meunier (2007): HyperLogLog, the analysis of a near-optimal cardinality estimation algorithm
- Redis documentation: HyperLogLog
- Redis documentation: PFMERGE
- Redis 8.4.0 source: hyperloglog.c (HLL_P 14, 6-bit registers)
- Google Cloud: Web Risk overview
- RFC 9110: HTTP Semantics, Section 15.5.11 (410 Gone; 404 is Section 15.5.5)
- Python documentation: queue
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.