Design a URL Shortener

Medium
Real World SystemsHashingRedirectionAnalyticsCacheCollision Handling

Problem Statement

Design a URL shortening service like bit.ly or TinyURL that generates short aliases for long URLs, handles redirection, supports custom slugs, tracks analytics, and handles high concurrency.

Requirements

Functional Requirements

  • shorten(longUrl) → generate a unique short code (6–8 chars, alphanumeric)
  • shorten(longUrl, customSlug) → use provided custom slug if available
  • resolve(shortCode) → redirect to original long URL
  • Expiry: optional TTL on shortened URLs
  • Analytics per short URL: click count, referrer, geographic distribution, time of access
  • User accounts: users own their shortened URLs, can manage them
  • Rate limiting: prevent abuse (max 100 shortens/day per user)
  • Delete/deactivate a short URL

Non-Functional Requirements

  • O(1) URL resolution (cache-backed)
  • Thread-safe short code generation
  • Collision-free code generation
  • Singleton URLShortenerService

Key Entities

  • URLMapping: shortCode, longUrl, userId, createdAt, expiresAt, clickCount
  • ClickEvent: shortCode, timestamp, referrer, ipAddress, country
  • User: id, email, urlMappings
  • CodeGenerator: generates unique 6-char base62 codes (a-z, A-Z, 0-9)
  • URLShortenerService: Singleton; manages mappings, resolution, analytics

Constraints

  • Short codes: 6 characters, base62 = 62^6 ≈ 56 billion unique codes
  • Custom slugs: 3–20 chars, alphanumeric + hyphens only
  • Expired URLs return 410 Gone status
  • Resolution must use cache (LRU) for hot URLs

!Constraints

- Short code: 6-character base62 (a-z, A-Z, 0-9) - Custom slugs: 3–20 characters, alphanumeric and hyphens only - Collision on code generation must be handled with retry - Expired URLs return appropriate error (410 Gone) - Resolution path is O(1) via cache layer
Output

Run or submit your code to see output here.