Sub topic 8
Redirecting: 301 versus 302
This chapter covers the redirect step of the shortener: which HTTP status code to return and what that choice costs. It assumes you know basic HTTP (methods, status codes, headers) and have read the API design chapter, where GET /{short_code} was defined as the resolve endpoint.
What the redirect response looks like
When a client requests a short link, the server does not return the page. It returns a status code and a Location header, and the client fetches the target itself.
HTTP/1.1 302 Found
Location: https://example.com/articles/very/long/path?id=42Two status codes fit this job. They differ in how long a client may remember the answer.
| Code | Name | Meaning | Default caching |
|---|---|---|---|
| 301 | Moved Permanently | The short code always maps to this URL. | Browsers and proxies may cache it indefinitely. |
| 302 | Found | The mapping is temporary. | Not cached unless `Cache-Control` or `Expires` allows it. |
Both codes may be answered with a different method by old clients, which is why newer services sometimes use 307 or 308. For a shortener that only handles GET, 301 and 302 are enough.
Trade-offs
A 301 lets the browser skip your servers on repeat visits. It lowers load and latency. The cost is that you lose control after the first visit:
- Click analytics miss every repeat visit from a browser that cached the redirect.
- If a link expires, is edited, or is taken down for abuse, cached copies keep sending users to the old target.
- Search engines may treat the short URL as an alias and pass ranking signals to the target. Some products want this, others do not.
A 302 sends every click through your service. That costs more traffic and slightly higher latency per click, but you see every request and can change or disable a link immediately.
Choosing
Match the code to the requirements you wrote earlier:
- If the product reports clicks, or links can expire or be revoked, use 302.
- If links are permanent, analytics are not needed, and server cost matters most, use 301.
- If you want a middle path, return 301 with a short
Cache-Control: max-age, or return 302 withmax-ageset to a few minutes. This trades some analytics accuracy for fewer requests.
Most commercial shorteners use 302 or an equivalent because analytics and link control are the product. The extra load is handled by the cache from the next chapter, which sits on the server side and so does not hide requests from your analytics.
Implementing the redirect
This example uses Flask and the resolve function from the cache-aside pattern. It returns 302 and a 404 for unknown codes. The in-memory store stands in for the cache and database.
from flask import Flask, redirect, abort
app = Flask(__name__)
LINKS = {"aZ3x9Kq": "https://example.com/articles/42"}
def resolve(short_code: str):
return LINKS.get(short_code)
@app.get("/<short_code>")
def follow(short_code: str):
long_url = resolve(short_code)
if long_url is None:
abort(404)
response = redirect(long_url, code=302)
response.headers["Cache-Control"] = "private, max-age=0"
return response
if __name__ == "__main__":
app.run(port=8000)Run it and check the headers with curl -i http://localhost:8000/aZ3x9Kq. You should see 302 FOUND and the Location header. Change code=302 to 301 and remove the Cache-Control line to see how the answer becomes cacheable.
Common errors
- Returning 301 while also promising click counts. Counts will be too low and hard to explain.
- Forgetting that CDNs and corporate proxies cache 301s too, so even a 302 with permissive cache headers can hide traffic.
- Using 200 with a JavaScript or meta-refresh redirect. Crawlers, link previews, and
curlwill not follow it.
Exercise
Your shortener lets users disable a link at any time and shows a click count per link. Which status code should the redirect use, and why?
Show answer
Use 302. A 301 may be cached by browsers and proxies, so repeat visits would skip the server. Those clicks would not be counted, and a disabled link would keep redirecting for users with a cached copy.
Exercise
A team wants lower server load but still wants approximate click counts. Name one way to get a compromise.
Show answer
Return 302 (or 301) with a short Cache-Control max-age, such as a few minutes. Repeat visits within that window are served from the client cache, and later visits reach the server again, so counts are approximate.