Sub topic 13
Collecting Click Analytics
This chapter assumes you have read the redirect and caching chapters. You should know the difference between a 301 and a 302 response, and how a cache-aside lookup serves most redirects without touching the database.
What to measure
Analytics answers questions such as how many times a link was clicked, when, from which country, and on which device. Each click becomes one event with a small set of fields.
- The short code that was resolved.
- A timestamp.
- The referrer header, if the browser sent one.
- The user agent string, which identifies the browser and device.
- A coarse location derived from the client IP address.
Store a country, not the raw IP address. Raw IP addresses are personal data in many jurisdictions, and you rarely need them.
Keep analytics off the critical path
The redirect must stay fast. A user waiting for a redirect should never wait for an analytics write. If the analytics database is slow or down, redirects must still work.
The usual design is to publish a click event to a message queue and return the redirect immediately. A separate consumer reads events and writes them to an analytics store.
The publish call is fire-and-forget. If the queue is unreachable, the service logs the failure and still redirects. You accept that some clicks may be lost, which is a reasonable trade for a redirect path that never blocks.
The link between redirects and analytics
Your choice of redirect status code decides what you can count.
- A 301 is permanent. Browsers cache it and often skip your server on later visits, so those repeat clicks are never recorded.
- A 302 is temporary. The browser asks your server every time, so every click is visible.
If analytics matters to your product, use 302 and accept the extra load. The cache from the previous chapter keeps that load manageable.
Aggregate instead of storing every row
At high volume, storing one row per click grows quickly. At 100 million clicks per day, that is 100 million rows daily. Most dashboards only need counts per link per hour or day.
The consumer can batch events and increment counters. The table below is keyed by code and time bucket.
CREATE TABLE click_counts (
short_code VARCHAR(10) NOT NULL,
bucket TIMESTAMP NOT NULL,
country CHAR(2) NOT NULL,
clicks BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (short_code, bucket, country)
);The consumer adds to the count with an upsert. This sketch reads a batch, groups it in memory, then writes one update per group.
from collections import Counter
def flush(events, db):
counts = Counter(
(e["code"], e["timestamp"].replace(minute=0, second=0, microsecond=0), e["country"])
for e in events
)
for (code, bucket, country), n in counts.items():
db.add_clicks(code, bucket, country, n)Grouping a batch of 1,000 events for one popular link turns 1,000 writes into one.
Common errors
- Writing to the database inside the redirect handler. A slow analytics write then slows every redirect.
- Counting with a 301. Cached redirects hide most repeat clicks, so the counts are too low.
- Storing raw IP addresses indefinitely. This creates a privacy and compliance burden you can avoid.
- Assuming exact counts. Bots, prefetching, and dropped events mean the numbers are approximate. Filter known crawlers by user agent, and describe the figures as estimates.
- Using one counter row per link. A viral link makes that row a write hotspot. Bucketing by time, as above, spreads the writes.
Exercise
Why does the redirect service publish click events to a queue instead of writing directly to the analytics database, and what is the cost of this choice?
Show answer
Publishing to a queue keeps the analytics write off the redirect path, so a slow or unavailable analytics database cannot delay or break redirects. The cost is that events can be lost or delayed if the queue fails or the consumer falls behind, so the counts are approximate and may lag.
Exercise
A team switches from 302 to 301 redirects to reduce server load. Their click counts then drop sharply for popular links. Why?
Show answer
Browsers cache a 301 and go straight to the destination on later visits without contacting the shortener. Those repeat clicks never reach the server, so no click event is produced.