Sub topic 13
Collecting click analytics
This chapter adds click analytics to the redirect path. It assumes you have read the chapters on redirect semantics (301 versus 302) and caching, and that you know basic SQL and Python. It does not cover abuse protection or availability in depth. Those have their own chapters.
Why analytics sits outside the core path
A URL shortener exists to redirect. Users also ask how many people clicked a link, from where, and when. Marketing teams often pay for these numbers.
The redirect path is latency-sensitive and read-heavy. In the capacity chapter you saw that reads dominate writes by a large factor. Analytics turns every read into a write, because each click produces an event. Recording that event in the same transaction as the lookup would give your fastest, most frequent operation the cost of your slowest one.
The design rule for this chapter is that a click must never wait on analytics, and an analytics failure must never break a redirect.
Decide what to measure
Start with the questions the product must answer. Each field you record costs storage and may carry privacy obligations.
| Question | Field needed | Notes |
|---|---|---|
| How many clicks in total? | short code, timestamp | Cheapest to answer |
| Clicks per day or hour? | timestamp | Needs time bucketing |
| Where are visitors? | country or region | Derive from IP, then discard the IP |
| Which device or browser? | User-Agent family | Store the parsed family, not the raw string |
| Where did traffic come from? | Referer host | Often missing or stripped |
| How many unique visitors? | visitor identifier | Hardest and most privacy-sensitive |
Start with total clicks, time buckets, country, and referrer host. Add more only when someone has a concrete need.
The 301 problem
Analytics only sees requests that reach your server. With a 301 (permanent) redirect, browsers and intermediate caches may remember the mapping. Later clicks from the same browser then go straight to the destination and never touch you. Your counts will be too low, and by an amount you cannot measure.
A 302 (temporary) redirect makes the client ask you each time. That costs more traffic, but every click is visible. If analytics is a product feature, use 302, or use 301 with a short Cache-Control: max-age. If a link is never tracked, 301 saves bandwidth.
An asynchronous pipeline
The standard shape is to emit an event on the redirect path and process it elsewhere.
The stages work like this:
- The redirect service resolves the code, using the cache-aside lookup from the caching chapter.
- It builds a small event (code, timestamp, country, referrer host) and hands it to a queue without waiting for confirmation from the consumer.
- It returns the redirect response.
- A consumer reads events in batches and updates the analytics store.
In production the queue is usually a durable log such as Kafka, or a managed queue. Inside a single process, a bounded in-memory queue plays the same role. The next section uses one to show the mechanics.
A runnable sketch
This program records clicks through a bounded queue. A background worker groups events by (short_code, hour, country) and writes counts to SQLite using an upsert, so one row absorbs many clicks.
import os
import queue
import sqlite3
import tempfile
import threading
import time
from collections import Counter
events = queue.Queue(maxsize=10_000)
dropped = 0 # approximate; not thread-safe, fine for a metric
def record_click(short_code: str, country: str, ts: float) -> None:
"""Called on the redirect path. Never blocks."""
global dropped
try:
events.put_nowait((short_code, country, ts))
except queue.Full:
dropped += 1 # shed load instead of slowing redirects
def flush_worker(db_path: str, stop: threading.Event,
batch_size: int = 500, max_wait: float = 1.0) -> None:
conn = sqlite3.connect(db_path)
conn.execute(
"""CREATE TABLE IF NOT EXISTS clicks_hourly (
short_code TEXT NOT NULL,
hour INTEGER NOT NULL,
country TEXT NOT NULL,
clicks INTEGER NOT NULL,
PRIMARY KEY (short_code, hour, country)
)"""
)
while True:
batch = []
deadline = time.monotonic() + max_wait
while len(batch) < batch_size:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
batch.append(events.get(timeout=remaining))
except queue.Empty:
break
if batch:
counts = Counter(
(code, int(ts // 3600), country) for code, country, ts in batch
)
rows = [(c, h, k, n) for (c, h, k), n in counts.items()]
with conn:
conn.executemany(
"""INSERT INTO clicks_hourly (short_code, hour, country, clicks)
VALUES (?, ?, ?, ?)
ON CONFLICT (short_code, hour, country)
DO UPDATE SET clicks = clicks + excluded.clicks""",
rows,
)
if stop.is_set() and events.empty():
break
conn.close()
if __name__ == "__main__":
path = os.path.join(tempfile.mkdtemp(), "analytics.db")
stop = threading.Event()
worker = threading.Thread(target=flush_worker, args=(path, stop))
worker.start()
now = time.time()
for i in range(1200):
record_click("aB3xY9z", "US" if i % 3 else "DE", now)
stop.set()
worker.join()
conn = sqlite3.connect(path)
for row in conn.execute(
"SELECT short_code, country, clicks FROM clicks_hourly ORDER BY country"
):
print(row)
conn.close()It prints ('aB3xY9z', 'DE', 400) and ('aB3xY9z', 'US', 800).
The sketch makes three design choices:
put_nowaitand a bounded queue protect the redirect path. If the consumer falls behind, you lose some analytics, not availability.- Batching turns 1,200 events into two writes. Batches amortize round trips and lock contention.
- The upsert makes the write idempotent in structure: a repeated key adds to the count instead of failing.
Raw events or pre-aggregated counters
You can store every click, store only counts, or do both.
| Approach | Strength | Weakness |
|---|---|---|
| Raw event log | Any question can be answered later; easy to reprocess after a bug | Large; privacy exposure |
| Pre-aggregated counters | Small; fast dashboard queries | Questions must be chosen in advance; errors are hard to repair |
| Both, with retention | Flexible and fast | More moving parts |
A rough size check shows why this matters. At 10,000 redirects per second and about 100 bytes per event, raw logging produces 1 MB per second, or about 86 GB per day. Hourly counters for the same traffic grow with the number of distinct (code, hour, country) combinations, which is far smaller.
A common compromise keeps raw events in cheap object storage for a short retention window, such as 30 days. Aggregates feed the dashboards and are kept longer.
A counter table also invites a tempting shortcut: UPDATE urls SET clicks = clicks + 1 on every redirect. Avoid it. A popular link would make one row a write hotspot, and it would put analytics load on your primary URL table.
Data quality problems
- Bots and prefetchers. Link-preview crawlers, security scanners, and uptime monitors all follow links. Filter known bot User-Agents, and consider counting them separately, not discarding them.
- Duplicate delivery. Most queues give at-least-once delivery, so a consumer crash can replay a batch and double-count. Give each event a unique ID and deduplicate, or accept small overcounts for non-billing use.
- Clock skew. Use the redirect server's timestamp at event creation, not the consumer's processing time. Late events then land in the correct hour bucket, and the upsert handles them.
- Unique visitors. Exact counts need to remember every visitor. For approximate counts, a probabilistic structure such as HyperLogLog gives about 1 to 2 percent error in a few kilobytes per link.
Privacy
An IP address and a User-Agent together can identify a person. Many jurisdictions treat IP addresses as personal data.
- Resolve the IP to a country or region at the edge of the pipeline, then discard the IP. Do not write it to logs.
- Store the parsed browser family, not the full User-Agent string.
- Set a retention limit on raw events and delete on schedule.
- If you count unique visitors, use a salted hash that rotates (for example daily) so visitors cannot be tracked across days.
Failure modes
| Failure | Effect | Mitigation |
|---|---|---|
| Queue full or down | Events lost | Bounded queue with drop counter; alert when drops rise |
| Consumer crash | Replay, double counts | Event IDs, idempotent writes |
| Analytics store slow | Queue backlog | Batching, autoscaled consumers, backpressure limits |
| Hot short code | One counter row gets many writes | Aggregate in the consumer before writing |
Always expose the drop count as a metric. Without it, undercounting is silent.
Exercise
A team switches their shortener from 302 to 301 to cut server load. A week later, customers report that click counts on old links have dropped sharply, even though the links are still in heavy use. Explain why, and name two ways to restore accurate counts.
Show answer
With a 301, browsers and intermediate caches remember the destination and send later clicks directly there, so those requests never reach the shortener and are never recorded. Two fixes are to return to 302, so every click reaches the server, or to keep 301 but add a short Cache-Control max-age so caches expire quickly and the server sees a click at least once per window. The second still undercounts, so 302 is the right choice when exact counts matter. Browsers that already cached the 301 may keep bypassing the server until their cache entries expire.
Exercise
In the sketch, why does recordclick use putnowait on a bounded queue instead of a plain blocking put?
Show answer
A blocking put would make the redirect wait whenever the queue is full, so a slow analytics consumer would slow down or stall redirects. put_nowait raises queue.Full immediately, and the code counts a dropped event and returns. This follows the rule that analytics failures must never break or delay a redirect, at the cost of losing some events under overload.