A URL shortener converts a long URL into a compact link that is easy to share. When someone opens the short link, the system redirects them to the original destination.
Let’s define what the system should do, estimate its scale, and build a simple design. Then we’ll ask where that design could fail and solve those problems one by one.
Functional Requirements: What Should the System Do?
For the initial version, we’ll support four features:
- Create a short URL. Accept a valid HTTP or HTTPS URL and return a unique short link, such as
https://short.ly/aB3x9K. - Redirect to the original URL. Opening a known short link redirects the visitor to its destination. Unknown codes return a clear error.
- Support custom aliases. Users can request an alias such as
short.ly/my-blog. Reject aliases that are already taken or reserved. - Support link expiration. Users can optionally specify an expiration time. Once that time is reached, the link stops redirecting. Without an expiration time, the link remains valid.
Optional extensions, outside our initial scope:
- Analytics: Show total clicks and daily click counts, allowing a small delay in updates.
- Link management: Let authenticated owners list, inspect, and disable their links.
Analytics will be covered in a separate article. The APIs and data model here focus on the four core features.
Non-Functional Requirements: How Well Should It Perform?
These are project design goals, not claims about Bitly’s actual infrastructure.
| Requirement | Design goal |
|---|---|
| Low latency | Target p95 server-side redirect response time below 100 ms, excluding network travel time and destination-page loading. |
| High availability | Target 99.9% availability for redirects. |
| Scalability | Handle growing link volume and traffic spikes, including viral links. |
| Durability | Preserve successfully created mappings through expected instance failures and restarts, with a recovery plan for larger failures. |
| Correctness and consistency | Each code keeps one destination. Concurrent creation cannot overwrite it; a successful create must be readable in the same region even if Redis population fails. |
p95 means at least 95% of measured requests finish within the target. These latency and availability targets still require load tests and failure tests.
The central priority is fast, reliable redirection with correct, durable mappings.
Capacity Estimation
These are hypothetical usage assumptions. Our goal is to understand the scale well enough to guide design decisions, not to produce an exact infrastructure bill.
Traffic Assumptions
- 1 million new links per day
- 100 million redirects per day
- Peak traffic at 5× the average
- Five years of mapping retention
Our daily redirect volume is 100 times our daily creation volume. This is a read-heavy workload; it does not mean every individual link receives exactly 100 clicks.
Requests Per Second
A day has 86,400 seconds. For quick interview arithmetic, round this to 10⁵ seconds.
| Operation | Average RPS using 86,400 seconds | Approximate peak RPS: 5× |
|---|---|---|
| Create a link | 1,000,000 ÷ 86,400 ≈ 12 | 60 |
| Redirect | 100,000,000 ÷ 86,400 ≈ 1,160 | 5,800 |
RPS means requests per second. These rounded rates guide sizing; add headroom and load-test the complete redirect path. A viral link may receive a large share of the traffic even when the overall rate stays within these estimates.
Storage for URL Mappings
Assume an average mapping occupies 1 KB, including its URL, short code, timestamp, and storage metadata. Actual sizes vary; this is a sizing assumption.
1 M new links/day × 365 × 5 = 1.825 billion links
1.825 billion × 1 KB ≈ 1.8 TB, rounded to 2 TB
We use decimal units: 1 KB is 1,000 bytes. This is logical mapping data, excluding indexes, replicas, backups, and database overhead.
Five years is the sizing window, not permission to reuse old codes. Keep expired mappings, or retain a small reservation record containing short_code if archiving the destination. An old bookmark must never start pointing to a different site.
Redis Working Set
Assume 1 million frequently accessed mappings are cached at once, averaging 1 KB of serialized data each:
1 M cached mappings × 1 KB ≈ 1 GB of payload
This is independent of the roughly 2 billion mappings accumulated in storage. Cache hot links rather than every link. Actual Redis RAM also includes keys, data structures, expiry metadata, and headroom. Replicas need their own memory. Measure real entries before choosing capacity.
API Design
An easy way to begin is to look at each functional requirement and define the corresponding interface.
We need two endpoints: one to create a link, including an optional custom alias, and another to redirect visitors.
1. Create a Short Link
Endpoint: POST /api/v1/links
Request:
{
"original_url": "https://example.com/articles/url-shortener",
"custom_alias": "my-blog",
"expires_at": "2027-10-08T00:00:00Z"
}
original_url is required. custom_alias is optional; when absent, the system generates a code. expires_at is an optional future UTC timestamp in ISO 8601 format; when omitted, the link does not expire.
Response: 201 Created
{
"short_code": "my-blog",
"short_url": "https://short.ly/my-blog",
"original_url": "https://example.com/articles/url-shortener",
"expires_at": "2027-10-08T00:00:00Z"
}
| Status | Meaning |
|---|---|
400 Bad Request |
Invalid URL, alias, or expiration timestamp. |
409 Conflict |
Requested alias is taken or reserved. |
429 Too Many Requests |
Rate limit exceeded. |
503 Service Unavailable |
Creation cannot complete because of a temporary failure. |
The application applies per-client or per-IP limits to link-creation requests and returns 429 Too Many Requests when a limit is exceeded.
For this initial design, account management is outside scope. If authentication is added, derive the owner from the verified token rather than trusting a user ID in the request, and return 401 when authentication fails.
Submitting the same original URL again may create a different short link. We are not deduplicating destination URLs in this version.
2. Redirect to the Original URL
Endpoint: GET /{short_code}
GET /my-blog
The application looks up the code and returns:
HTTP/1.1 302 Found
Location: https://example.com/articles/url-shortener
Cache-Control: no-store
The browser follows the URL in the Location header.
Why 302 instead of 301? A 301 declares a permanent redirect and can be cached. We choose 302 with an explicit no-store policy so later visits continue reaching our service. This allows the service to enforce expiration and supports future disabling and click tracking. The status code alone is not a complete cache policy.
| Status | Meaning |
|---|---|
302 Found |
Mapping exists; redirect to its destination. |
404 Not Found |
Short code is unknown. |
410 Gone |
Short code exists, but the link has expired. |
503 Service Unavailable |
Lookup failed temporarily; we cannot determine the destination. |
A database failure must not be reported as “link not found.” The application returns 410 Gone when the mapping exists but its expires_at timestamp has passed.
High-Level Design: Start with the Four Core Features
Start with a client, load balancer, application, and durable links store. The application handles both creation and redirection. For this design, use DynamoDB with short_code as the partition key: each main operation reads or writes one mapping, without joins.
A PostgreSQL table with an indexed primary key is also a valid starting point. DynamoDB is our chosen implementation, not a requirement for every URL shortener.
1. Create a Short Link
Client → Load balancer → Application → DynamoDB
- Validate the request. Accept only a valid HTTP or HTTPS destination and, if supplied, a future expiration time.
- Generate a code. Choose six random Base62 characters, such as
aB3x9K. Problem 1 compares the alternatives. - Insert the mapping. Write
short_code,original_url,created_at, and optionalexpires_atintolinks. Use a conditional insert that succeeds only if this code is unused. The check and insert happen atomically, so concurrent requests cannot replace one another’s mapping. - Return the result. After DynamoDB acknowledges the write, construct
short_urlfrom the configured domain and code and return201 Created. No separateshort_urlfield is needed.
Each mapping is one item, so this operation needs one atomic conditional write rather than a transaction spanning several records. If a generated code collides, retry with another code, within a bounded attempt limit.
2. Redirect to the Original URL
Visitor → Load balancer → Application → DynamoDB → Redirect response
- Read
linksbyshort_code. Use a strongly consistent read of the table in this region so a just-created mapping can be found. - Check the result. An absent code returns
404 Not Found; a passedexpires_atreturns410 Gone. A failed database lookup returns503, not404. - Return the destination. For a valid mapping, return
302 FoundwithLocationandCache-Control: no-store. The browser then requests the destination site.
Problem 2 adds Redis to avoid repeated database reads for popular codes.
3. Support Custom Aliases
Client → Application → Conditional insert into the same links store
Validate the requested alias and reject reserved application paths such as api. Use the alias as short_code and perform the same conditional insert. If it is taken, return 409 Conflict; do not replace its destination or silently choose a different alias. Generated codes and aliases share one namespace.
4. Enforce Link Expiration
Read the mapping → Compare expires_at with server time → Redirect or return 410
Store an optional UTC deadline in links; no deadline means no expiration. Check it on every redirect, including Redis hits once caching is added. Expiry is a request-time rule, so a delayed cleanup job cannot keep a link valid.
Keep the code reserved after expiry. Do not use automatic deletion of the whole DynamoDB item as the mechanism for expiring links, because that could make the code available for reuse.
Problem 1: What If Two Links Get the Same Short Code?
There are several generation strategies. Let’s compare three.
First, Why Base62?
We’ll use this 62-character alphabet:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
Base62 produces alphanumeric codes that are straightforward to share and type. Standard Base64 contains + and /; URL-safe Base64 replaces them with - and _ and is also a valid choice. Our preference for Base62 is about the alphabet, not a claim that URL-safe Base64 is unsafe.
Codes are case-sensitive, so A and a represent different values. This distinction is required for the full Base62 code space.
| Length | Base62 combinations |
|---|---|
| 5 characters | 62⁵ = 916,132,832 ≈ 916 million |
| 6 characters | 62⁶ = 56,800,235,584 ≈ 56.8 billion |
| 7 characters | 62⁷ ≈ 3.52 trillion |
Six characters provide enough space for our five-year estimate of approximately 2 billion links.
Approach 1: Increment a Counter and Encode It
In the simplest version, the application keeps a counter variable in memory. For each new link, it atomically increments the counter and converts the resulting number to Base62. The increment must be atomic so concurrent requests cannot receive the same value. We’ll explain atomic increments later in this section.
How does integer encoding work?
With our alphabet, A = 0, B = 1, …, Z = 25, a = 26, …, z = 51, 0 = 52, …, 9 = 61.
To encode 12345, repeatedly divide by 62:
| Division | Quotient | Remainder | Character |
|---|---|---|---|
| 12345 ÷ 62 | 199 | 7 | H |
| 199 ÷ 62 | 3 | 13 | N |
| 3 ÷ 62 | 0 | 3 | D |
Read the characters bottom to top: 12345 → DNH.
Check the result:
3 × 62² + 13 × 62 + 7 = 12345
For exactly six characters, pad with our zero character, A: AAADNH.
The alphabet order is our choice; changing it changes the output. This is integer base conversion, not encoding the text "12345" with a Base64 function.
Where the Counter Approach Breaks
The counter is simple on one process, but production introduces several failure modes:
| Failure mode | What can go wrong | Safeguard |
|---|---|---|
| Application restarts | An in-memory counter resets and reuses issued values. | Keep the counter in a durable external system. |
| Multiple application instances | Independent counters generate the same value. | Give every instance access to one shared counter, such as Redis. |
| Concurrent increments | A read-modify-write sequence lets two requests read the same value. | Use Redis INCR, an atomic operation on a single primary. |
| Counter failure or data loss | Creation stops, or a restored counter reissues old values. | Configure persistence and failover, then enforce uniqueness on short_code in the mapping database. |
| Predictable sequence | Someone can guess nearby codes and enumerate links. | Do not treat codes as secrets; use random codes when they must be difficult to guess. |
Concurrency deep dive: Why does
INCRwork while read-modify-write fails? See Understanding Concurrency, Part 1: Counters, Locks, Redis, and Databases for a visual explanation of race conditions, atomic operations, and locks.
Approach 2: Combine a Timestamp, Instance ID, and Counter
Build an identifier from timestamp + instance ID + counter, using defined fields or bit ranges rather than ambiguous text concatenation.
- The timestamp separates time intervals.
- The instance ID separates generators.
- The counter separates values generated within one interval by one instance.
This resembles a Snowflake-style identifier and avoids a shared increment for every creation.
Why do we need an instance ID? Two instances might generate a value at the same time with the same local counter.
Does a timestamp solve restarts automatically? No. A restart within the same time interval, a reused instance ID, or a clock moving backward can cause duplicates unless the generator handles these cases.
We must manage instance IDs, clock rollback, counter exhaustion, and restarts. Depending on the identifier’s bit length, encoding it may require more than six characters.
This approach is useful, but adds coordination rules to what we want to keep simple.
Approach 3: Generate a Random Code and Retry
Choose a uniformly random integer from 0 to 62⁶ − 1, then encode it into six Base62 characters. Alternatively, independently choose six characters uniformly from the alphabet. Use a secure random generator.
What if the same code is generated again?
- Generate a code.
- Attempt an atomic insert that succeeds only if the code is unused.
- On a confirmed collision, generate another and retry.
- Return success only after the mapping is stored.
Use a bounded retry limit, such as five attempts, and return a temporary error if all fail. Handle database timeouts separately: a timeout does not prove the write failed or that a collision occurred. Read back or otherwise resolve an uncertain write before treating it as a new attempt.
How likely is a collision?
If 2 billion of the 56.8 billion possible codes are already reserved, a new random code has about a 3.5% chance of collision and a 96.5% chance of success.
When a collision occurs, generate another code and retry. At this occupancy, creating 1,000 links would require about 1,036 attempts: only 36 extra attempts, or roughly 1.04 attempts per link.
Custom aliases and expired links also count as reserved codes, but we assume custom-alias volume is small for this estimate. We do not reuse an expired code because old bookmarks could then redirect to a different destination.
Does this mean collisions are rare across the whole system? No. At billions of creations, encountering collisions is effectively certain. The 3.52% figure describes the next attempt at that occupancy, not the probability of ever seeing a collision.
Can a primary key alone prevent replacement?
In SQL, use a unique key and an ordinary insert that rejects duplicates. Avoid an upsert that overwrites mappings.
In DynamoDB, a normal PutItem can replace an existing item with the same key. Use a conditional write:
ConditionExpression: attribute_not_exists(short_code)
This makes the absence check and insertion atomic. Checking first and inserting later is unsafe because two requests could both observe an unused code.
For a taken custom alias, return 409 Conflict rather than silently choosing another alias. Reserve application paths and use the same collision-safe write process.
Recommended approach
We’ll choose random Base62 generation with conditional writes and retries. It keeps generation independent across application instances while the database enforces uniqueness.
Random codes reduce predictability, but public short links are still not access-control mechanisms.
Problem 2: Every Redirect Reads from the Database
At about 1,160 average redirects/s and 5,800 at the normal peak, many requests may ask for the same popular mapping.
This does not prove the database is too slow. It does create an opportunity to reduce repeated work.
The baseline already uses DynamoDB for short_code lookups. Redis keeps frequently requested mappings in memory so these repeated reads do not all reach DynamoDB.
Add Redis Using Cache-Aside
- Look up the code in Redis.
- On a hit, check
expires_at. Return410 Goneif the link has expired; otherwise, redirect. - On a miss, read
linksby its partition key withConsistentRead=truein the same region. - Return
404 Not Foundif the code does not exist, or410 Goneif it has expired. - Cache a valid mapping and return the redirect.
A key such as link:aB3x9K stores original_url and expires_at. Cache only after the DynamoDB write is confirmed. For a cache fill, choose the smaller of the normal cache lifetime and the time remaining before link expiry; non-expiring links still get a bounded cache lifetime. Recheck the saved deadline on every hit.
Mappings are immutable in this version, so regular redirects do not need cache invalidation. Do not cache missing codes, and never treat Redis expiry as permission to reuse a code. If editing or disabling links is added later, it needs a separate invalidation policy.
How the Cache Behaves During Failures
| Scenario | System behavior |
|---|---|
| Redis has the mapping | Validate expires_at, then redirect without reading DynamoDB. |
| Redis misses | Read DynamoDB, cache a valid mapping, then redirect. |
| Cache population fails after creation | The link is safely stored in DynamoDB. A following read falls back to the database. |
| A link was just created and Redis is empty | The strongly consistent same-region table read finds the acknowledged mapping. |
| Redis is unavailable | Bypass it and read DynamoDB, while using timeouts and rate limits to protect the database from the extra load. |
When many requests miss the same hot code, combine the refill so one database read can serve them. Redis can answer from a cached mapping, but a cache miss must be checked against DynamoDB before returning 404.
Problem 3: One Application Instance Becomes a Bottleneck
One application instance may not handle all the traffic, and its failure would interrupt the service. The application tier therefore needs to scale without introducing a new single point of failure.
Scale and failure handling for application instances
| Risk | Design response |
|---|---|
| Traffic exceeds one instance’s capacity | Run multiple stateless instances and add more as demand grows. |
| An application instance fails | Let the load balancer stop routing traffic to the unhealthy instance. |
| An Availability Zone fails | Distribute instances across zones. |
| The load balancer fails | Use a managed, redundant load balancer or a properly redundant deployment. |
| Shared dependencies are overwhelmed | Load-test the complete path, not just the application tier. |
Every instance follows the same redirect rules, including checking expires_at. Adding more application servers improves capacity and resilience only when Redis, DynamoDB, and the load balancer can support the resulting traffic.
Problem 4: The Database Is Still a Failure Point
DynamoDB replicates data across multiple Availability Zones, but replication does not eliminate throttling, request failures, accidental data loss, or a regional outage.
Database failure and recovery options
| Failure | Response |
|---|---|
| Temporary request failure | Retry with exponential backoff and jitter. |
| Throttling or capacity pressure | Monitor throttling, latency, and errors; adjust capacity or traffic controls. |
| Accidental deletion or corruption | Enable backups and point-in-time recovery, then test restoration. |
| Regional outage | Follow a documented regional recovery plan when the availability target requires one. |
| DynamoDB is unavailable but Redis has the link | Continue redirecting cached, unexpired links. |
| DynamoDB is unavailable on a cache miss or creation | Return 503 Service Unavailable; do not report the link as missing. |
Failure rule: An infrastructure error is not a
404. Return404 Not Foundonly when the system successfully checks the source of truth and confirms that the code does not exist.
Where We Have Arrived
We started with a working create-and-redirect path, then added a cache and more application instances without changing who owns the mappings.
- Create links. Validate the URL, generate a random Base62 code, and conditionally insert one immutable mapping into DynamoDB.
- Honor custom aliases. Use the same namespace and conditional write; return a conflict for a taken or reserved alias.
- Redirect and expire. Check Redis first, then DynamoDB on a miss. Validate the deadline before returning a
302; keep expired codes reserved. - Scale and recover. Run stateless instances across zones, bound database fallback during cache failures, and configure DynamoDB recovery and backups.
How We Address the Non-Functional Requirements
| Requirement | How the final design addresses it |
|---|---|
| Low latency | Redis serves popular mapping reads; direct partition-key reads handle misses. The p95 target below 100 ms still needs measurement. |
| High availability | A redundant load balancer, instances across zones, and bounded database fallback support the 99.9% redirect target. Cached valid links can still redirect during some database failures. |
| Scalability | Independent code generation and stateless instances spread application work; hot-link caching reduces repeated database reads. Load-test the roughly 5,800 redirects/s normal peak and more concentrated viral traffic. |
| Durability | Acknowledge creation only after DynamoDB stores the mapping. Use its regional replication, configured backups, and tested restoration; Redis is not the durable copy. |
| Correctness and consistency | Atomic conditional writes prevent replacement. Same-region strongly consistent table reads find acknowledged creations; every redirect checks expiry and no issued code is reused. |
These choices support the targets; they do not prove them. Validate latency, outages, cache fallback, and backup restoration before claiming those guarantees.
The application creates and validates links. Redis speeds up popular reads. DynamoDB keeps each code’s destination and reservation durable.
Interview tip: Explain creation and redirection first. Then show how conditional inserts protect uniqueness and why a cache can speed up reads without becoming the source of truth.
Join the discussion
Spot a mistake or have another perspective? Share your feedback, insights, or suggestions.