Hello! Welcome to the first lesson of our module on Designing Core Infrastructure Systems.
In the previous module, we established the fundamental building blocks of distributed systems, such as caching patterns, invalidation strategies, and data partitioning. Now, we'll start applying these building blocks to solve full-scale system design problems, beginning with a classic: the URL shortener.
This lesson directly addresses the learning outcome: Design a URL shortener with analytics, addressing scalability and collision handling.
This problem is a favorite in interviews because it starts simple but quickly expands to touch upon nearly every core concept in distributed systems: scalability, availability, data modeling, caching, and more. For a Staff-level interview at a company like Google or Uber, you're expected to go beyond a basic working solution and drive a deep discussion on trade-offs, fault tolerance, and production-readiness. This lesson is designed to prepare you for that conversation.
1. Structuring the Interview: The Core Framework
A system design interview is a collaborative problem-solving session. Success depends not just on your technical solution, but also on how you structure your communication. We'll follow the standard four-step framework that interviewers at Google, Uber, and Meta expect.
To get an overview of this framework in action, let's start with a video.
Design a URL Shortener (Bitly) - System Design Interview
This video, 'Design a URL Shortener' by NeetCodeIO, provides an excellent demonstration of the structured approach to a system design interview. It covers the essential phases from requirements gathering to the deep dive.
Watch the segment from 03:35 to 05:40. Pay close attention to the four-part process outlined: Gather Requirements (Functional & Non-Functional) API Design High-Level Design Deep Dives \nThis is the roadmap we will follow for the rest of the lesson.
Now, let's apply this framework step-by-step.
2. Step 1: Requirements and Estimations
Your first task is to scope the problem. Don't assume anything. Lead a discussion with your interviewer to clarify both functional (what it does) and non-functional (how it performs) requirements.
A good starting point is to list the core features and then perform back-of-the-envelope estimations to understand the scale you're designing for.
Design Url Shortener | System Design Interview - AlgoMaster.io
The article 'Design Url Shortener' from AlgoMaster.io provides an excellent example of a requirements clarification dialogue and the subsequent back-of-the-envelope estimations. This is a crucial first step to ground your design in concrete numbers.
Read sections '1. Clarifying Requirements' and '2. Back-of-the-Envelope Estimation'. Focus on: The types of questions asked (scale, character set, custom features). The key requirements derived: URL shortening/redirection, custom aliases, expiration, and analytics. The translation of '10 million new URLs/day' and a '100:1 read-to-write ratio' into QPS (Queries Per Second) for reads and writes, and total storage over 5 years.
From this, let's summarize our target requirements.
Functional Requirements:
- URL Shortening: Generate a unique short URL for a given long URL.
- URL Redirection: Redirect users from a short URL to the original long URL.
- Analytics: Track the number of clicks for each short URL.
- (Optional but good to discuss): Custom aliases, link expiration.
Non-Functional Requirements:
- High Availability: The system, especially redirection, must be highly available (e.g., 99.99%).
- Low Latency: Redirection should be very fast (< 100ms). Latency for shortening is less critical.
- Scalability: Must handle ~35,000 read QPS and ~350 write QPS at peak, with storage in the multi-terabyte range.
The most important takeaway is the read-heavy nature of the system (~100:1). This asymmetry will be the primary driver of our design decisions, especially regarding caching and database architecture.
3. Step 2: API Design
With requirements established, you define the system's public contract. A simple RESTful API is a standard and effective choice here.
The article from AlgoMaster.io (LINK) outlines three key endpoints in its 'Core APIs' section:
POST /shorten: To create a new short URL.GET /{short_code}: To handle the redirection.GET /analytics/{short_code}: To retrieve click data.
A crucial detail in the GET /{short_code} endpoint is the type of HTTP redirect to return. This choice has significant implications for caching and your ability to collect analytics.
301 Moved Permanently: The browser caches this redirect indefinitely. On subsequent visits, the browser goes directly to the long URL, bypassing your service entirely.- Pro: Fastest possible experience for repeat users; zero load on your servers after the first hit.
- Con: You lose all control. You cannot update the destination URL, and you cannot count any clicks after the first one.
302 Found/307 Temporary Redirect: The browser does not cache this redirect. It must contact your server every time.- Pro: You retain full control to track every click and update or expire the link.
- Con: Higher load on your servers as every redirect hits your system.
For a service with an analytics requirement, a 302 or 307 redirect is the necessary choice. The performance "cost" is what we will mitigate with a robust caching architecture.
4. Step 3: High-Level Design
Now we sketch the main components. Given the stark difference between read and write loads, a microservices approach with separate read and write paths is a standard pattern.

