Part 3 of 7 · 1 min read
High-level design
Shorten, then redirect.
The service has two REST endpoints.
- Shorten. A client sends a POST with one parameter, the long URL, and gets back the short URL.
- Redirect. A client sends a GET for the short URL and is redirected to the long URL.
The simplest store for the pairs is a hash table from short URL to long URL. This is a fine start, but memory is limited and costly, so a real system keeps the pairs in a database table with three columns: id, short URL and long URL.
The redirect and its status code. When a user opens the short link, the server answers with a redirect. The book compares two kinds:
- 301, "moved permanently". The browser remembers the answer, so later visits to the same short link skip the service and go straight to the long address. This lowers load on the service.
- 302, "moved temporarily". The browser asks the service every time. This gives the service a chance to count each click and see where it came from, which helps analytics.
So the choice depends on the priority: use 301 to cut load, and use 302 to keep a view of every click. Most products that sell click statistics use 302.
Redirect
A redirect is a reply that tells the browser to go to a different address instead.
Example: a reply with status 302 and the long address in its location field.
Check yourself: 1. Which status makes the browser remember the answer? 2. Which one helps count clicks? 3. Why use a database table and not an in-memory hash table?