Lesson 10 of 15
31. Design a URL Shortener

31.9 How do you count clicks without slowing redirects?

3 min read+10 XP

Writing a counter to the database on every redirect would add a write to the hottest path. Instead:

  1. The app server publishes a small click event (code, time) to a queue and returns the redirect immediately (Chapter 22).
  2. Analytics workers read events in batches and add them up per code per hour.
  3. They write the totals to an analytics store. The stats API reads from there.

Counts lag by seconds or minutes, which the requirements allow. Most queues deliver at least once, so after a worker crash a few events may be counted twice. For "nice to have" counts that's acceptable; if counts were billed, each event would carry an ID and workers would ignore duplicates (Chapter 22, idempotent consumers).

Memory code: "Redirect now, count later."