Design a URL shortener

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-04-15

Problem Statement

Design a URL Shortening Service (similar to Bitly or TinyURL) that converts long URLs into short, unique links that can be easily shared.


When users visit the short URL, the service should redirect them to the original long URL efficiently and reliably.


The system should be highly available, scalable, and support analytics tracking (e.g., number of clicks, location, device type).


🎯 Objective


Build a system that:


•Takes a long URL and returns a short, unique alias.
•Redirects users to the original URL when the short one is accessed.
•Can handle billions of redirections per day with low latency.
•Optionally provides usage statistics and custom aliases.
•Supports link expiry, user ownership, and rate limiting.


✅ Functional Requirements


1. Short URL Creation


•User submits a long URL via UI or API.
•The system generates a unique short code (e.g., https://sho.rt/abc123).
•The mapping between short code and original URL is stored in the database.
•Optionally allow:
•Custom short codes (user-defined).
•Expiration time for temporary URLs.


2. Redirection


•When a user visits the short URL, the system:
•Looks up the original long URL.
•Redirects the user (HTTP 301/302).
•Logs the access for analytics.


3. Analytics (Optional/Advanced)


•Track the following metrics:
•Number of visits per short URL.
•Visitor metadata: browser, device, country, timestamp.
•Provide APIs or dashboards for users to view link statistics.


4. User Accounts & Management


•Allow users to:
•Create and manage multiple short links.
•Delete or update links.
•Set expiration dates and custom aliases.


5. Admin Tools (Optional)


•Monitor overall usage and abuse.
•Blacklist malicious URLs.


⚙️ Non-Functional Requirements


| Attribute | Requirement |

| ----------------- | ------------------------------------------------------------ |

| **Scalability** | Should handle hundreds of millions of URLs and redirects/day |

| **Availability** | 99.99% uptime — short links should *always* work |

| **Latency** | Redirect latency < 100ms |

| **Durability** | Mappings should never be lost |

| **Consistency** | Strong consistency for short→long URL lookups |

| **Security** | Prevent phishing and spam |

| **Observability** | Metrics for latency, error rates, redirect count |


🧩 Core Components


| Component | Responsibility |

| ------------------------------ | ------------------------------------------------ |

| **API Gateway** | Handles user API requests (create, read, delete) |

| **URL Shortening Service** | Generates unique short codes and stores mappings |

| **Redirection Service** | Redirects users to the original long URL |

| **Database / Key-Value Store** | Stores short→long URL mappings |

| **Analytics Service** | Logs redirection data for insights |

| **Cache Layer** | Fast lookups for popular short links |

| **Rate Limiter** | Prevents API abuse |

| **Expiration Service** | Removes or invalidates expired URLs |



🧱 High-Level Architecture

1 2 +-------------------------+ 3 | Client / Browser | 4 +-----------+-------------+ 5 | 6 v 7 +--------+--------+ 8 | API Gateway | 9 +--------+--------+ 10 | 11 +------------------------------------------+ 12 | | 13 v v 14+---------------+ +------------------+ 15| URL Shortener | | Redirect Service | 16| (Write Path) | | (Read Path) | 17+-------+-------+ +--------+---------+ 18 | | 19 v v 20+---------------+ +------------------+ 21| Database / | | Cache (Redis) | 22| Key-Value | +--------+---------+ 23| Store (e.g.,| | 24| DynamoDB, | v 25| Cassandra) | +------------------+ 26+---------------+ | Analytics Logger | 27 +------------------+

🧾 Data Model


| Field | Description |

| -------------- | ----------------------------- |

| `short_code` | Unique short ID (primary key) |

| `long_url` | Original full URL |

| `created_at` | Timestamp of creation |

| `expires_at` | Optional expiration timestamp |

| `user_id` | Owner of the link |

| `click_count` | Total redirects |

| `custom_alias` | Optional custom short code |


⚡ Scalability & Performance Considerations


| Challenge | Solution |

| --------------------------------- | ---------------------------------------------------- |

| **High read traffic (redirects)** | Use **Redis / CDN caching** for fast lookups |

| **Unique short code generation** | Use **base62 encoding**, or **Snowflake IDs** |

| **DB bottlenecks** | Use **NoSQL key-value stores** (Cassandra, DynamoDB) |

| **Analytics volume** | Stream logs to **Kafka + ClickHouse / BigQuery** |

| **Link expiration** | TTL index or background cleanup worker |

| **Abuse prevention** | Validate URLs and rate-limit per user/IP |


🔐 Security Considerations


•Sanitize and validate URLs before shortening.
•Detect and block malicious/phishing domains.
•Use HTTPS for all requests.
•Protect API endpoints with authentication and rate limiting.
•Encrypt sensitive metadata at rest.


🧠 Tech Stack (Example)


| Layer | Technology |

| -------------------- | --------------------------------- |

| **Frontend** | React / Angular |

| **Backend** | Node.js / Go / Spring Boot |

| **Database** | DynamoDB / Cassandra / PostgreSQL |

| **Cache** | Redis / Memcached |

| **Queue** | Kafka for analytics pipeline |

| **Storage for logs** | S3 / BigQuery / ClickHouse |

| **Monitoring** | Prometheus + Grafana |

| **Auth** | OAuth2 / JWT |


💡 Possible Extensions


•Custom domains (e.g., mybrand.link/offer).
•Bulk shortening API for businesses.
•QR code generation for each short link.
•Link previews and tagging.
•A/B testing for marketing URLs.
•Private shorteners for internal enterprise use.


✅ End Goal


Design a highly available, low-latency, and globally scalable URL shortener that:


•Efficiently maps long URLs to short codes.
•Redirects users in <100ms.
•Supports billions of lookups.
•Offers analytics and customization features securely.


Solution

Comments