Video in progress
Should a URL shortener return 301 or 302 for the redirect?
A 301 is cached by the browser and later clicks never reach the server — less load, but you lose statistics and can't change the target. If you need to count clicks or edit the link, use 302 (or 307).
📖 Answer
In this question the business requirement matters more than the technical answer.
301 Moved Permanently. The browser caches the response for a long time (sometimes indefinitely). If the user clicks the link a second time, the browser doesn't send you a request. The result: less server load, but:
- not every click is counted;
- if the owner changes the target or deletes the link, browsers that cached it keep going to the old place;
- even if you block a malicious link, some people still get through.
302 Found / 307 Temporary Redirect. Every click passes through the server: it's counted, geo and device are recorded, and if the link was deleted, 410 is returned. Services like Bitly mostly take this route, because analytics is their product.
To manage load you can cache briefly even with 302: Cache-Control: private, max-age=60. Or perform the redirect at the CDN edge and log the click asynchronously.
In practice I do it like this: keep the redirect path very light — find the code in a cache (Redis or local), return 302, drop a click event on a queue. Writing to the DB synchronously ruins redirect latency. Counting clicks with a delay of a few seconds rather than in real time is normal here.
A minor difference: 307 preserves the method and body, while with 302 browsers often switch to GET. For a plain link there's no difference.
Sign up to mark studied questions and save your progress.