AlgoViz

Design a URL shortener

medium 45 min

Turn a long URL into a short code and redirect anyone who opens it.

API and data

The contract first, then the data that serves it.

Entities

Name the things first

Four nouns are enough to start: Link (code, long URL, owner, expiry), User, Domain and Click. Add fields when a request needs them, and take the owner from the sign-in token, never from the request body.

API

Endpoints and status codes

HTTP
POST /api/v1/urls{ "long_url": "https://www.example.com/very/long/path?query=params",  "custom_alias": "my-link",        (optional)  "expires_at": "2027-12-31",       (optional)  "domain": "go.brand.com" }        (optional, enterprise)→ 201 { "short_url": "https://sho.rt/my-link", "short_code": "my-link",        "long_url": "...", "created_at": "2026-01-15T10:30:00Z",        "expires_at": "2027-12-31T23:59:59Z",        "qr_code_url": "https://sho.rt/qr/my-link.png" }GET /{short_code}→ 302 Found  Location: https://www.example.com/very/long/path?query=params  Cache-Control: public, max-age=0, s-maxage=60GET /api/v1/urls/{short_code}/stats?from=2026-01-01&to=2026-01-31→ 200 { "total_clicks": 15420, "unique_visitors": 8932,        "clicks_by_country":  { "US": 5200, "UK": 2100, "IN": 1800, "DE": 1500 },        "clicks_by_referrer": { "twitter.com": 4500, "direct": 3200, "google.com": 2100 },        "clicks_by_device":   { "mobile": 9200, "desktop": 5800, "tablet": 420 },        "clicks_by_hour": [ { "hour": "2026-01-15T10:00:00Z", "clicks": 523 } ] }DELETE /api/v1/urls/{short_code}→ 204  soft delete: later redirects return 410, the code is never reused
Create, redirect, statistics and delete.

Status codes

CodeMeaning here
201 CreatedShort URL created
302 FoundTemporary redirect, the default (analytics)
301 Moved PermanentlyPermanent redirect (SEO, less load)
400 Bad RequestInvalid URL
404 Not FoundCode does not exist
409 ConflictCustom alias already taken
410 GoneExpired or deleted
429 Too Many RequestsRate limit exceeded, with Retry-After

API decisions

  1. Interviewer

    What are the key design decisions?

  2. You

    One per endpoint:

    • Create: retries carry an idempotency key. Same owner and same URL may return the same code; different owners get different codes, so their analytics stay apart.
    • Create: return the full short URL, not only the code, so clients can use it directly.
    • Redirect: the hot path, about 99% of traffic. No body, just Location. Default 302, with 301 as an option.
    • Stats: hourly, daily or weekly aggregates, never raw clicks; paginate by date range and cache for 5 minutes.
  3. Interviewer

    How do you protect against abuse?

  4. You

    Three layers, with X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers so good clients can behave:

    • Gateway limits: sliding window counters in Redis with a TTL. Anonymous: 10 creates and 1,000 redirects an hour per IP. Signed in: 100 creates. Enterprise: 10,000 creates.
    • Validation: http and https only, blocked domains, Google Safe Browsing, optional reachability check (it adds latency).
    • Detection: the same URL from many IPs (bots), bulk links to similar domains (spam), and a model that scores URLs.

Database

Data model

Three stores, three access patterns

URL_MAPPINGS is DynamoDB, USERS and CUSTOM_DOMAINS are PostgreSQL, CLICK_STATS_HOURLY is ClickHouse.

Why each database

StoreUseWhyAlternatives
DynamoDBURL mappingsSingle-digit ms, scales by key, global tablesCassandra
RedisHot link cacheSub-ms reads, TTLMemcached
PostgreSQLUsers, billing, domainsACID, complex queries, not on the hot pathMySQL
ClickHouseAnalytics (OLAP)Columnar, fast aggregates, good compressionBigQuery, Druid
KafkaEvent streamDecouples, durableKinesis, Pulsar

Indexes

StoreIndexServes
DynamoDBpartition key short_coderedirect, O(1)O(1)
DynamoDBGSI user_idlist a user's links
DynamoDBGSI long_url_hashfind this owner's duplicate
ClickHouseorder by (short_code, hour)time series of one link
ClickHousepartition by monthdrop old data cheaply
ClickHouseskip index on countrygeographic filters
SQL
CREATE TABLE click_stats_hourly (  short_code   String,  hour         DateTime,  total_clicks SimpleAggregateFunction(sum, UInt64),  visitors     AggregateFunction(uniq, UInt64),  by_country   SimpleAggregateFunction(sumMap, Map(String, UInt64)),  by_referrer  SimpleAggregateFunction(sumMap, Map(String, UInt64)),  by_device    SimpleAggregateFunction(sumMap, Map(String, UInt64))) ENGINE = AggregatingMergeTreePARTITION BY toYYYYMM(hour)ORDER BY (short_code, hour);SELECT sum(total_clicks), uniqMerge(visitors)FROM click_stats_hourlyWHERE short_code = 'abc123'  AND hour >= '2026-01-01' AND hour < '2026-02-01';
Counts are summed and visitors are kept as a mergeable sketch, so any range can be combined correctly.

Consistency and invalidation

  1. Interviewer

    How do you keep the caches correct?

  2. You

    The database is the source of truth and every cache has a TTL.

    • Create: write the database, then Redis with 24 hours.
    • Update or delete: update the database, delete the Redis key, purge the CDN.
    • Miss: read the database, fill Redis (cache-aside), let headers fill the CDN.
    • Not write-behind: losing Redis before a sync would lose links.
    • Popular links can keep 24 hours; unpopular ones 1 hour or nothing. Redis evicts with LRU.
    • Include the host in the cache key, so custom domains never share entries.
  3. Interviewer

    Where do you need strong consistency?

  4. You

    Only for claiming a code: a conditional write decides. Clicks may be minutes late. With multi-region tables that replicate asynchronously, a condition is checked against the local copy only, so I send each alias claim to one home region.