We are designing a URL shortening service. We need to consider:
Functional requirements:
Shorten a long URL to a short URL.
Redirect from the short URL to the original long URL.
Optionally, custom short URLs.
Analytics (click counts, referrers, etc.) - but we can keep it simple for now.
Non-functional requirements:
Scalability: handle millions of users and billions of redirects.
Availability: high availability for redirects (since it's a critical path).
Latency: low latency for both shortening and redirection.
Uniqueness: ensure that short URLs are unique (or handle collisions).
System design considerations:
How to generate the short code? (hashing, base conversion, random string, etc.)
How to store the mapping? (database choice: key-value store for fast lookups)
How to handle high read traffic (redirects) and write traffic (shortening)?
Basic flow:
a. User submits a long URL.
b. System generates a unique short key (e.g., 7 characters from [a-zA-Z0-9]).
c. Store the mapping (short key -> long URL) in a database.
d. Return the short URL (e.g., https://short.url/abc123).
For redirection:
a. User clicks on short URL.
b. System looks up the short key in the database to get the long URL.
c. Issue an HTTP 301 (permanent) or 302 (temporary) redirect.
Potential challenges:
Collision: two long URLs might get the same short key. We can check and retry.
Abuse: users might create many short URLs to abuse the service. Rate limiting.
Custom short URLs: if the user requests a custom short key, we must check if it's available.
Database schema:
We can have a table (or key-value store) with:
short_key (primary key, indexed)
long_url (the original URL)
created_at (timestamp)
user_id (if we have user accounts)
expiration_date (optional, if we want to expire links)
click_count (for analytics)
But for scalability, we might use a distributed key-value store (like Redis, DynamoDB, Cassandra) because:
Reads are very frequent (redirects) and we need low latency.
Writes are less frequent (shortening).
Generating short keys:
Option 1: Use a hash function (like MD5, SHA-1) of the long URL and take the first 7 characters. But this may cause collisions and also the same long URL will always get the same short key (which might be desired to avoid duplicates for the same URL?).
Option 2: Generate a random string and check for uniqueness. This avoids duplicate long URLs having the same short key but might cause collisions (though unlikely with a large enough keyspace). We can use a counter (like auto-increment) and then encode it in base62 (to make it short). This is common and ensures uniqueness.
Let's consider base62 encoding of a unique integer (from a database sequence or distributed ID generator). This gives us a short string without collision.
However, if we use a distributed ID generator (like Snowflake), we can generate unique IDs across multiple servers and then encode them.
GET /api/v1/analytics/:short_key (if we want to provide analytics)
Caching:
For redirects, we can cache the mapping (short_key -> long_url) in a cache (like Redis) to reduce database load.
Rate limiting:
We should rate limit the shorten endpoint to prevent abuse.
System components:
Web servers: handle HTTP requests (shorten and redirect).
Database: persistent storage (key-value store for quick lookups, and maybe a relational DB for user data and analytics if needed).
Cache: for frequently accessed short URLs.
ID generator: for generating unique short keys (if using base62 encoding of a number).
Scalability:
We can scale horizontally by adding more web servers.
Database: sharding by short_key (or by user_id if we have user accounts) if we use a relational DB. But a key-value store might handle scaling better.
For redirects (read-heavy):
Use caching at multiple levels (CDN for static assets, but for redirects we need to look up the short key which is dynamic).
We can use a distributed cache (like Redis cluster) and also cache at the web server level.
For shortening (write-heavy, but less than redirects):
We can scale the database by sharding. If we use a distributed ID generator, we can shard by the ID (or by the short_key prefix).
High availability:
Use multiple instances of web servers, cache, and database with replication and failover.
Data model for key-value store:
Key: short_key (string)
Value: long_url (string) and maybe other metadata (like creation time, user_id) but for redirection we only need the long_url.
We can store additional metadata in a separate database (relational) if we need to run complex queries for analytics.
Steps for shortening:
a. Validate the long URL (format, maybe check if it's a valid URL).
b. If custom short provided, check if it's available (and valid format) and then use it.
c. Otherwise, generate a short key (using base62 encoding of a unique ID from a distributed ID generator).
d. Store in the key-value store: short_key -> long_url.
e. Also, if we need analytics, store additional metadata in the relational DB (or in the same key-value store with more fields? but key-value stores are not good for complex queries).
However, for simplicity and performance, we might store everything in the key-value store as a hash (if the store supports it) or as a JSON string. But then we cannot easily query by user_id, etc.
Alternatively, we can have:
Key-value store for quick redirection: short_key -> long_url (and maybe a reference to the metadata record?).
Relational DB for metadata: short_key (primary key), user_id, created_at, etc.
Then during redirection, we only need the long_url, so we can get it from the key-value store. For analytics, we can query the relational DB.
But then we have to keep two stores in sync. Alternatively, we can use a key-value store that also supports secondary indexes (like DynamoDB) and store all the data in one place.
Let's consider using DynamoDB:
Table: short_urls
Partition key: short_key (string)
Attributes: long_url (string), user_id (string, if any), created_at (number), click_count (number), etc.
Then we can get by short_key for redirection, and we can also query by user_id (using a global secondary index on user_id) for user's links.
But note: DynamoDB is eventually consistent by default, but we can use strongly consistent reads for redirection? Actually, for redirection we can use eventually consistent because if we just created the short URL, we want it to be available immediately. So we might need strongly consistent for the first few seconds? Alternatively, we can write to the database and then cache the result, and then redirect from cache. But if we write and then immediately try to read (from cache or DB) and it's not there, that's a problem.
To avoid that, we can do:
When we create a short URL, we write to DB and then also write to cache (if we are using a cache). Then when we redirect, we read from cache first, then DB.
But if the cache write fails, we can still read from DB. And if the DB write fails, we don't return the short URL.
However, for a new short URL, we want to make sure that the next redirect (which might happen immediately) works. So we can do:
Write to DB (with strong consistency) and then write to cache. Since DB write is synchronous, we know it's there. Then when we redirect, we can read from DB (if cache miss) and then cache it.
Implementation details for generating short key:
code
We can use a distributed ID generator (like Twitter's Snowflake) to generate a unique 64-bit integer. Then encode that integer in base62 (which uses 0-9, a-z, A-Z). 64-bit integer in base62 will be at most 11 characters (since 62^11 is about 5.2e19, which is greater than 2^64~1.8e19). But we can use 7 or 8 characters by using a larger character set? But we already have 62. Alternatively, we can use a hash of the long URL and take the first 7 characters, but then we have to handle collisions.
code
17. Distributed ID generator:
We can use a service that hands out unique IDs (like Twitter's Snowflake: 64-bit: 41-bit timestamp, 10-bit machine ID, 12-bit sequence). Then we have to manage machine IDs, etc.
code
Alternatively, we can use a database that auto-increments, but that doesn't scale across multiple shards. So we need a distributed ID generator.
We can also use UUIDs, but they are 128-bit and too long for short URLs.
So we stick with a 64-bit distributed ID.
18. Architecture:
code
Client -> Load Balancer -> Web Servers (stateless) -> Cache (Redis) and Database (DynamoDB or similar).
Web servers:
- For shorten:
* validate URL
* if custom short, check availability (by trying to write with that short_key and catch duplicate? or check first? But check first might have race condition. We can use a conditional write: only write if the key doesn't exist. If it exists, return error.
* if not custom, generate a new short_key (from ID generator) and write to DB and cache.
* return the short URL.
- For redirect:
* extract short_key from path.
* check cache for short_key. If found, redirect to long_url.
* if not in cache, query DB (with strong consistency? or eventually consistent? We want the latest, so strongly consistent? But if we just wrote and then immediately redirect, we want to see it. So we can use strongly consistent reads for a short time after write? Or we can write to cache as well so that the next read is from cache.
But note: if we use a distributed ID generator, we don't have to worry about the same long URL getting the same short key? We are not checking for duplicates by long URL. So two users shortening the same long URL will get two different short keys.
If we want to avoid that, we can create an index on the hash of the long URL and then check before generating a new short key. But then we have to handle race conditions: two requests for the same long URL at the same time might both generate a new short key. We can use a database transaction or a lock? But that would reduce performance.
Given the scale, it might be acceptable to have duplicate long URLs with different short keys. Or we can do:
Step 1: Compute a hash (like SHA-256) of the long URL.
Step 2: Check in the database (with an index on the hash) if there's already a short key for that hash. If yes, return that short key.
Step 3: If not, generate a new short key and store with the hash.
But then we have to store the hash in the database (and index it). And we have to handle the race condition: two requests for the same long URL at the same time might both not find the hash and then both generate a new short key. To avoid that, we can use a transaction with a unique constraint on the hash? But then one of them will fail and we can retry by reading the existing one.
This adds complexity. For simplicity, let's not deduplicate by long URL.
19. Custom short URLs:
We need to check if the custom short key is available. We can try to write it in the database with a condition that the key doesn't exist. If the write fails because the key exists, we return an error.
code
But note: we might have a separate table for custom short keys? Or we can use the same table. We can have a flag for custom.
20. Analytics:
We can record each click (when a short URL is accessed) by:
- Incrementing a click count for the short key in the database.
- Storing additional data (timestamp, IP, user agent, referrer) in a separate table (or in a log stream that goes to a data warehouse for analysis).
code
But for real-time analytics, we might want to show the click count on the short URL. So we can update the click_count in the same row. But then we are writing on every click, which is a huge write load.
Alternatively, we can use a cache to count clicks and then periodically flush to the database. Or use a distributed counter (like in DynamoDB with atomic increment) but that might be expensive.
We can also use a separate service for analytics that is eventually consistent.
For simplicity, we can just increment a counter in the database (if the DB supports atomic increment). But with billions of clicks, that might be too many writes.
We can use a write-behind cache: count in Redis and then every N clicks or every T seconds, write to the database.
But then the click count might not be exactly real-time.
Since we are designing a basic system, we can skip real-time analytics and just log the clicks and then process the logs asynchronously.
21. Expiration of short URLs:
We might want to set an expiration date. Then when redirecting, we check if the short URL has expired and return an error if so.
Security:
- Validate the long URL to avoid XSS? Actually, we are redirecting, so we are setting the Location header. We must be careful not to allow JavaScript: URLs? We can blacklist certain schemes (like javascript:) and only allow http, https, ftp, etc.
Rate limiting:
- We can use a token bucket algorithm per IP or per user (if authenticated) to limit the number of shorten requests.
Monitoring:
- Monitor the number of shorten requests, redirects, error rates, latency.
Putting it together:
code
Components:
code
26. Summary of design:
code
- Web servers: stateless, run in multiple instances behind a load balancer.
- Use a distributed ID generator (like Snowflake) to generate 64-bit IDs, then encode in base62 to get short keys (variable length, up to 11 characters).
- Database: DynamoDB table with primary key short_key, and attributes: long_url, created_at, expires_at, click_count, custom (boolean), user_id (optional).
- Cache: Redis cluster. Store: key=short_key, value=long_url (and maybe TTL if we have expiration). Also, for rate limiting, we can store counters in Redis.
- For redirects:
try cache.get(short_key). If found, then:
increment a click counter in Redis (or use a separate key for counting) and then redirect.
If not found, do a strongly consistent read from DynamoDB. If found, set in cache and redirect. If not, 404.
- For shortening:
Validate long_url.
If custom short:
Validate the custom key.
Try to write to DynamoDB with condition attribute_not_exists(short_key). If fails, return error.
Then write to cache (set key to long_url, with TTL if expires_at is set).
Else:
Generate a new short_key from ID generator.
Write to DynamoDB (without condition, because we know it's new).
Write to cache.
Return short_url.
- For rate limiting on shorten endpoint: use Redis to count requests per IP (or per user) and limit.
- For analytics:
We can increment the click_count in DynamoDB on every redirect? But that would be a huge write load. Instead, we can:
- Increment a counter in Redis (for that short_key) and then periodically (every minute or so) flush the counters to DynamoDB.
- Also, we can log each click (with timestamp, IP, user agent) to a queue (like Kafka) and then process for detailed analytics.
- Expiration:
When redirecting, check if the current time is after expires_at (if set). If expired, return 410 (Gone) or 404.
- Custom short key format: only allow [a-zA-Z0-9] and length between 1 and 20? We can set a minimum and maximum.
27. Scaling:
code
- Web servers: can scale horizontally.
- Cache: Redis cluster can scale by sharding.
- Database: DynamoDB scales automatically by partitioning.
But note: if we use a distributed ID generator, we have to make sure it can generate unique IDs at scale. Snowflake can generate thousands per second per node, and we can have multiple nodes.
28. Potential issues:
code
- Hot keys: some short URLs might be very popular (e.g., from a popular tweet). Then the same key is accessed very frequently. We can cache it in Redis and also use a CDN for the redirect? But the redirect is a dynamic request (we have to look up the long URL). We can set a long TTL in cache for popular keys. Also, we can use multiple cache replicas.
- Distributed ID generator might become a bottleneck? We can have multiple ID generator servers, each with a unique machine ID.
29. Alternatives:
code
- Use a database that auto-increments and then shard by the short_key prefix? But then we have to manage sharding.
- Use a hash-based approach: take the first 7 characters of a hash of the long URL. But then we have to handle collisions (by appending a salt and retrying). This might be acceptable if we don't have too many URLs. But with billions, it might be hard.
30. Conclusion:
code
We'll go with the distributed ID generator and base62 encoding. This gives us a fixed keyspace (up to 2^64) and no collisions.
We'll use DynamoDB for the main storage and Redis for caching.
We'll handle custom short keys by checking existence with a conditional write.
We'll handle analytics by using Redis counters and a background job to update DynamoDB, and also log clicks to a queue for detailed analysis.
We'll rate limit the shorten endpoint.
We'll validate URLs and custom keys.
We'll handle expiration.
We'll use a load balancer and multiple web server instances.
31. Diagrams:
code
We can draw a diagram, but since this is text, I'll describe:
Client -> [LB] -> [Web Server 1, Web Server 2, ...]
Each web server:
- Has a connection to Redis cluster.
- Has a connection to DynamoDB (or uses AWS SDK).
- May have a connection to the distributed ID generator (or use a library that generates IDs locally if we assign machine IDs).
For analytics:
Web server on redirect -> push click event to Kafka (or SQS) -> Analytics service -> Data warehouse (like Redshift) or another DynamoDB table for click logs.
But for simplicity, we can just update the click_count in DynamoDB (using Redis to batch the increments). And also log to a file or stream for further analysis.
32. Detailed steps for redirect with click counting:
code
33. Rate limiting for shorten:
code
We can use a token bucket in Redis. For each IP (or user_id), we allow, say, 100 requests per hour.
Steps:
When a request comes to shorten:
key = "rate_limit:" + ip + ":" + current_hour (or day)
current = redis.incr(key)
if current == 1:
redis.expire(key, 1 hour)
if current > 100:
return 429
We can also have a separate rate limit for custom short keys? Maybe not.
34. URL validation:
code
We should validate that the long_url is a valid URL and uses an allowed scheme (http, https, ftp, etc.). We can use a library.
Also, we should check the length (max 2048?).
35. Custom short key validation:
code
Only allow [a-zA-Z0-9] and length between 4 and 20? We can set a minimum to avoid too short (which might be guessable) and maximum for storage.
36. Expiration:
code
When creating a short URL, we can set an expiration time (optional). Then when redirecting, if current time > expires_at, return 404 or 410.
We can store expires_at in DynamoDB and also in Redis (so we don't have to check DynamoDB every time). But then if we update the expiration? We don't support updating.
We can store the expiration in Redis as well? But then we have to update both.
Alternatively, we can store only in DynamoDB and check on every redirect (if we read from DynamoDB). But if we read from cache, we don't have the expiration.
So we should store the expiration in the cache value? We can store a JSON in cache: { "long_url": "...", "expires_at": ... }
Then when we redirect, we check the expiration in the cached object. If expired, we delete from cache and return 404.
But then if we update the expiration in DynamoDB (if we allow update) we have to update the cache.
Since we don't support update, we can set the expiration only at creation.
So:
On shorten:
If expiration provided, store in DynamoDB and also in cache (as part of the value).
On redirect:
If cache hit, check the expiration. If expired, delete from cache and return 404.
If cache miss, read from DynamoDB (with strong consistency) and then set in cache (with expiration as TTL? or store the expires_at in the value). We can set the TTL in Redis to the remaining time until expiration? But then if the expiration is far, we don't want to keep it in cache forever? We can set a max TTL? Actually, we can set the TTL in Redis to the time until expiration (if within a certain limit) or a default? But then if the expiration is in a year, we don't want to keep it in cache for a year.
Alternatively, we can store the expires_at in the cache value and then check on every read. But then we have to check the expiration even if the key is in cache. We can set a TTL in Redis to a fixed value (like 1 day) and then if the key is still in cache but the expiration is in the future, we are okay. But if the expiration is in 1 hour and we set TTL to 1 day, then after 1 hour the key is still in cache but expired. So we have to check the expiration in the value.
So we store in cache:
{
"long_url": "...",
"expires_at": <timestamp>
}
Then when we get from cache, we check if expires_at is in the past. If yes, delete and return 404.
But then we are storing more data in cache.
Alternatively, we can store two keys in cache:
- One for the long_url (without expiration) and one for the expiration? Not efficient.
Given that we are already storing the long_url, storing an extra field is acceptable.
37. Final design:
code
38. DynamoDB TTL:
code
We can set a TTL attribute (say 'expiration_time') on the DynamoDB item (if expires_at is provided) so that DynamoDB automatically deletes the item after expiration. But note: DynamoDB TTL is eventually consistent and may take up to 48 hours to delete. So we still have to check on read.
So we set the TTL attribute, but also check on read.
39. Summary:
code
We have a basic design that should scale and handle the requirements.
Let's write the answer in a structured way.
Note: This is a high-level design. We can dive deeper into each component if needed.</think>
I'll design a scalable URL shortening service similar to Bitly. Here's a comprehensive system design:
1. System Requirements
Functional Requirements:
Shorten long URLs to short URLs (e.g., short.url/abc123)
Redirect from short URL to original long URL (301/302 redirect)
1. User clicks short.url/abc123
2. Load balancer routes to nearest web server
3. Check Redis cache:
- Cache HIT: Verify expiration, increment counter in Redis, redirect
- Cache MISS: Query DynamoDB (strongly consistent read)
4. If found in DB:
- Check expiration → 410 Gone if expired
- Set in Redis (with TTL = min(1 day, time_to_expire))
- Increment click counter (Redis)
- Return 301/302 redirect
5. If not found: 404 Not Found
4.5 Write Path (Shortening)
code
1. Validate long_url (format, scheme, length)
2. Check rate limit (IP/user)
3. If custom_short provided:
- Validate format (allowed chars, length)
- Check availability (DB conditional write)
4. Else:
- Generate short_key via ID generator → base62
5. Write to DynamoDB (with TTL if expires_at set)
6. Write to Redis (with TTL)
7. Publish event to Kafka for async analytics
8. Return short_url
4.6 Click Analytics Pipeline
code
Web Server → Increment Redis counter (key: click:{short_key})
→ Push event to Kafka: {short_key, timestamp, IP, UA, referrer}
→ Return redirect immediately (user doesn't wait)
Kafka Consumers:
1. Click aggregator (every 5 min):
- Batch update DynamoDB click_count
- Aggregate by hour/country
2. Detailed analytics processor:
- Write to ClickHouse/Redshift for complex queries
- Build user-specific dashboards
3. Real-time dashboard (optional):
- Use Redis HyperLogLog for unique visitors
- Sliding window counters for recent activity
5. Scaling Considerations
5.1 Database Scaling
DynamoDB/Cassandra: Partition by short_key prefix (consistent hashing)
Hot key problem: Popular URLs (e.g., from news sites) → cache aggressively
Write scaling: Use write sharding if >10K writes/sec
5.2 Cache Strategy
Redis Cluster: Sharded by short_key
Cache policies:
Hot URLs: TTL 24 hours
Normal URLs: TTL 1 hour
LRU eviction for overflow
Cache warming: Pre-populate popular URLs from analytics
5.3 ID Generation
Snowflake-style: 64-bit ID (timestamp + machine ID + sequence)
Zookeeper/Etcd: For machine ID coordination
Throughput: 10K+ IDs/sec per node
5.4 Rate Limiting
IP-based: Token bucket (100 req/min per IP)
User-based: Higher limits for authenticated users
Implementation: Redis with Lua scripts for atomicity
Rate limit custom alias attempts (5 per hour per user)
Validate: length 3-30, alphanumeric + hyphens, no reserved words
6.2 Security
Spam/abuse detection:
Check against phishing/malware databases
Rate limit per domain
CAPTCHA after threshold
XSS prevention: Sanitize User-Agent, Referrer before display
SSL: All traffic HTTPS-only
6.3 Analytics Query Patterns
sql
-- Total clicks for URL in last 7 days
SELECT COUNT(*) FROM click_events
WHERE short_key = 'abc123'
AND click_time > NOW() - INTERVAL '7 days';
-- Top referrers
SELECT referrer, COUNT(*) as clicks
FROM click_events
WHERE short_key = 'abc123'
GROUP BY referrer
ORDER BY clicks DESC
LIMIT 10;
-- Geographic distribution
SELECT country_code, COUNT(*)
FROM click_events
WHERE short_key = 'abc123'
GROUP BY country_code;
7. Failure Handling
7.1 Cache Failure
Fallthrough to database (slightly higher latency)
Circuit breaker pattern if DB overloaded
7.2 Database Failure
Read replicas for scaling
Multi-region replication (active-active)
Failover to cached redirects (stale data acceptable for redirects)
7.3 Data Loss Prevention
Write-ahead logging: All writes to Kafka before DB
Regular backups: Daily snapshots to S3/Blob storage
Cross-region replication: For disaster recovery
8. Monitoring & Alerting
Key Metrics:
Redirect success rate (target: 99.99%)
P99 latency (target: <200ms)
Cache hit rate (target: >90%)
Error rates (4xx/5xx)
Queue lag (Kafka consumer lag)
Alerts:
Redirect success rate <99.9%
Latency P99 >500ms
DB replication lag >1 min
Cache hit rate <80%
9. Cost Optimization
Storage:
S3 Intelligent Tiering for click logs
DynamoDB auto-scaling
Cache:
Redis reserved nodes for steady load
Spot instances for analytics workers
CDN:
Cache redirect responses (with Cache-Control: public, max-age=3600) for popular URLs
10. Evolution Path
Phase 1: Basic service with DynamoDB + Redis
Phase 2: Add analytics pipeline (Kafka + ClickHouse)
Phase 3: Multi-region deployment
Phase 4: Advanced features (QR codes, bulk upload, team management)
11. Technology Stack Example
Component
Technology Options
Web Framework
Express.js (Node), Flask (Python), Spring Boot (Java)
Load Balancer
Nginx, HAProxy, AWS ALB
Cache
Redis Cluster, ElastiCache
Primary DB
DynamoDB, Cassandra, ScyllaDB
Analytics DB
ClickHouse, BigQuery, Redshift
Queue
Kafka, RabbitMQ, SQS
ID Generator
Snowflake, Sonyflake, UUID v7
Monitoring
Prometheus + Grafana, CloudWatch, Datadog
Deployment
Kubernetes, ECS, Cloud Run
Key Design Decisions & Trade-offs:
Consistency vs Availability: For redirects, favor availability (eventual consistency acceptable). For shorten operations, require strong consistency.
Cache Invalidation: Never invalidate hot URLs proactively. Let TTL expire. For revoked URLs, explicitly delete from cache.
Analytics Latency: Accept eventual consistency (minutes delay) for click counts to reduce DB write load.
Sequential IDs: Reveal total URLs count but ensure no collisions. Random hashes hide count but require collision handling.
TTL Strategy: Separate TTL for cache (short) and DB (long) to balance freshness and load.
This design handles billions of redirects monthly with sub-100ms latency, while providing useful analytics and maintaining high availability. The system can start simple (single region, DynamoDB + Redis) and scale horizontally as needed.
But if we are using a distributed ID generator, we don't have to worry about the same long URL being shortened multiple times? We can choose to allow or disallow duplicate long URLs.
Option: allow duplicate long URLs but with different short keys? Or same short key for same long URL? It depends on the product.
Let's assume we want to avoid duplicates for the same long URL (to save storage and to have a consistent short key for the same URL). Then we can:
Compute a hash of the long URL and check if we already have a short key for that hash. But then we need a separate index on the hash of the long URL.
Alternatively, we can let the user decide: if they try to shorten the same long URL again, we return the existing short URL? But then we need to check by long URL.
For simplicity, let's not deduplicate by long URL. We allow the same long URL to be shortened multiple times and get different short keys.
Let's calculate:
If we use 7 characters from 62, we have 62^7 = 3.5e12 possibilities. That's 3.5 trillion. If we have 1 billion short URLs, the probability of collision (by chance) is very low (birthday paradox: for 1 billion, probability of at least one collision is about 1 - exp(-1e18/(2*3.5e12))? Actually, let's compute:
n=1e9, N=3.5e12, probability of collision ~ 1 - exp(-n^2/(2N)) = 1 - exp(-1e18/(7e12)) = 1 - exp(-1.4e5) ~ 1. So actually, with 1 billion and 3.5 trillion, the probability is very high? Wait, I made a mistake.
The formula for the probability of at least one collision in n draws from N is approximately 1 - exp(-n(n-1)/(2N)). For n=1e9, n(n-1)/2 is about 5e17. Then 5e17 / 3.5e12 = about 142857. So the exponent is -142857, which is a very small number, so the probability is almost 1. So with 1 billion and 3.5 trillion, we will have many collisions.
We need a larger keyspace. 8 characters: 62^8 = 2.18e14. Then n=1e9: n(n-1)/2 ~5e17, divided by 2.18e14 = about 2293. So again, probability is almost 1.
9 characters: 62^9 = 1.35e16, then 5e17/1.35e16 = 37, so still high.
10 characters: 62^10 = 8.39e17, then 5e17/8.39e17 = 0.6, so probability of collision is about 1 - exp(-0.6) = 0.45. So for 1 billion, we have 45% chance of at least one collision.
11 characters: 62^11 = 5.2e19, then 5e17/5.2e19 = 0.0096, so probability ~ 0.0095 (0.95%).
So to have a low probability of collision for 1 billion short URLs, we need at least 11 characters. But we want short URLs to be as short as possible. So we need a way to avoid collisions: by checking and retrying. But if we are generating random strings, we might have to retry multiple times.
Alternatively, we can use an auto-increment ID and then encode it. Then we are guaranteed no collision, but the short keys will be sequential (which might be a security issue? people can guess the next one). We can shuffle the ID by using a bijective function (like a Feistel network) to make it non-sequential. Or we can use a random salt and then encode the ID? But then we need to store the mapping.
Another idea: use a hash of the long URL (like MD5) and take the first 7 characters. But then we have to handle collisions (two different long URLs having the same first 7 characters of MD5). We can then try the next 7, or append a salt and retry.
Given the complexity, a common approach is to use a distributed ID generator (so we have a unique number) and then encode that number in base62. This gives us a fixed length (depending on the number of IDs we generate). Initially, with 64-bit IDs, we can have up to 2^64 (~1.8e19) URLs. With base62, that's at most 11 characters. And we can have variable length: as the ID grows, the string gets longer. But we can set a fixed length by using leading zeros? But then we waste some keyspace.
Alternatively, we can use a shorter ID by using a larger character set (like base64 or base58) but then we have to be careful with URL-safe characters.
Let's stick with base62 (URL-safe) and use a distributed ID generator. Then we don't have to worry about collisions.
Steps for generating short key without custom:
1. Get a unique ID from the distributed ID generator (like Snowflake).
2. Encode the ID in base62 (without leading zeros? but then we have variable length). We can pad to a fixed length? But then we might have to use more characters than needed.
Alternatively, we can use a random string of fixed length (say 7) and if we get a collision (which is rare at first) we try again. But as we get more URLs, the probability of collision increases and we might have to try many times.
Given the trade-offs, I think using a distributed ID generator is more reliable and scalable.
- Load balancer (like Nginx or cloud LB)
- Web servers (in multiple zones, stateless)
- Distributed ID generator service (or library included in the web server)
- Cache: Redis cluster (for storing short_key -> long_url and also for rate limiting)
- Database: DynamoDB (or Cassandra) for storing short_urls table with:
short_key (partition key), long_url, user_id (if any), created_at, expires_at, click_count, custom (boolean), hash (if we do deduplication)
- For analytics writes: we can write to a queue (like Kafka) and then have a service that writes to a data warehouse (or to a separate table for click logs).
Steps for shortening (without custom):
1. Receive POST /shorten with long_url.
2. Validate long_url (format, scheme).
3. Generate a unique short_key:
a. Get a unique ID from the distributed ID generator.
b. Encode the ID in base62 (without leading zeros? but then we have variable length). We can set a minimum length? Or just use as is. The length will grow as IDs increase.
4. Write to DynamoDB:
Item: {
short_key: <base62 of ID>,
long_url: <long_url>,
created_at: <now>,
expires_at: <if provided>,
custom: false,
click_count: 0
}
5. Also write to cache: cache.set(short_key, long_url, ex=expiration if any).
6. Return short_url = base_url + short_key.
Steps for custom short:
1. Validate the custom short key (only allowed characters, length, etc.)
2. Check if the short_key already exists in DynamoDB (using a conditional write? or read first?).
3. We can try to write with a condition that the attribute_not_exists(short_key). If it fails, the short key is taken.
4. If write succeeds, then set in cache and return.
Steps for redirect:
1. GET /:short_key
2. Look up in cache by short_key.
3. If found, increment the click count in cache (or in a separate cache for counts) and redirect.
4. If not in cache, read from DynamoDB (with strong consistency? Actually, we can use eventually consistent because if we just wrote and then immediately read, we might not see it. But we are writing to cache after DB write, so the next read should be in cache. However, if we are reading from DB and the write hasn't propagated, we might not find it. But we are writing to DB and then to cache. So if the cache write fails, we are reading from DB and we might not see the latest write? We are using a distributed system, so we have to consider.
We can do:
- Read from cache. If miss, read from DB with strong consistency (to get the latest). Then write to cache.
But strong consistency in DynamoDB is more expensive and slower. Alternatively, we can write to cache and then read from cache (which is eventually consistent) but then we might have a stale cache? Actually, we want the latest. So for a newly created short URL, we want to make sure that the redirect works immediately.
How about:
- When we create a short URL, we write to DB and then write to cache. Then when we redirect, we read from cache. If the cache write fails, we read from DB (with eventually consistent read) and then write to cache again? But if the DB write hasn't propagated to all replicas, we might not read the latest.
To avoid that, we can use a write-through cache: every write goes to both DB and cache. And every read goes to cache, and if miss, then read from DB (with strong consistency?) and then update cache.
But strong consistency for every redirect read is expensive.
Alternatively, we can design the system to have a single writer per short_key? But we have multiple web servers.
Another idea: use the cache as the primary for redirects and then asynchronously persist to DB. But then we lose data if cache fails.
Given that redirects are critical and we need high availability and low latency, we can:
- Use a cache (Redis) that is highly available and persistent (with AOF or RDB) for the short_key -> long_url mapping. And then asynchronously write to the database for persistence and analytics.
But then we have to handle cache eviction. If the cache evicts a key, then we won't have it and we have to read from DB. But if we didn't write to DB, we lose it.
So we must write to DB and cache. And we must make sure that the DB write is durable.
Let's do:
- For shorten: write to DB (with strong consistency? We can use DynamoDB with strong consistency for writes? Actually, DynamoDB writes are durable and then replicated. We can use conditional writes for custom short keys.
- Then write to cache (if cache write fails, we can retry or log an error but still return the short URL? Then if the cache doesn't have it, we read from DB. But if we read from DB and the write hasn't propagated? We are writing to DB and then to cache. The DB write is synchronous (we wait for it to succeed). Then we write to cache asynchronously? But then if the cache write fails and we don't write to cache, then the next read will go to DB and should see the write because we waited for the DB write to complete.
So:
Write to DB (synchronously, wait for success).
Then write to cache (asynchronously, but we don't wait for it).
Then return short URL.
Then for redirect:
Read from cache. If found, redirect.
If not found, read from DB (with eventually consistent read? But we want the latest. Since we waited for the DB write to complete, we can use eventually consistent reads for the same key? Actually, DynamoDB eventually consistent reads might not see the latest write immediately. So we might read from a replica that hasn't received the write yet. Then we get a miss and then we have to return 404? But we know we just wrote it.
To avoid that, we can use strongly consistent reads for the first few seconds? Or we can set a flag in the cache that we are writing? This is getting complex.
Alternatively, we can use a cache that is write-through and read-through, and we invalidate the cache only when we update the DB? But we never update the long_url? Actually, we might allow users to update the long_url? That's another feature.
Let's assume we don't update the long_url. Then we can:
- When we write a new short URL, we write to DB and then set in cache (with a long TTL).
- When we read, we read from cache. If miss, we read from DB (with eventually consistent read) and then set in cache.
But if we just wrote and the cache write hasn't happened, then we read from cache (miss) and then read from DB. If the DB read is eventually consistent, we might not see the write. However, DynamoDB's eventually consistent reads might return the latest data within a second? Actually, it's typically within a second, but not guaranteed.
To guarantee that we see the write immediately, we can use a strongly consistent read for the DB read. But that doubles the read capacity units and is slower.
Another idea: when we write to DB, we also set a flag in the cache that the key is being written? Then when we read, if we see that flag, we wait and retry? That's not good.
Given the complexity, and since we are designing for a service that might have high traffic, we can accept that a very small fraction of newly created short URLs might not be available immediately for redirection (if the cache write fails and the DB read is eventually consistent and we read from a stale replica). But that's not acceptable.
So let's use:
- For shorten: write to DB (with strong consistency? Actually, DynamoDB writes are always durable and then replicated. We don't have strong/eventual for writes. For reads, we can choose.
We can do:
Write to DB (synchronous, wait for success).
Then write to cache (synchronously? but that adds latency). We can do it asynchronously but then we risk the cache not having it.
But if we write to cache synchronously, then we add latency to the shorten request. We can do:
Step 1: write to DB.
Step 2: write to cache.
Step 3: return.
Then when we redirect, we read from cache. If the cache write succeeded, we are good. If the cache write failed, then we read from DB (with strongly consistent read) and then write to cache again.
So:
Redirect:
read from cache -> if found, redirect.
else:
read from DB with strong consistency -> if found, write to cache and redirect.
else, 404.
This way, we are guaranteed to see the latest write (because if the cache write failed, we do a strong DB read). But strong DB reads are more expensive.
We can also use a cache that is persistent and highly available (like Redis with replication and persistence) so that cache writes rarely fail.
Given the trade-offs, I think this is acceptable.
We want to count the click and then redirect.
Option 1:
- Increment a Redis key for the short_key (e.g., "click:<short_key>") by 1.
- Then redirect.
Then a background job reads the Redis counters and updates the click_count in DynamoDB.
But then the click count in DynamoDB is not real-time.
Option 2:
- Use DynamoDB atomic increment on the click_count for the short_key. But that would be a write on every click, which is expensive and might throttle.
Given the scale, we might have billions of clicks per day. That's thousands per second. DynamoDB can handle that if we partition properly (by short_key). But it's still a lot of writes.
We can use a hybrid approach:
- For the first N clicks (say 1000) for a short URL, we update DynamoDB on every click (so that the count is real-time). Then after that, we switch to batch updates (every 10 minutes) for that key.
But that adds complexity.
Alternatively, we can use a time-series database for clicks and then aggregate. But for the click count displayed on the short URL, we can eventually consistent.
Since the requirement is not specified, let's assume we don't need real-time click count. We can update the click_count every 5 minutes.
So:
On redirect:
- Increment a Redis counter for the short_key (with an expiry of, say, 10 minutes).
- Redirect.
Background job (every 5 minutes):
- For each key in Redis that has a count, read the count and then update DynamoDB (add the count to the existing click_count). Then delete the key from Redis (or reset).
This way, the DynamoDB click_count is eventually consistent (within 5 minutes).
But if we want to show the click count on the short URL page (if we have one), we might show the count from DynamoDB, which is delayed.
If we want real-time, we can read from Redis (but then we have to expose Redis to the web server? We are already using Redis). We can have the web server read the current count from Redis (for the short_key) and then display it? But then we are reading from Redis for every page view? That might be acceptable.
Alternatively, we can have two counters: one in Redis (real-time) and one in DynamoDB (persisted). Then for the display, we can show the sum of the two? But then we have to read both.
Given the complexity, let's stick with batch updates for the click count in DynamoDB and not show real-time counts.
If we need real-time counts, we can use Redis to store the current count (and then the background job flushes). Then for displaying the count, we can read from Redis (with a fallback to DynamoDB if Redis doesn't have the key?).
But then we have to make sure Redis has the key. We can initialize the Redis key when we create the short URL? But then if we have a new short URL, we might not have a Redis key until the first click? Then we would read from DynamoDB for the count.
We can do:
When creating a short URL, set the Redis key to 0 (with a TTL? or no TTL). Then on click, increment. Then when displaying, read from Redis. If the key doesn't exist (maybe expired), then read from DynamoDB and set in Redis.
But then we have to set a TTL for the Redis key to avoid having all keys in Redis forever. We can set a TTL of 1 day? Then after 1 day of inactivity, the key expires and we read from DynamoDB.
This is getting complex.
Let's simplify:
We don't show the click count in real-time. We update the click_count in DynamoDB every 5 minutes (or every 1000 clicks, whichever comes first). And we don't show the count on the redirect page (we just redirect). If we want to show the count on a separate analytics page, we can query DynamoDB (which is eventually consistent).
So:
On redirect:
- Increment a Redis key (with a TTL of, say, 1 hour) for the short_key.
- Then redirect.
Background job (every 5 minutes):
- Scan Redis for keys that match "click:*" and then for each key, get the count and update the corresponding short_key's click_count in DynamoDB (using atomic increment). Then delete the key.
But scanning Redis might be expensive. We can use a Redis sorted set by timestamp? Or we can have a separate Redis database for these temporary counters and then use the `SCAN` command every 5 minutes? Alternatively, we can use a Redis stream or a list that we push to and then have a consumer.
Alternatively, we can use a Redis hash for each short_key? But then we have to expire the hash.
Let's do:
When we create a short URL, we set a key: "click:<short_key>" with value 0 and no expiration? But then we have to manage expiration.
We can set an expiration of 1 day for the click counter in Redis. Then we don't have to clean up old keys. And then the background job runs every 5 minutes and for each key that exists (and hasn't expired) it flushes the count to DynamoDB and then deletes the key? But if we delete the key, then the next click will create it again and start from 0? That's not good because we would lose counts between flushes.
Actually, we want to accumulate counts for 5 minutes and then flush and reset to 0? But then if we have a key that is not being clicked, we don't want to reset it to 0? We only want to reset after we flush.
So:
Background job:
- For each key in Redis that matches "click:*", get the value (count) and then:
Update DynamoDB: ADD click_count :count for the short_key (the key without the "click:" prefix).
Then delete the Redis key.
But then if a new click comes in after we delete and before the next flush, we create the key again and set to 1? That's acceptable because we are batching.
However, if we have a very popular key, we might be creating and deleting the same key every 5 minutes. That's acceptable.
But then we are losing the count that was just flushed? No, we are adding the count to DynamoDB and then resetting the Redis counter to 0 by deleting and then starting again.
But what if a click comes in exactly after we delete and before we set again? Then the key doesn't exist and we set it to 1. That's fine.
Alternatively, we can use a Redis hash to store multiple counters? Not necessary.
We can also use a Redis INCR command and then use a TTL of 1 hour. Then the key will automatically expire after 1 hour of inactivity. Then the background job runs every 5 minutes and for each key that exists, it flushes and then deletes? But if we delete, then the TTL is gone and if a new click comes, we create again. That's acceptable.
But if we delete the key, then the next click will create a new key and start from 0. So we are losing counts between the delete and the next click? Actually, we are flushing the count and then deleting. Then the next click creates a new key with count 1. So we are not losing counts because we already flushed the previous counts.
However, if we have a key that is clicked very frequently, we might have:
At time T1: count=1000.
Background job at T1+5min: flushes 1000 to DynamoDB and deletes the key.
At T1+5min+1sec: a click comes, creates key with value 1.
Then at T1+10min: flushes 1.
That's correct.
But what if the background job takes a long time and during that time, the key is being incremented? We are deleting the key and then the next increment will create a new key. But we are flushing the value at the moment we read it. So if we read 1000 and then delete, and then during the delete, there is an increment? Actually, Redis operations are atomic. But we are doing:
GET the key -> then DEL -> then update DynamoDB.
But between GET and DEL, there might be an INCR. Then we would lose that increment because we are flushing the old value and then deleting, and then the INCR after delete will set to 1 (but the previous value was 1000, and we flushed 1000, but then the INCR after delete sets to 1, so we lose the increment that happened between GET and DEL).
To avoid that, we can:
Use a Redis transaction (WATCH/MULTI/EXEC) to get and delete atomically? But then we are blocking other INCRs? Actually, we can use:
WATCH key
count = GET key
MULTI
DEL key
EXEC
But if the key changes between WATCH and EXEC, the EXEC fails and we retry.
Alternatively, we can use a Lua script to do:
local count = redis.call('GET', KEYS[1])
redis.call('DEL', KEYS[1])
return count
This is atomic.
So:
Background job (for each key):
Use a Lua script to atomically get and delete the key.
Then update DynamoDB with the count.
Then the next INCR will create a new key with value 1.
This way, we don't lose counts.
But note: if the key doesn't exist, the script returns nil, and we do nothing.
Components:
- Load balancer
- Web servers (stateless)
- Redis cluster (for caching and rate limiting)
- DynamoDB (for persistent storage)
- Distributed ID generator (if not built into the web servers)
Workflows:
Shorten (with custom):
POST /shorten
Body: { "long_url": "...", "custom_short": "mylink", "expires_at": "optional" }
Steps:
1. Validate long_url (scheme, length).
2. Validate custom_short (allowed chars, length).
3. Check rate limit for the IP (or user).
4. Try to write to DynamoDB with ConditionExpression: attribute_not_exists(short_key).
- If fails, return 409 (Conflict).
5. If write succeeds, then set in Redis:
key = short_key
value = { "long_url": long_url, "expires_at": expires_at (if provided) } as JSON.
Set TTL to the time until expiration if provided, or a default (like 1 year)? But we don't want to keep it forever? Actually, we want to keep it until expiration. So we can set the TTL to (expires_at - now) if provided, else a long TTL (like 1 year). But if the expiration is very far (like 10 years) we don't want to set a TTL of 10 years? We can set a max TTL (like 1 year) and then rely on the expiration check in the value? But then the key might stay in cache even after expiration.
Alternatively, we can set a fixed TTL (like 1 day) and then rely on the expiration in the value to check. But then if the key is in cache and the expiration is in the future, we are okay. If the expiration is in the past, we delete. So we can set a fixed TTL (say 1 day) and then when we read, we check the expiration in the value. But then after 1 day, the key might be evicted and we go to DynamoDB, which is okay.
Let's set a TTL of 1 day in Redis for all keys. Then we don't have to worry about very long TTLs. And we check the expiration in the value when we read from cache.
6. Return short_url.
Shorten (without custom):
Steps 1,3,4 (without custom_short condition).
4. Generate short_key from ID generator.
5. Write to DynamoDB (without condition) and then to Redis (same as above).
Redirect:
GET /:short_key
Steps:
1. Check rate limit for the IP (for redirects? maybe not, but we can if we want to prevent abuse).
2. Look up in Redis by short_key.
3. If found:
- Parse the JSON.
- Check if expires_at is set and current time > expires_at -> 410 (or 404) and delete from Redis.
- Else, increment the click counter in Redis (key: "click:"+short_key) by 1 (with no expiration? or set a TTL? We can set a TTL of 1 hour for the click counter key? But then if we don't get clicks for an hour, the key expires. That's okay because we only care about recent clicks for batching. But then if we get a click after an hour, we start from 0 again? We are batching every 5 minutes, so we want to accumulate for 5 minutes. We can set the TTL for the click counter key to 10 minutes (so that it expires if no clicks for 10 minutes). But then we might lose counts if the background job runs every 5 minutes and the key expires in between? We can set the TTL to 1 hour and the background job runs every 5 minutes, so we have 12 batches per key per hour at most. That's acceptable.
Actually, we don't need to set TTL for the click counter key because we are deleting it in the background job. But if we don't get any clicks for a long time, the key will stay. We can set a TTL of 1 day for the click counter key? But then if we have a key that is clicked once a day, we will have a key in Redis for each short_key that ever got a click? That might be a lot.
Alternatively, we can use a separate Redis database for these temporary counters and set a TTL of 1 hour. Then after 1 hour of inactivity, the key expires. And we run the background job every 5 minutes, so we are only flushing active keys.
Let's do:
For each click, we do:
redis.incr("click:"+short_key)
and set a TTL of 1 hour (if not set already). We can do this on every click? That might be expensive. We can set the TTL only when we create the key? But we don't know when it's created.
We can set the TTL when we create the key (on first click). Then on subsequent clicks, we don't set the TTL? But then if the key is already there, we don't reset the TTL? Then the key will expire 1 hour after the first click, even if there are subsequent clicks.
We want the TTL to be reset on every click? Actually, we want to keep the key as long as there are clicks within the last hour. So we can set the TTL on every click? That might be too many EXPIRE commands.
Alternatively, we can use a separate process that scans for keys that haven't been incremented in the last hour? Not efficient.
We can set the TTL to 1 hour on every click? That's an extra command per click. But we are already doing an INCR. So two commands per click. That might be acceptable.
But then we are setting the TTL on every click, which might be heavy.
We can set the TTL only when we create the key (on the first click). Then if we get clicks within the hour, the key will be there. But if we get a click at 59 minutes, then the key will expire at 60 minutes from the first click, even though we just got a click. So we might lose the last click if it comes right before expiration? Actually, the background job runs every 5 minutes and flushes the key. So if the key expires at 60 minutes and the background job runs at 55 minutes, it will flush and then the key expires at 60 minutes. Then a click at 61 minutes will create a new key with count 1.
That's acceptable because we are batching every 5 minutes, so we are not losing more than 5 minutes of clicks.
So:
On click:
count = redis.incr("click:"+short_key)
if count == 1:
redis.expire("click:"+short_key, 3600) # 1 hour
Then the key will expire 1 hour after the first click. If we get clicks continuously, the key will exist until 1 hour after the first click. But if we get a click after 1 hour, we start a new key.
Then the background job (every 5 minutes) will flush all keys that exist (that haven't expired) and then delete them.
But note: if the background job runs and flushes a key, it deletes it. Then the next click will create a new key and set the TTL again.
This seems acceptable.
So:
On redirect:
Increment the click counter in Redis (with TTL on first increment).
Then redirect.
Then the background job:
For each key in Redis that matches "click:*":
Use Lua script to atomically get and delete the key.
Then update DynamoDB: ADD click_count :count for the short_key (strip the "click:" prefix).
4. If cache miss:
Read from DynamoDB with strong consistency.
If found:
- Check expiration (if current time > expires_at) -> 410 and delete from DynamoDB? or just return 410? We can also delete from cache if it was there? But it wasn't in cache. We can delete from DynamoDB? Or just leave it? We can have a TTL on DynamoDB? We can set a TTL attribute on DynamoDB and use DynamoDB TTL to automatically delete expired items? That would be better.
Actually, we can set a TTL on DynamoDB items (using DynamoDB TTL feature) so that expired items are automatically deleted. Then we don't have to check expiration on every read? But we still have to check because the TTL deletion is eventually consistent (within 48 hours). So we have to check on read.
So:
If expired, return 410 and also delete from DynamoDB (or let TTL handle it) and also delete from cache if present? But we just had a cache miss.
We can also delete from DynamoDB immediately? But then if we have a cache miss and the item is expired, we can delete it from DynamoDB.
So:
If expired, delete from DynamoDB (if exists) and return 410.
If not expired:
Set in Redis (with TTL of 1 day? or until expiration? We can set the TTL to (expires_at - now) if within 1 day, else 1 day? But then we have to check expiration again when we read from cache.
We'll store in Redis: { "long_url": ..., "expires_at": ... } and set a TTL of 1 day (so that it eventually expires from cache even if the short_url doesn't have an expiration). Then when we read from cache, we check the expires_at.
Then redirect.
If not found in DynamoDB, return 404.
This should work.