Design the API for a URL shortener

Difficulty: Intermediate

Question

Design the REST API for a URL shortener service like bit.ly. Cover endpoints, status codes, and key design decisions.

Answer

Let me approach this like a real design round: clarify requirements, define resources, then walk through endpoints and the edge cases. Requirements I would confirm: create a short link from a long URL, optional custom alias and expiry, redirect when the short link is visited, view and delete links, and basic click analytics. Non-functional: redirects are read-heavy and must be very fast, creation is much rarer, and abuse control matters.

Resources. The main resource is a link, identified by its short code. Analytics are a sub-resource. Create: POST /v1/links with body { url, custom_alias?, expires_at? }. Success is 201 Created with a Location header /v1/links/{code} and the resource in the body containing code, short_url, long_url, created_at, expires_at. Validation failures such as an invalid URL scheme return 422 with problem details. A custom alias that is already used returns 409 Conflict. Rate limit creation per API key and return 429 when exceeded.

Idempotency question: should posting the same long URL twice return the same code? Design choice. For anonymous shortening, some services dedupe. For authenticated users with per-link analytics, each creation gets a new code. Support an Idempotency-Key header so retried POSTs don't create duplicates.

Read and manage: GET /v1/links/{code} returns metadata, 404 if missing. GET /v1/links lists the caller's links, cursor paginated and filterable by created_after or status. PATCH /v1/links/{code} updates the destination or expiry, and DELETE /v1/links/{code} disables the link, returning 204. Every route except redirect requires authentication, and object-level checks ensure users only manage their own links.

The redirect itself is the hot path and lives outside the /v1 API on the short domain: GET /{code}. It returns 301 Moved Permanently or 302 Found (or 307/308), with a Location header. This is a classic interview probe. 301 is cacheable by browsers and CDNs, which cuts server load, but then the browser skips our servers on repeat visits, so click counting misses hits and we can't change or expire the target reliably. 302 or 307 are not cached by default, so every click reaches us, enabling analytics, expiry and destination edits. Most analytics-driven shorteners use 302 (or 301 with strict cache headers). For expired links return 410 Gone; unknown codes return 404. Disabled or malicious links can return 451 or a warning interstitial.

Analytics: GET /v1/links/{code}/stats?from=&to=&interval=day returns aggregated clicks by day, country, referrer and device. Clicks should not be counted synchronously in the redirect path. Publish an event to a queue (Kafka) and aggregate asynchronously, so redirects stay at low milliseconds. The stats endpoint reads pre-aggregated data.

Design details: generate codes with a base62 encoding of a unique id (from a distributed ID generator or counter range allocation) or random 7-character strings with a collision check; 62^7 is about 3.5 trillion combinations. Avoid sequential guessable codes if links are private. Validate destinations: allow only http and https, block internal IPs (SSRF) and known malware domains. Cache code-to-URL mappings in Redis or a CDN edge. Reserve words such as api, admin and login so aliases can't shadow routes.

Security and abuse: authenticate creators, rate limit, scan URLs with a safe browsing service, and let owners disable links quickly.

Code examples

Create and redirect

POST /v1/links HTTP/1.1
Authorization: Bearer <token>
Idempotency-Key: 3f7a...
Content-Type: application/json

{ "url": "https://example.com/products/very/long/path?utm=abc", "custom_alias": "diwali-sale", "expires_at": "2026-11-15T00:00:00Z" }

HTTP/1.1 201 Created
Location: /v1/links/diwali-sale
{ "code": "diwali-sale", "short_url": "https://sho.rt/diwali-sale", "long_url": "https://example.com/products/very/long/path?utm=abc" }

GET /diwali-sale HTTP/1.1
Host: sho.rt

HTTP/1.1 302 Found
Location: https://example.com/products/very/long/path?utm=abc
Cache-Control: private, max-age=0

Creation returns 201 with Location; the redirect uses 302 so that each click reaches the service for analytics.

Redirect handler

app.get('/:code', async (req, res) => {
  const link = await cache.get(req.params.code) ?? await db.link.findUnique({ where: { code: req.params.code } });
  if (!link) return res.status(404).send('Not found');
  if (link.expiresAt && link.expiresAt < new Date()) return res.status(410).send('Link expired');
  clickQueue.publish({ code: link.code, ts: Date.now(), ua: req.get('user-agent'), ip: req.ip }); // async
  res.redirect(302, link.longUrl);
});

Fast lookup, correct status for missing and expired links, and click recording off the critical path.

Key points

Common follow-up questions

Interview tips

Concepts covered

URL shortener, API design exercise, redirects, analytics

More API Design questions