This article outlines the system design for a URL shortening service, covering functional and non-functional requirements, high-level architecture, database schema, and key components like short code generation and analytics. It details the workflows for URL creation and redirection, emphasizing distributed ID generation and asynchronous analytics processing.
Read original on Dev.to #systemdesignA URL shortening service must handle input of long URLs and output unique short URLs, facilitate redirection from short to original URLs, and optionally support custom aliases and expiration times. Key non-functional requirements include low redirect latency (e.g., < 50ms), high availability, and an architecture optimized for a read-heavy workload.
The proposed architecture utilizes a URL Service as the main entry point, backed by Redis for caching and PostgreSQL for persistent storage. Analytics are handled asynchronously using Kafka for event streaming and a dedicated Analytics Consumer that ingests data into ClickHouse, an OLAP database suitable for time-series and aggregate analytics.
+----------------+ Client ----------> | URL Service | +----------------+ | | Redis Cache PostgreSQL | Redirect | Async Event (Kafka) | +----------------+ | Analytics | | Consumer | +----------------+ | ClickHouse (Analytics DB)For large distributed systems, generating unique and short IDs is critical. The article suggests using a Snowflake-like ID generation algorithm combined with Base62 encoding. Snowflake IDs offer a distributed, time-ordered, and unique ID generation scheme, preventing collisions and enabling high throughput. Base62 encoding converts these numeric IDs into URL-friendly alphanumeric strings, optimizing for length and character set compatibility.
| 1 bit | 41 bits | 10 bits | 12 bits |
|-------|---------|----------|----------|
| Sign | Timestamp | Worker ID | Sequence |Scalability of Short Codes
Base62 encoding allows for a vast number of unique short URLs. For instance, 6 characters in Base62 can generate approximately 56 billion unique URLs (62^6), which is sufficient for most large-scale services. This choice provides a good balance between brevity and capacity, making the service highly scalable in terms of available short codes.