This diagram illustrates a robust design:
- Write Path: A client sends a
POSTrequest. The API Gateway routes it to the URL Shortening Service. This service is responsible for generating a unique ID, constructing the short URL, and saving the mapping to the Database. - Read Path: A client sends a
GETrequest. The API Gateway routes it to the Redirection Service. This service performs a fast lookup (ideally from a Cache) to find the long URL and returns the302redirect. - Analytics Path: The Redirection Service, after a successful lookup, sends an event to a Message Queue (e.g., Kafka). An Analytics Service consumes these events asynchronously to update click counts in a separate Analytics Database. This decoupling ensures that counting clicks does not add latency to the critical redirect path.
5. Step 4: Deep Dives
This is where you demonstrate senior-level expertise. Let's tackle the three most important challenges: unique ID generation, read path scalability, and the analytics pipeline.
Deep Dive 1: Unique Short URL Generation
How do we generate the unique part of short.ly/{unique_code}? This is a classic distributed systems problem with several valid approaches, each with different trade-offs.
The Hello Interview article (LINK) and AlgoMaster.io article (LINK) provide excellent, detailed comparisons of the main strategies. Let's synthesize them.
| Strategy | How it Works | Pros | Cons | Staff+ Considerations |
|---|---|---|---|---|
| Hashing | Hash the long URL (e.g., with SHA-256), encode with Base62, and truncate to 7-8 characters. | Deterministic (same long URL gives same short URL). Stateless generation. | Collision Prone: Truncation means different long URLs can hash to the same short code. Requires a "check-then-insert" against the DB, which isn't atomic and needs retry logic for collisions. | Hashing the long URL + a user-specific salt can generate unique short URLs for the same destination, which might be a product requirement. |
| Centralized Counter | Use a centralized atomic incrementor like Redis' INCR to get a unique integer. Base62 encode this integer. |
Guaranteed unique and simple to reason about. Computationally efficient. | Single Point of Failure (SPOF): If Redis is down, you can't create new links. Scalability Bottleneck: All write requests must go to one place. Predictable: IDs are sequential. | To scale the counter, use counter batching: each service instance requests a range of 1,000 IDs at a time from Redis to use locally. This drastically reduces the load on the central counter. |
| Distributed ID Generator | Use a "Snowflake"-like approach. Each ID is a 64-bit number composed of: Timestamp + Worker ID + Sequence Number. |
Highly Scalable & Available: No central bottleneck. IDs are roughly time-sortable. | Complex to implement. Requires a coordination service (like Zookeeper) to assign worker IDs and is sensitive to clock synchronization (NTP). | For multi-region deployments, each region can be assigned a different range of Worker IDs to ensure global uniqueness without cross-region communication on writes. |
Recommendation for an interview:
Start with the Centralized Counter approach using Redis. It's simple and effective. When your interviewer pushes on scalability and SPOF, introduce counter batching as the solution. This shows you can evolve your design based on constraints. Mentioning the Distributed ID Generator as the "at-scale" industrial solution (used by Twitter, Discord) demonstrates breadth of knowledge.
Deep Dive 2: Scaling the Read Path
Our back-of-the-envelope math showed a potential for ~35,000 read QPS. A database alone cannot serve this with low latency. This is a classic use case for aggressive caching, building directly on our previous lessons.
We'll use a multi-layer caching strategy, often called a "waterfall" lookup.
Design Url Shortener | System Design Interview - AlgoMaster.io
The article from AlgoMaster.io provides an excellent description of a multi-layered read path designed for extreme performance and low latency.
Read the section '6.2 Fast URL Redirections'. Focus on the four layers of the read path: Browser Cache, CDN, In-Memory Cache (Redis), and the Database. Understand how a request flows through these layers on a cache miss.
The layers of defense are:
- Layer 1: CDN (Content Delivery Network): The redirect response for popular links can be cached at CDN edge locations close to the user. This can serve a huge portion of traffic without it ever hitting your origin servers.
- Layer 2: In-Memory Cache (e.g., Redis/Memcached): A distributed cache that sits in front of your database. It stores
short_code -> long_urlmappings. Since memory access is orders of magnitude faster than disk access, this is key to achieving low latency. We would use the cache-aside pattern here. - Layer 3: Database: The source of truth. It must be queried on a cache miss. To make this fast, the
short_codecolumn must be the primary key and therefore indexed, allowing for O(log n) lookups.
This multi-layer caching approach is the standard solution for read-heavy systems and is exactly what an interviewer wants to see.
Deep Dive 3: Designing the Analytics Service
The requirement is to count clicks, but we must do so without adding latency to the redirect. The asynchronous architecture we outlined earlier is the solution.
Design a URL Shortener (Bitly) - System Design Interview
Let's revisit the NeetCodeIO video, which discusses the implementation of the analytics service.
Watch from 43:42 to 48:18. The video explains why writing to a database on every redirect is a bad idea. It then proposes an asynchronous solution: using an in-memory store (like Redis) to batch counts and periodically flush them to a persistent database. This is the 'Buffered Counting' approach.
There are a few ways to implement this asynchronous pipeline:
- Buffered Counting (Good): The Redirection Service increments a counter for the short code in Redis (
INCR clicks:short_code). A separate background job runs periodically (e.g., every minute), reads these counters from Redis, updates the main database, and resets the Redis counters. This massively reduces database writes. - Event Streaming (Better for huge scale): The Redirection Service publishes a small event
{ "short_code": "abc123", "timestamp": ... }to a message queue like Kafka or AWS Kinesis. A dedicated analytics service consumes this stream, aggregates the data, and writes it to a database optimized for analytics (like a columnar store, e.g., ClickHouse). This is more complex but offers real-time analytics and greater flexibility.
For an interview, describing the Buffered Counting approach is typically sufficient and demonstrates a solid understanding of decoupling.
6. Achieving Staff-Level Depth
To elevate the conversation to a Staff+ level, you need to proactively discuss production concerns, security, and long-term maintenance.
The Hello Interview article (LINK) has a dedicated section for this, which is an invaluable guide.
Design a URL Shortener Like Bit.ly - Hello Interview
This section of the Hello Interview article is tailored perfectly to your goal. It explicitly contrasts the expectations for a Senior vs. a Staff+ candidate.
Read the 'Staff+' section carefully. Note the emphasis on proactively discussing topics like multi-region deployment, the security implications of predictable IDs, and operational concerns like URL expiration cleanup.
Let's summarize those key Staff-level talking points:
- Multi-Region Strategy: How would you deploy this globally?
- ID Generation: To avoid cross-region coordination, you can give each region a disjoint set of IDs to generate (e.g., US-East gets odd-numbered IDs, EU-West gets even-numbered IDs, or use dedicated ranges from a distributed ID generator).
- Databases: Use a globally replicated database (like DynamoDB Global Tables or Google Cloud Spanner) to ensure writes in one region are visible everywhere.
- Traffic Routing: Use Geo-DNS to route users to the nearest regional deployment for low latency.
- Security of Sequential IDs: If using a counter-based approach, short URLs are predictable (
/101,/102, etc.). This could allow an attacker to scrape your data. How do you mitigate this?- Solution: Obfuscate the ID before Base62 encoding. For example, you can apply a reversible permutation using a Feistel network or simply XOR the ID with a secret key. This makes the final short code appear random while still being derived from a unique, sequential source.
- Operational Readiness:
- Link Expiration: How do you handle expired links? A
cronjob that scans and deletes from the database (active deletion) is resource-intensive. A better way is passive expiration: check theexpires_attimestamp during the redirect lookup. A hybrid approach uses passive checks for real-time accuracy and a low-frequency background job for data cleanup. - Fault Tolerance: What happens if Redis goes down? The read path degrades gracefully by falling back to the database (with higher latency). The write path might fail for new URL creation unless you have a high-availability Redis setup (e.g., Redis Sentinel).
- Link Expiration: How do you handle expired links? A
By bringing up these points yourself, you shift the conversation from simply solving a problem to demonstrating that you can build, operate, and maintain a robust, large-scale service.
Conclusion
We've designed a URL shortener that is not only functional but also scalable, highly available, and includes analytics. We moved beyond a basic design to address the complex trade-offs that senior engineers are expected to navigate.
Key Takeaways:
- Structure is Key: Always follow the framework: requirements, API, high-level design, and deep dives.
- The Read/Write Ratio Dictates Design: The 100:1 read-heavy nature of this problem makes aggressive, multi-layered caching the cornerstone of the solution.
- Decouple for Performance: Use asynchronous processing (via a message queue or buffered counters) for non-critical tasks like analytics to protect the latency of the primary user-facing operation.
- Know Your ID Generation Trade-offs: Be ready to discuss the pros and cons of hashing, centralized counters, and distributed ID generators in the context of scalability, complexity, and security.
- Think Like an Operator: To reach the Staff+ bar, proactively discuss multi-region deployment, security vulnerabilities, and long-term operational concerns like data cleanup.
Preview of the Next Lesson:
In our design, we proposed using a message queue like Kafka for the analytics pipeline. In the next lesson, we will dive deep into this building block itself and tackle the problem: Design a distributed message queue (e.g., Kafka-like) with ordering and delivery guarantees. This will give you the underlying principles needed to justify its use in other system designs.