bit.ly/my-link| Metric | Estimate |
| ----------------------- | ------------------------------------------------ |
| Write volume | 1 million new URLs/day = ~12 URLs/second |
| Read volume | 100 million redirects/day = ~1160/second |
| URL ratio | 100:1 read-to-write |
| Storage (5 years) | 1M × 365 × 5 = 1.8B URLs × 500 bytes ≈ **900GB** |
| New URLs/sec in 5 years | Maybe 100-500/sec (still manageable) |
create url:
post , api/v1/shorten
request :
long url
expired at
custom alias
response:
short url
created at
expires at
i want that url"
get , short url
redirect cache the browser
use 301 rather than 302 to avoid server load and make it faster
some decisions to consider:
during coding if i use hashmap there might be some collisions and due to the lack of uniqueness so i will use a base62 and also due to the incremental nature of this i might need to start at a random number
code: in js
import express from "express"
const app= express(json);
const char = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// to base62
function toBase62(num){
// base case
if(num=== 0 ) return "";
let result = "";
while( num > 0){
result= char[num%62] + result
num = Math.floor(num/62)
}
return result;
}
let nextId = 1;
const urlDatabase = {};
app.post('api/shorten/v1', async(req,res,next){
const longUrl= req.body._longUrl
const id= nextId++;
const shortCode = toBase62(id);
// Save
urlDatabase[shortCode] = longUrl;
res.json({
short_url: `bit.ly/${shortCode}`,
created_at: new Date().toISOString()
});
Database Design:
short code
long url
created at
expires at
click count
user_Id
// schema model prisma postgress and typescript
model URL_shortener {
id BigInt @id @default(autoincrement()),
shortCode String @unique @map("short_code") @db.VarChar(10)
longUrl String @map("long_url") @db.Text
createdAt DateTime @default(now()) @map("created_at)
expiresAt DateTime? @map("expires_at")
clickCount BigInt @default(0) @map("click_count")
userId Int? @map("user_id")
}
id and short_code? (Internal tracking vs user-facing)INDEX do? (Makes lookups fast)User: "Shorten https://example.com"
↓
Load Balancer → App Server
↓
1. Get unique ID from database/ID service
↓
2. Convert ID → base62 ("15FTG")
↓
3. Save to database: (15FTG → https://example.com)
↓
4. Return to user: "bit.ly/15FTG"
User: clicks "bit.ly/15FTG"
↓
Load Balancer → App Server
↓
1. Check Redis: "Do I know 15FTG?"
↓
┌─────────────────────────────────────┐
│ CACHE HIT (99% of time) │
│ Redis: "Yes! → https://example.com"│
│ Return: 301 redirect (~1ms) │
└─────────────────────────────────────┘
↓
CACHE MISS (1% of time)
Check database → Save to Redis → Return redirect (~10ms)
DB scaling
Deep dive into 2-3 key components. Explain how they work, how they scale, discuss tradeoffs, capacity, and any relevant algorithms or data structures.