URL Shortener
Difficulty: Intermediate Patterns: Strategy, Repository, Factory Asked at: Amazon, Google, Microsoft, Uber, Flipkart
Functional Requirements
- Shorten URLs - generate short codes via Base62 encoding of atomic counter
💡 Base62 = writing a number using 62 symbols (0-9, a-z, A-Z) instead of 10, so counter value 1,000,000 becomes a 4-character code instead of a 7-digit one. - Custom aliases - register user-specified short codes with conflict checking
- Resolve URLs - redirect short code to long URL with click tracking
- URL expiration - time to live (TTL) based expiry with auto-cleanup on resolve
💡 Time to live (TTL) = how long an entry stays valid after creation. Here the mapping is not deleted by a background job; it is checked on read and dropped the first time someone resolves an expired code. - Usage statistics - track click count, creation time, expiration status
Non-Functional Requirements
- Thread-safety - atomic counter increment and collision-free alias registration
💡 Thread-safety = the design still produces correct results when several threads call it at the same time. Here two concurrentshorten()calls must never receive the same counter value. - Extensibility - swappable encoding strategies without changing service logic
- Uniqueness - short codes are guaranteed unique (counter-based or collision-checked)
- Validation - URL format and alias constraints enforced at the service boundary
Core Entities
| Entity | Description |
|---|---|
UrlMapping |
Domain model - short code, long URL, user, click count, timestamps, expiration |
UrlStats |
Read-only stats snapshot - code, URL, clicks, creation time, expiry status |
EncodingStrategy |
Strategy interface - converts a numeric ID into a short code string |
Base62Strategy |
Deterministic encoding - maps counter value to compact Base62 string |
RandomStrategy |
Non-deterministic encoding - generates random alphanumeric codes |
UrlRepository |
Repository interface - abstracts storage (save, find, exists, delete) |
UrlShortenerService |
Core service - atomic counter, encoding, alias registration, resolution |
AliasAlreadyExistsException |
Thrown when a custom alias is already taken |
UrlNotFoundException |
Thrown when a short code has no mapping |
UrlExpiredException |
Thrown when a resolved URL has passed its TTL |
💡 A read-only snapshot (UrlStats) is built once from the live mapping and then never changes, so handing it to a caller cannot let them mutate the real UrlMapping by accident.
Class Diagram
classDiagram
class UrlMapping {
-String shortCode
-String longUrl
-String userId
-long clickCount
-LocalDateTime createdAt
-LocalDateTime expiresAt
+incrementClicks()
+isExpired() boolean
+getClickCount() long
}
class EncodingStrategy {
<<interface>>
+encode(long id) String
}
class Base62Strategy {
-String ALPHABET
+encode(long id) String
}
class RandomStrategy {
-int length
-SecureRandom random
+encode(long id) String
}
class UrlRepository {
<<interface>>
+save(UrlMapping)
+findByShortCode(String) UrlMapping
+existsByShortCode(String) boolean
+delete(String)
}
class InMemoryUrlRepository {
-ConcurrentHashMap store
+save(UrlMapping)
+findByShortCode(String) UrlMapping
+existsByShortCode(String) boolean
+delete(String)
}
class UrlShortenerService {
-AtomicLong counter
-UrlRepository repository
-EncodingStrategy strategy
-ReentrantLock aliasLock
+shorten(String longUrl) String
+shortenWithAlias(String longUrl and String alias) String
+resolve(String shortCode) String
+delete(String shortCode)
+getStats(String shortCode) UrlStats
}
class UrlStats {
-String shortCode
-String longUrl
-long clickCount
-LocalDateTime createdAt
-LocalDateTime expiresAt
-boolean expired
}
class AliasAlreadyExistsException {
-String alias
}
class UrlNotFoundException {
-String shortCode
}
class UrlExpiredException {
-String shortCode
}
UrlShortenerService --> UrlRepository
UrlShortenerService --> EncodingStrategy
UrlRepository <|.. InMemoryUrlRepository
EncodingStrategy <|.. Base62Strategy
EncodingStrategy <|.. RandomStrategy
InMemoryUrlRepository --> UrlMapping
UrlShortenerService --> UrlStats
💡 Reading the arrows: a dashed arrow with a hollow head (<|..) means “implements this interface”, and a plain arrow (-->) means “holds a reference to”. So UrlShortenerService --> EncodingStrategy says the service owns an encoder but does not care which one. Learn more →
Key classes:
UrlShortenerService— the only class with business rules. Owns the atomic counter, validates URLs, asks the strategy for a code, and writes through the repository. Everything else is a collaborator it holds.EncodingStrategy— the one-method interface (encode(id)) that turns a number into a code. The service depends on this interface, never onBase62StrategyorRandomStrategydirectly.Base62Strategy/RandomStrategy— the two interchangeable encoders. Base62 is derived from the counter so codes are short and never repeat; Random is unpredictable but needs a collision check.UrlRepository— the storage boundary.InMemoryUrlRepositoryis the version used by the demo and by tests; a Redis or DynamoDB version would implement the same four methods.UrlMapping— the stored record itself: code, long URL, owner, click count, created-at and expires-at. It knows how to answerisExpired()so no caller has to do date arithmetic.UrlStats— a copy of the interesting fields of a mapping, handed out for reporting so callers never touch the live record.
Design Patterns
| Pattern | Where | Why |
|---|---|---|
| Strategy | EncodingStrategy with Base62/Random |
Swap encoding algorithm without changing service logic; add new strategies without modifying existing code |
| Repository | UrlRepository with InMemory impl |
Abstracts storage - swap to Redis or DynamoDB for production without touching business logic |
| Factory | UrlMapping creation in service |
Centralized initialization of timestamps, click counts, and expiration ensures consistency |
💡 Factory pattern = put object creation in one place instead of scattering new calls around the codebase. Every UrlMapping is born through the same path, so no caller can forget to stamp createdAt or the expiry.
💡 Repository pattern = hide storage behind a plain interface of save/find/exists/delete. The service talks only to UrlRepository, so whether the data lives in a HashMap, Redis or DynamoDB never leaks into the business rules.
Data Structures
| Component | Structure | Why |
|---|---|---|
| Short code to long URL | ConcurrentHashMap<String, UrlMapping> |
This is the redirect path, so it is the one lookup that has to be O(1) and lock-free for readers |
| Click count | AtomicLong on each mapping |
Incremented on the redirect without locking the mapping, so counting never slows the thing being counted |
| Code sequence | a single AtomicLong |
A monotonic source feeding the base62 encoder. Unique without coordination inside one process, which is why the encoder shuffles bits — the raw sequence would be guessable |
💡 AtomicLong gives a correct increment with no lock, which is enough here because nothing ever reads the count and writes it back. The moment a decision depended on the count, an atomic increment would stop being sufficient.
How It All Fits Together
Here’s what happens when a client shortens a URL:
- Client calls
shorten(longUrl)on UrlShortenerService - Service validates the URL format (must start with http/https)
- Atomically increments the counter to get a unique ID
- Delegates to the EncodingStrategy to convert the ID to a short code
- Checks for collision (only possible with RandomStrategy); retries if collision found
- Creates a UrlMapping with the short code, long URL, timestamps, and TTL
- Persists to the repository and returns the short code
💡 With Base62Strategy, collisions are impossible because the counter is monotonically increasing and the encoding is bijective. The collision loop only activates for RandomStrategy where two different IDs could produce the same random string.
💡 Monotonically increasing = the counter only ever goes up, never repeats a value. Bijective = the number-to-code mapping is one-to-one in both directions, so two different counter values can never produce the same code.
Complete Code
UrlMapping and UrlStats
UrlMapping is the core domain entity representing a shortened URL. It tracks the short code, original URL, click count (atomically incremented), and expiration. UrlStats is a read-only snapshot for reporting.
Discussion
Newest first