URL Shortener (TinyURL) - System Design
Thiết kế hệ thống URL Shortener tương tự TinyURL, cho phép chuyển đổi long URL thành short URL dễ chia sẻ.
1. 📋 Đề Bài (Problem Statement)
- Thiết kế hệ thống URL Shortener tương tự TinyURL, cho phép chuyển đổi long URL thành short URL dễ chia sẻ.
- Hệ thống phải xử lý lưu lượng đọc rất lớn (redirect), độ trễ thấp, và đảm bảo link ổn định trong thời gian dài.
- Scope chính: tạo short URL, redirect, custom alias, expiration, và analytics cơ bản.
- Scope ngoài bài (out of scope): deep malware scanning, QR generator, full marketing campaign suite.
- Mục tiêu business: tăng tốc độ chia sẻ link, tracking click, và cung cấp nền tảng cho API integrations.
2. 🔍 Requirement Gathering & Analysis
2.1 Functional Requirements
| Priority | Requirement | Mô tả |
|---|---|---|
| MUST-HAVE | Create short URL | User nhập long URL và nhận về short URL duy nhất |
| MUST-HAVE | Redirect | Khi truy cập short URL, hệ thống trả về HTTP redirect đến long URL |
| MUST-HAVE | High availability redirect | Redirect vẫn hoạt động khi một phần service lỗi |
| MUST-HAVE | URL validation | Validate format URL, block schema không hợp lệ |
| NICE-TO-HAVE | Custom alias | User chọn alias riêng (ví dụ tiny.ly/sale2026) |
| NICE-TO-HAVE | Expiration time | Link tự hết hạn theo thời gian |
| NICE-TO-HAVE | Basic analytics | Theo dõi số lượt click theo ngày, quốc gia, user-agent |
2.2 Non-Functional Requirements
- Performance: Redirect p95 < 50ms (cache hit), create URL p95 < 200ms.
- Scalability: Hỗ trợ peak ~70K redirect QPS và ~2K create QPS.
- Availability: SLA 99.99% cho redirect path, 99.9% cho create/manage API.
- Consistency: Read-after-write gần real-time cho link mới tạo (<1s), analytics chấp nhận eventual consistency.
- Security: JWT/OAuth2 cho API quản trị, TLS end-to-end, chống abuse/spam link.
- Cost: Ước lượng ~$3,000-5,000/tháng cho MVP (EKS cluster ~$800, RDS Multi-AZ r6g.large ~$600, ElastiCache r6g.large ~$400, MSK ~$500, ALB+CloudFront ~$300, S3+logging ~$200, monitoring ~$200). Scale lên peak traffic có thể đạt $8,000-12,000/tháng.
- Observability: Metrics, logs, traces đầy đủ theo Golden Signals (latency, error, traffic, saturation).
2.3 Capacity Estimation (Back-of-the-envelope)
Bước 0: Quy ước đơn vị (để tránh nhầm)
1 day = 86,400 seconds1M = 1,000,000,1B = 1,000,000,000(B ở đây là Billion, không phải Byte)1 byte = 8 bits- Trong phần này dùng đơn vị thập phân cho dễ tính:
1KB = 1,000B,1GB = 1,000,000,000B
Bước 1: Inputs giả định
| Input | Giá trị | Tại sao chọn |
|---|---|---|
| DAU | 100M users/day | Bài toán consumer scale lớn |
| New short URLs/day | 30M links/day | Giả sử khoảng 30% DAU tạo 1 link/ngày |
| Read:Write ratio | 40:1 | Hệ thống read-heavy; cứ 1 URL tạo ra thì trung bình sinh 40 lượt redirect (tính trên toàn bộ link active, bao gồm cả link cũ lẫn mới) |
| Avg long URL size | 300B | Kịch bản conservative (URL có query params/UTM) |
| Metadata per URL | 200B | id, short_code, status, user_id, timestamps + overhead row/index |
| Avg redirect payload | 1.5KB/click | Request + response headers và overhead mạng cơ bản |
📌
300Bcholong_urllà giả định capacity để tránh under-estimate, không phải hằng số cứng.
Bước 2: Tính write traffic (create short URL)
- Công thức:
write_qps_avg = new_urls_per_day / 86,400 - Thay số:
30,000,000 / 86,400 = 347.2 - Kết quả: write QPS trung bình ~347
- Peak factor giờ cao điểm chọn
x5:347 * 5 = 1,735 - Kết quả: peak write QPS ~1,735
Bước 3: Tính read traffic (redirect)
- Công thức:
daily_redirects = new_urls_per_day * read_write_ratio - Thay số:
30,000,000 * 40 = 1,200,000,000 = 1.2B redirects/day
📌 Đây là ước lượng tổng redirect toàn hệ thống (bao gồm click trên link cũ lẫn link mới), không phải 40 click/link mới. Read:Write ratio 40:1 là mức phổ biến cho URL shortener (Bitly công bố ~100:1). Chọn 40:1 là kịch bản moderate.
- Công thức read QPS:
read_qps_avg = daily_redirects / 86,400 - Thay số:
1,200,000,000 / 86,400 = 13,888.9 - Kết quả: read QPS trung bình ~13,889
- Peak factor
x5:13,889 * 5 = 69,445 - Kết quả: peak read QPS ~69,445
Bước 4: Tính storage cho bảng URL
- Kích thước 1 record:
record_size = avg_long_url + metadata - Thay số (kịch bản conservative):
300B + 200B = 500B/record - Daily raw storage:
30,000,000 * 500B = 15,000,000,000B = 15GB/day - Yearly raw storage:
15GB * 365 = 5,475GB ~ 5.48TB/year - 5-year raw storage:
5.48TB * 5 = 27.4TB - Cộng index + replication + free space (xấp xỉ
3x):~82TB(thực tế vận hành lấy 80-90TB)
Bước 5: Tính bandwidth redirect mỗi ngày
- Công thức:
redirect_bandwidth/day = daily_clicks * payload_per_click - Thay số:
1.2B * 1.5KB = 1.8B KB = 1.8TB/day - Đổi sang bit:
1.8TB * 8 = 14.4Tb/day
Bước 6: Redis cache memory estimate
- Giả sử quy luật 80/20: khoảng 5% links nóng tạo phần lớn traffic.
- Nếu active links cần phục vụ nhanh khoảng
1B, thì hot set ~50M links. - Giả sử 1 cache entry trung bình
~400B(key + value + metadata + Redis overhead):50M * 400B = 20GBraw
- Cộng replication + fragmentation + headroom: nhân khoảng
2x- Kết quả cluster Redis nên chuẩn bị ~40GB.
Bước 7: So sánh nhanh 2 kịch bản để dễ kiểm chứng
| Kịch bản | Avg long URL | Record size | Daily storage (30M links/day) |
|---|---|---|---|
| Base | 120B | 320B | 9.6GB/day |
| Conservative (đang dùng) | 300B | 500B | 15GB/day |
📊 Bảng tổng hợp Capacity Estimation
| ID | Metric | Avg | Peak |
|---|---|---|---|
| C1 | Write QPS | ~347 | ~1,735 |
| C2 | Read QPS (redirect) | ~13,889 | ~69,445 |
| C3 | Daily storage | 15GB/day | — |
| C4 | Yearly / 5-year storage | 5.48TB/yr | ~82TB/5yr |
| C5 | Bandwidth (redirect) | 1.8TB/day | — |
| C6 | Redis cache memory | ~40GB | — |
| C7 | Daily click events | 1.2B/day | — |
3. ⚖️ Trade-offs
3.1 Bảng tổng quan quyết định
| Decision | Option A | Option B | Chọn | Lý do chính |
|---|---|---|---|---|
| ID generation | Random hash + collision check | Snowflake ID + Base62 | B | Không cần collision check runtime, latency ổn định khi write tăng |
| Redirect type | 302 (temporary) | 301 (permanent) | B | Cache tốt ở browser/CDN, giảm request quay về origin |
| Data store chính | PostgreSQL | Cassandra | A | Cần unique constraints + query quản trị linh hoạt |
| Cache strategy | Cache-aside Redis | Write-through | A | Phù hợp workload read-heavy, giảm write amplification |
| Analytics pipeline | PostgreSQL sync write | Kafka async events | B | Tách redirect critical path, giữ redirect latency thấp |
3.2 Decision #1: ID Generation (Random Hash vs Snowflake + Base62)
| Tiêu chí | Random hash + collision check | Snowflake + Base62 |
|---|---|---|
| Uniqueness | Probabilistic, cần check DB | Deterministic unique theo node+timestamp+sequence |
| Write latency | Có thể tăng khi phải retry collision | Ổn định hơn, không cần retry collision |
| Độ dài short code | Dễ ép cố định 7-8 chars | Encode full ID thường 10-11 chars |
| Độ phức tạp vận hành | Đơn giản lúc đầu | Cần đồng bộ clock và worker ID |
Cách 1: Random Hash + Collision Check hoạt động thế nào?
- Nhận
long_url. - Tạo seed:
long_url + "|" + nonce + "|" + timestamp. - Băm SHA-256(seed).
- Convert hash sang Base62, lấy 7 ký tự đầu làm
short_code. - Check DB: nếu trùng thì tăng
noncevà lặp lại.
Ví dụ từng bước:
long_url = https://shop.example.com/deal?utm_campaign=sale&utm_source=facebooktimestamp = 2026-02-28T10:00:00Z- Lần 1 với
nonce = 0:- seed =
https://shop.example.com/deal?utm_campaign=sale&utm_source=facebook|0|2026-02-28T10:00:00Z - SHA-256 =
3ca09f253d8275c124936e3e10b15adbcd9814fa052f634ac137acb197e78695 - Base62 prefix =
ENLlbnZS63VeqvoOVZOs... - Lấy 7 ký tự =>
ENLlbnZ - DB báo đã tồn tại -> collision
- seed =
- Lần 2 với
nonce = 1:- SHA-256 =
649ec9a6d40b40074cfc18510f1283b1c8786c08cb9dac134059f70e9e0901c9 - Base62 prefix =
NrKT6qWPGVl61KeWEjYq... - Lấy 7 ký tự =>
NrKT6qW - DB chưa có -> insert thành công
- SHA-256 =
- Điểm mạnh: đơn giản, không cần service ID riêng.
- Điểm yếu: ở peak traffic có thể gặp retry, làm latency dao động; luôn cần check DB uniqueness.
Cách 2: Snowflake ID + Base62 hoạt động thế nào?
Cấu trúc Snowflake điển hình (64-bit):
41 bits timestamp(ms từ custom epoch)10 bits workerId(mã node sinh ID)12 bits sequence(counter trong cùng 1 ms)
workerId và sequence là gì?
workerId = 17: node/pod số 17 trong cụm ID generator.sequence = 23: ID thứ 23 được node đó phát ra trong cùng millisecond hiện tại.
Luồng xử lý:
id_generator_servicetự quản lýsequencevà sinhsnowflake_id.- URL service encode
snowflake_idsang Base62. - Insert DB một lần (UNIQUE index chỉ là safety net).
Flow end-to-end cụ thể (với số thật):
- Cấu hình:
epoch = 2024-01-01T00:00:00ZworkerId = 17- Generator state ban đầu:
lastTimestamp = null,sequence = 0
- Request A đến lúc
2026-02-28T10:00:00.123Z:delta_ms = 68,205,600,123- Vì là ms mới ->
sequence = 0 snowflake_id = (delta_ms << 22) | (17 << 12) | 0snowflake_id = 286075021418369024- Base62 ->
L8E3B1JoxM - Insert DB:
id = 286075021418369024short_code = L8E3B1JoxMlong_url = ...
- Request B vẫn trong cùng ms
.123:timestampkhông đổi -> tăngsequence = 1snowflake_id = 286075021418369025- Base62 ->
L8E3B1JoxN - Insert DB 1 lần thành công
- Request C vẫn trong cùng ms
.123:sequence = 2snowflake_id = 286075021418369026- Base62 ->
L8E3B1JoxO
- Nếu cùng ms mà sequence chạm trần:
- Với 12 bits, max sequence =
4095 - ID cuối trong ms
.123:286075021418373119->L8E3B1Jq1P - Request tiếp theo phải đợi sang ms
.124, resetsequence = 0 - ID mới:
286075021422563328->L8E3B1bQ5Q
- Với 12 bits, max sequence =
- Tại sao chỉ insert DB 1 lần:
- ID đã unique theo
timestamp + workerId + sequence, nên không cần vòng lặp retry như random-hash. UNIQUE(short_code)vẫn giữ để làm safety net nếu có misconfiguration hiếm (trùng workerId, clock lỗi).
- ID đã unique theo
Chi tiết bước 2: URL service encode Snowflake ID sang Base62
- Bảng ký tự Base62:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz - Nguyên tắc:
- Lấy
idchia cho62. - Lấy
remainder(0..61) map sang 1 ký tự. - Lấy
quotientchia tiếp cho62đến khi bằng0. - Ghép các ký tự theo thứ tự ngược lại.
- Lấy
Ví dụ với id = 286075021418369024:
| Vòng | n hiện tại | q = n / 62 | r = n % 62 | Ký tự |
|---|---|---|---|---|
| 1 | 286075021418369024 | 4614113248683371 | 22 | M |
| 2 | 4614113248683371 | 74421181430376 | 59 | x |
| 3 | 74421181430376 | 1200341635973 | 50 | o |
| 4 | 1200341635973 | 19360348967 | 19 | J |
| 5 | 19360348967 | 312263693 | 1 | 1 |
| 6 | 312263693 | 5036511 | 11 | B |
| 7 | 5036511 | 81234 | 3 | 3 |
| 8 | 81234 | 1310 | 14 | E |
| 9 | 1310 | 21 | 8 | 8 |
| 10 | 21 | 0 | 21 | L |
- Ký tự thu được theo thứ tự vòng lặp:
M x o J 1 B 3 E 8 L - Đảo ngược lại:
L8E3B1JoxM
Vì sao Snowflake gần như không trùng?
-
workerIdphải unique giữa các node. -
Trên mỗi node,
sequencetăng dần trong cùng ms; sang ms mới thì reset. -
Nếu
sequencetràn (hơn 4096 ID/ms), generator chờ sang ms tiếp theo. -
Clock phải được đồng bộ (NTP); nếu clock lùi thì generator tạm dừng hoặc failover.
-
Điểm mạnh: không collision runtime (nếu clock/worker đúng), latency ổn định hơn.
-
Điểm yếu: cần quản lý clock drift, worker ID, và sequence overflow.
Pseudo-code so sánh nhanh
Random Hash:
do:
code = base62(sha256(longUrl + nonce + now))[0..6]
while exists(code)
insert(code, longUrl)
Snowflake + Base62:
id = snowflake.nextId()
code = base62(id)
insert(code, longUrl) // unique index as safety netKết luận cho bài toán này
- Context: write peak ~1.7K QPS
[C1], cần latency create ổn định. - Chọn Snowflake + Base62 vì giảm retry loop và giảm query-check collision trên critical path.
- Lưu ý độ dài: nếu encode full Snowflake thì code thường 10-11 ký tự; nếu bắt buộc 7-8 ký tự thì cần chiến lược khác (ví dụ random/truncate + collision check).
- Mitigation vận hành:
- NTP đồng bộ clock cho các node ID generator.
- Fallback nếu clock lùi: tạm dừng phát ID vài ms hoặc switch node khác.
- Có thể thêm obfuscation (salt/permutation) trước khi trả code ra ngoài để giảm khả năng đoán chuỗi.
3.3 Decision #2: Redirect Semantics (301 vs 302)
| Tiêu chí | 302 Temporary | 301 Permanent |
|---|---|---|
| Cache browser/CDN | Thấp hơn | Cao hơn |
| Latency trung bình | Cao hơn do quay lại origin nhiều hơn | Thấp hơn cho traffic lặp |
| Khả năng đổi target URL | Linh hoạt hơn | Kém linh hoạt hơn (client cache lâu) |
| SEO | Trung tính | Tốt hơn cho canonical redirect |
Context kỹ thuật
- Redirect là hot path (~70K QPS peak)
[C2], mục tiêu chính là giảm round-trip về origin. - Mỗi request redirect đi qua nhiều tầng (CloudFront -> Gateway -> Redirect Service -> Redis/DB), nên tối ưu cache ở edge mang lại lợi ích lớn nhất.
- Link short trong sản phẩm mặc định xem như immutable sau khi publish.
Cách 301 và 302 khác nhau trong thực tế
| Tình huống | Nếu dùng 302 | Nếu dùng 301 |
|---|---|---|
| User click lần 1 | Trình duyệt vẫn phải hỏi origin | Trình duyệt nhận redirect và có thể cache |
| User click lần 2 cùng link | Thường vẫn gọi lại origin | Nhiều trường hợp dùng cache local/edge, giảm call origin |
| Link viral (hàng triệu click lặp) | Origin chịu tải cao hơn | Giảm đáng kể origin QPS |
| Owner đổi target URL | Dễ cập nhật ngay | Khó hơn do client/CDN có thể cache lâu |
Ví dụ end-to-end cụ thể
- Giả sử một short link được click
10Mlần/ngày, trong đó60%là revisit từ user/client đã từng click. - Nếu dùng
302, phần lớn10Mrequest vẫn quay về origin để lấy redirect. - Nếu dùng
301+Cache-Control: public, max-age=86400, phần revisit có thể được phục vụ từ browser/CDN. - Giả sử cache absorb được 40% traffic revisit, origin giảm khoảng:
10M * 60% * 40% = 2.4M requests/day
- Kết quả: giảm chi phí hạ tầng và hạ p95 latency trên đường redirect.
Rủi ro khi dùng 301 và cách giảm rủi ro
- Rủi ro 1: đổi target URL khó propagate.
- Mitigation: policy “immutable by default”; nếu cần đổi, tạo short code mới.
- Rủi ro 2: link bị abuse nhưng đã cache.
- Mitigation: trả
410 Gone, setCache-Control: no-storecho response lỗi, trigger CDN invalidation cho key nóng.
- Mitigation: trả
- Rủi ro 3: cache quá lâu gây stale behavior.
- Mitigation: chỉ dùng TTL lớn cho active link ổn định; link editable dùng 302 và TTL ngắn.
Rule vận hành đề xuất
- Mặc định: public short link dùng
301. - Link cần chỉnh sửa thường xuyên (A/B campaign, thử nghiệm): dùng
302. - Khi có security incident: ưu tiên disable link và trả
410ngay.
3.4 Decision #3: Primary Data Store (PostgreSQL vs Cassandra)
| Tiêu chí | PostgreSQL | Cassandra |
|---|---|---|
| Unique alias constraints | Mạnh (UNIQUE index) | Phức tạp hơn (cần design riêng) |
| Transaction support | ACID tốt | Eventual consistency mặc định |
| Query quản trị | Mạnh (filter/sort/report) | Tối ưu theo access pattern cố định |
| Scale write cực lớn | Scale vertical + partition/read replica | Scale ngang rất tốt |
Access patterns cần support
GET /{shortCode}: lookup theoshort_code(cực nhiều).POST /api/v1/urls: insert mới + kiểm tra unique alias.GET /api/v1/urls?cursor=...: list URL theouser_id, sort theocreated_at.DELETE /api/v1/urls/{shortCode}: update status/soft-delete.GET stats: đọc aggregate theo(short_code, date).
Vì sao chọn PostgreSQL cho v1
- Cần
UNIQUE(short_code)vàUNIQUE(custom_alias)đảm bảo chính xác ngay khi ghi. - Cần transaction rõ ràng cho luồng create + ownership + audit.
- Cần query quản trị linh hoạt (lọc theo user, trạng thái, khoảng thời gian).
- Ở quy mô trong capacity hiện tại (write ~347 avg, ~1.7K peak), PostgreSQL + partition + replica vẫn rất phù hợp.
Flow ghi/đọc điển hình với PostgreSQL
- Create link:
- Validate URL.
- Sinh
short_code. INSERTvàoshort_urls.- Nếu trùng unique ->
409 Conflict.
- Redirect:
- Đọc Redis trước.
- Miss thì
SELECT long_url, status, expires_at FROM short_urls WHERE short_code=?.
- Disable link:
UPDATE short_urls SET status='DISABLED', updated_at=NOW() WHERE short_code=? AND user_id=?.
Ví dụ SQL cho tính nhất quán alias
INSERT INTO short_urls (id, short_code, long_url, user_id, status)
VALUES (:id, :short_code, :long_url, :user_id, 'ACTIVE');
-- Nếu short_code đã tồn tại, PostgreSQL ném unique violation ngay.Điểm yếu của PostgreSQL và kế hoạch giảm rủi ro
- Điểm yếu: scale write ngang kém hơn Cassandra ở workload cực lớn.
- Mitigation 1: hash partition bảng
short_urlstheoshort_code. - Mitigation 2: read replicas cho query dashboard/stats.
- Mitigation 3: giữ redirect chủ yếu ở Redis để giảm DB load.
- Mitigation 4: tách analytics raw ra Kafka + S3 thay vì dồn vào PostgreSQL.
Khi nào nên cân nhắc Cassandra
| Dấu hiệu | Ý nghĩa |
|---|---|
| Write QPS tăng lên mức rất cao và kéo dài | RDS bắt đầu là bottleneck ghi |
| Dữ liệu phân tán đa region active-active mạnh | Cassandra replication model có lợi hơn |
| Access pattern đơn giản dạng key-value khối lượng cực lớn | Cassandra phù hợp hơn relational query |
💡 Tại sao chưa dùng Cassandra ngay từ đầu? Với bài toán TinyURL v1, nhu cầu uniqueness + quản trị + transaction quan trọng hơn lợi ích scale write cực lớn. Chọn PostgreSQL giúp giảm độ phức tạp triển khai ban đầu.
3.5 Decision #4: Cache Strategy (Cache-aside vs Write-through)
| Tiêu chí | Cache-aside | Write-through |
|---|---|---|
| Độ phức tạp | Đơn giản, app kiểm soát cache | Logic ghi đồng thời DB + cache |
| Cache miss đầu tiên | Có penalty | Ít hơn |
| Write cost | Thấp hơn | Cao hơn (mọi write đi qua cache) |
| Phù hợp read-heavy | Tốt | Trung bình |
Context kỹ thuật
- Redirect là read-heavy cực cao; create/update comparatively thấp.
- Mục tiêu: p95 redirect thấp, kể cả khi DB đang có spike.
Flow cache-aside chi tiết
GET /{shortCode}vào redirect-service.- Service gọi Redis:
- Hit: trả redirect ngay (không chạm DB).
- Miss: đọc PostgreSQL -> validate status/expiry -> set Redis -> trả redirect.
- Link bị disable/expire:
- Update DB trước (source of truth).
- Xóa/invalidate cache key tương ứng.
Ví dụ định lượng lợi ích
Giả sử:
- Redis hit latency:
~2ms - PostgreSQL lookup latency:
~25ms - Cache hit ratio:
90%
Latency trung bình xấp xỉ:
0.9 * 2 + 0.1 * 25 = 4.3ms(chưa tính network)
Nếu không cache:
- Gần như toàn bộ request phải đi DB -> khoảng
~25msbaseline hoặc hơn khi load tăng.
Vì sao không chọn write-through làm mặc định
- Write-through bắt mọi lần ghi phải update cache ngay, tăng độ phức tạp và write amplification.
- Với URL shortener, write ít hơn read rất nhiều; lợi ích write-through không bù được chi phí vận hành.
- Cache-aside cho phép chỉ cache những key thật sự được đọc (hot keys).
TTL Strategy
- Link không có expiration: TTL mặc định 24h + jitter ngẫu nhiên ±10-20% (ví dụ:
24h ± ~2.5h). Vìlong_urlgần như không đổi sau khi tạo, TTL dài giúp tối đa cache hit ratio và giảm DB load. Khi link bị disable/delete thì invalidate cache key ngay lập tức. - Link có
expires_at: TTL =min(default_ttl, expires_at - now)để cache tự hết hạn đúng lúc link expire, tránh serve redirect cho link đã hết hạn. - Hot keys (viral links): kết hợp local L1 cache (TTL ~30s) + Redis để tránh single Redis key bị quá tải. Redis TTL vẫn giữ 24h.
📌 Jitter ngẫu nhiên rất quan trọng: nếu nhiều hot keys cùng hết TTL đồng thời sẽ gây cache stampede — hàng loạt request đồng thời đổ xuống DB.
Failure scenarios và mitigation
- Cache stampede khi hot key vừa hết TTL:
- Dùng request coalescing/single-flight.
- Thêm TTL jitter ngẫu nhiên.
- Stale cache sau khi disable link:
- Event invalidation tức thì + TTL ngắn cho key nhạy cảm.
- Redis outage:
- Fallback DB, bật circuit breaker và rate-limit để bảo vệ DB.
- Hot key skew:
- Local L1 cache ngắn hạn + Redis cluster sharding.
3.6 Decision #5: Analytics Ingestion (Sync write DB vs Kafka async)
| Tiêu chí | Ghi sync vào PostgreSQL | Kafka async events |
|---|---|---|
| Redirect latency | Tăng theo DB write | Thấp hơn, tách khỏi critical path |
| Độ bền dữ liệu click | Cao nhưng đắt | Cao nếu cấu hình durability đúng |
| Khả năng scale analytics | Hạn chế | Rất tốt, consumer scale ngang |
| Độ phức tạp | Đơn giản ban đầu | Cao hơn (queue + consumers + retry) |
Context kỹ thuật
- Click volume ước tính
1.2B events/day(~13.9K EPS trung bình, peak cao hơn nhiều). - Nếu mỗi click ghi sync vào DB trên redirect path, latency và DB cost tăng mạnh.
So sánh trực tiếp 2 cách
| Tiêu chí vận hành | Sync DB write | Kafka async |
|---|---|---|
| Redirect p95 | Dễ tăng theo DB contention | Ổn định hơn vì tách luồng |
| Khả năng buffer burst traffic | Thấp | Cao (Kafka làm buffer) |
| Khả năng replay dữ liệu | Khó | Dễ (re-consume theo offset) |
| Phức tạp hệ thống | Thấp | Trung bình-cao |
Flow Kafka async chi tiết
- Redirect service resolve short code và trả
301cho client trước. - Cùng lúc publish
ClickEventvào Kafka topicurl-click-events. - Analytics consumer đọc event theo partition.
- Consumer aggregate theo
(short_code, stat_date)và upsert vàourl_stats_daily. - Raw events đồng thời đẩy sang S3 để phân tích sâu/offline.
- Dashboard đọc từ bảng aggregate, không đọc trực tiếp raw stream.
Ví dụ event schema
{
"eventId": "9f3e2f59-2b8b-4f0a-9d0b-78f1f2f76e11",
"shortCode": "L8E3B1JoxM",
"clickedAt": "2026-02-28T10:00:00.123Z",
"ipHash": "e4bc1a...",
"userAgent": "Mozilla/5.0",
"country": "US",
"referrer": "https://example.com"
}Duplicate và consistency xử lý thế nào
- Thực tế thường dùng at-least-once delivery, nên duplicate có thể xảy ra.
- Cách xử lý:
- Producer bật idempotence.
- Consumer upsert theo key
(short_code, stat_date). - Optional dedupe theo
eventIdtrong cửa sổ thời gian ngắn.
- Kết quả: analytics mang tính eventual consistency (trễ vài giây/phút) nhưng redirect path vẫn nhanh.
Failure scenarios và mitigation
- Kafka lag tăng cao:
- Auto-scale consumers theo lag.
- Alert khi lag vượt ngưỡng.
- Consumer crash giữa chừng:
- Commit offset sau khi ghi DB thành công.
- DB aggregate bị nghẽn:
- Batch upsert, tune indexes, partition theo ngày.
- Poison message:
- Dead-letter topic + replay tool.
SLA tách biệt
- Redirect SLA: realtime, ưu tiên latency thấp và availability cao.
- Analytics SLA: cho phép trễ
1-5 phútđể đổi lấy khả năng scale và ổn định.
4. 🧩 Defining Entities / Components
| Component | Vai trò |
|---|---|
| CloudFront + WAF | Edge caching, DDoS/basic bot protection, giảm latency toàn cầu |
| Spring Cloud Gateway | API routing, auth filter, rate limiting |
| URL Management Service | Create/update/delete URL, custom alias validation, sinh Snowflake ID (embedded library) |
| Redirect Service | Resolve short code và trả redirect response cực nhanh |
| Redis | Cache mapping short_code -> long_url cho hot traffic |
| PostgreSQL | Source of truth cho URL metadata, ownership, expiration |
| Kafka + Analytics Service | Thu click events async, aggregate số liệu |
💡 Tại sao nhúng ID Generator vào URL Management Service thay vì tách riêng? Ở giai đoạn MVP, chỉ có URL Service cần sinh Snowflake ID. Nhúng dưới dạng embedded library (mỗi pod tự quản lý
workerIdqua lease từ DB hoặc K8s ordinal index) giúp: (1) giảm 1 network hop trên write path, (2) giảm độ phức tạp vận hành. Khi hệ thống scale lên và có nhiều service cần sinh ID, có thể tách ra thành standalone ID Generator Service để tái sử dụng và quản lýworkerIdtập trung.
5. 🔗 Client-Server Connection
- Protocol:
- Management APIs: HTTPS REST/JSON (
/api/v1/...). - Redirect: HTTP GET
/{shortCode}trả về301 Location.
- Management APIs: HTTPS REST/JSON (
- Authentication:
- Anonymous được phép redirect.
- JWT Bearer token bắt buộc cho create/delete/stats owner-level.
- Connection patterns:
- Request-Response cho create/manage.
- Async Pub-Sub qua Kafka cho click analytics.
- Rate limiting & throttling:
- Anonymous create API: 30 req/min/IP.
- Authenticated users: theo plan (Free/Pro/Enterprise).
- Dùng Redis token bucket ở Gateway.
💡 Gateway Redis vs Redirect Redis — tách riêng hay dùng chung? Tách thành 2 ElastiCache cluster riêng biệt:
- Rate-limit Redis (nhỏ, ví dụ
r6g.large~13GB): chỉ phục vụ Gateway, workload write-heavy (INCR+EXPIRE), key TTL ngắn (~1 phút), cần vài GB RAM.- Redirect cache Redis (lớn, ví dụ
r6g.xlarge× nhiều shard, tổng ~40GB[C6]): phục vụ Redirect Service, workload read-heavy (GET/SET), TTL dài (~24h).Lý do tách: (1) failure isolation — Redis rate-limit lỗi không ảnh hưởng redirect cache và ngược lại; (2) workload khác biệt — chung cluster gây memory fragmentation và khó tune riêng; (3) sizing khác nhau — rate-limit chỉ cần vài GB, redirect cache cần ~40GB.
- Idempotency:
- Hỗ trợ
Idempotency-KeychoPOST /api/v1/urlsđể tránh tạo trùng khi retry.
- Hỗ trợ
6. 🔄 System / App Flow
Các sequence D2 dưới đây đọc từ trên xuống; nét đứt là response/event như nhãn mô tả. Trong group alt, chỉ một nhánh được chọn; loop là phần lặp lại. Group par biểu diễn các nhánh song song, không phải thứ tự thực thi từ trên xuống.
Flow 1: Tạo short URL
Flow 2: Redirect short URL
Error handling & Edge cases
- Short code không tồn tại: trả
404với landing page thân thiện (không expose internals). - Link hết hạn hoặc bị disable: trả
410 Gone. - Malformed URL khi tạo: trả
400 Bad Request. - Alias đã tồn tại: trả
409 Conflict. - Redis outage: fallback đọc PostgreSQL, degrade nhẹ nhưng vẫn redirect được.
7. 📡 API Modeling
Endpoint Definitions
| Method | Path | Auth | Mô tả |
|---|---|---|---|
| POST | /api/v1/urls | JWT optional (required để quản lý ownership) | Tạo short URL |
| GET | /{shortCode} | None | Redirect đến long URL |
| GET | /api/v1/urls/{shortCode} | JWT owner/admin | Lấy metadata URL |
| GET | /api/v1/urls/{shortCode}/stats?from=...&to=... | JWT owner/admin | Lấy analytics |
| DELETE | /api/v1/urls/{shortCode} | JWT owner/admin | Disable URL |
| GET | /api/v1/urls?cursor=...&limit=20 | JWT | Danh sách URL của user |
Request/Response Examples
📌 Các cặp dưới đây là transcript HTTP/1.1 minh họa, không gửi request thật. Body hiển thị ở dạng đã decode; chức năng copy không tạo wire format hay cURL. Token chỉ là dữ liệu ví dụ.
201 CreatedPOST → 201
301 Moved PermanentlyGET → 301
Error Response Format
{
"timestamp": "2026-02-28T10:01:22Z",
"status": 409,
"error": "Conflict",
"code": "ALIAS_ALREADY_EXISTS",
"message": "Custom alias is already taken",
"path": "/api/v1/urls"
}Pagination / Filtering / Sorting
- Dùng cursor-based pagination cho endpoint list URL để tránh offset scan nặng.
- Cho phép filter theo
status,createdFrom,createdTo. - Sort mặc định
created_at DESC.
API Versioning
- Version qua path
/api/v1. - Breaking changes phát hành
/api/v2, duy trì dual-run tối thiểu 6 tháng.
8. 🗄️ Data Modeling
Database Schema (PostgreSQL)
CREATE TABLE short_urls (
id BIGINT PRIMARY KEY,
short_code VARCHAR(16) NOT NULL UNIQUE,
long_url TEXT NOT NULL,
user_id BIGINT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
expires_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT chk_status CHECK (status IN ('ACTIVE', 'DISABLED', 'EXPIRED'))
);
CREATE TABLE url_stats_daily (
short_code VARCHAR(16) NOT NULL,
stat_date DATE NOT NULL,
click_count BIGINT NOT NULL DEFAULT 0,
unique_ip_count BIGINT NOT NULL DEFAULT 0,
top_country VARCHAR(2) NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (short_code, stat_date)
);ER Diagram
Sơ đồ dùng D2 sql_table: PK là primary key, FK là foreign key và UNQ tương đương UK (unique). Đầu nối crow’s foot và nhãn 1, 0..N, 0..1 giữ cardinality của mô hình; đường nối gắn vào cột liên quan. Các cột cùng mang PK thuộc một composite primary key. DDL phía trên là nguồn chuẩn cho constraint được database thực thi.
Indexing Strategy
UNIQUE INDEX idx_short_urls_short_codecho lookup redirect.INDEX idx_short_urls_user_createdtrên(user_id, created_at DESC)cho dashboard user.PARTIAL INDEX idx_short_urls_activetrênstatus='ACTIVE'để giảm scan.INDEX idx_url_stats_daily_datetrên(stat_date)cho báo cáo theo ngày.
Partitioning / Sharding Strategy
Hash Partition cho short_urls
- PostgreSQL hỗ trợ declarative partitioning: ta tự định nghĩa số partition khi tạo bảng, PostgreSQL tự động route row vào đúng partition dựa trên hash value.
-- Bảng cha: khai báo partition strategy
CREATE TABLE short_urls (
id BIGINT NOT NULL,
short_code VARCHAR(16) NOT NULL,
long_url TEXT NOT NULL,
user_id BIGINT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
expires_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
) PARTITION BY HASH (short_code);
-- Tạo 32 partition con
CREATE TABLE short_urls_p0 PARTITION OF short_urls FOR VALUES WITH (MODULUS 32, REMAINDER 0);
CREATE TABLE short_urls_p1 PARTITION OF short_urls FOR VALUES WITH (MODULUS 32, REMAINDER 1);
-- ... (tương tự cho p2 đến p30)
CREATE TABLE short_urls_p31 PARTITION OF short_urls FOR VALUES WITH (MODULUS 32, REMAINDER 31);- App vẫn query bảng
short_urlsbình thường, PostgreSQL tự route:hash(short_code) MOD 32→ đúng partition.
Tại sao chọn 32 partitions?
| Số partition | Data/partition/year (5.48TB total [C4]) | Đánh giá |
|---|---|---|
| 8 | ~685GB | Quá lớn, vacuum chậm, index khó fit RAM |
| 32 | ~170GB | Vừa phải, vacuum nhanh, index fit RAM trên RDS r6g.large |
| 64 | ~85GB | Nhỏ hơn nhưng overhead quản lý nhiều partition, metadata tăng |
⚠️ Lưu ý: Số hash partition trong PostgreSQL không thể thay đổi sau khi tạo. Chọn sai phải migrate toàn bộ data → nên chọn dư hơn một chút ngay từ đầu.
Range Partition cho url_stats_daily
url_stats_daily: range partition theostat_datetheo tháng — dễ drop partition cũ khi retention hết hạn.
Khi nào cần Sharding (nhiều RDS cluster)?
- Nếu tổng data vượt ~30TB
[C4](tức khoảng năm thứ 3 theo estimate 5.48TB/year + index), cân nhắc shard theo prefixshort_code(application-level routing) sang nhiều RDS cluster. - Partitioning (chia nhỏ trong 1 DB instance) và sharding (chia sang nhiều DB instance) là 2 bước khác nhau — partitioning giải quyết vấn đề vacuum/index, sharding giải quyết vấn đề vượt giới hạn phần cứng 1 instance.
Data Retention Policy
short_urls: giữ lâu dài (trừ khi user yêu cầu xóa theo compliance).url_stats_daily: giữ chi tiết 24 tháng, sau đó rollup monthly.- Raw click events trong S3 lifecycle về Glacier sau 90 ngày. Với 1.2B clicks/day
[C7], mỗi event ~200B → raw events ~240GB/day → ~7.2TB/tháng trước khi archive.
💡 Tại sao không lưu toàn bộ click events vào PostgreSQL? Redirect có QPS rất cao; ghi synchronous vào PostgreSQL sẽ tăng latency và chi phí write. Dùng Kafka + S3 data lake cho raw events giúp tách critical path và scale analytics tốt hơn.
9. ⚙️ Manager Classes / Services
Service Decomposition (Spring Boot microservices)
gateway-service: auth, rate limiting, request routing.url-service: tạo link, validate, ownership checks, metadata CRUD.redirect-service: resolve short code, cache fallback DB, emit click event.analytics-service: consume Kafka events, aggregateurl_stats_daily.id-generator-service: sinh Snowflake IDs đồng nhất toàn cụm.
Core Service Classes & Responsibilities
ShortUrlService(@Service): business logic create/disable URL.RedirectResolver(@Component): resolve + expiration/status checks.ClickEventPublisher(@Component): publish analytics events tới Kafka.SecurityConfig(@Configuration): Spring Security + JWT validation.AuditLoggingAspect(@Aspect): log structured audit cho actions quan trọng.
Backend Code Example (Java / Spring Boot)
@Servicepublic class ShortUrlService { private final ShortUrlRepository shortUrlRepository; private final IdGeneratorClient idGeneratorClient; public ShortUrlService(ShortUrlRepository shortUrlRepository, IdGeneratorClient idGeneratorClient) { this.shortUrlRepository = shortUrlRepository; this.idGeneratorClient = idGeneratorClient; } @Transactional public ShortUrlResponse create(CreateShortUrlRequest req, Long userId) { String shortCode = req.customAlias() != null ? req.customAlias() : Base62.encode(idGeneratorClient.nextId()); if (shortUrlRepository.existsByShortCode(shortCode)) { throw new ConflictException("ALIAS_ALREADY_EXISTS"); } ShortUrlEntity entity = ShortUrlEntity.of(shortCode, req.longUrl(), userId, req.expireAt()); shortUrlRepository.save(entity); return ShortUrlResponse.from(entity); }}Repository và ID generator được inject; service không tạo dependency trong business method.
Frontend Code Example (React + TypeScript)
import { useState } from "react";
export function CreateUrlForm() {
const [longUrl, setLongUrl] = useState("");
const [shortUrl, setShortUrl] = useState("");
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
const res = await fetch("/api/v1/urls", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ longUrl }),
});
const data = await res.json();
setShortUrl(data.shortUrl);
}
return (
<form onSubmit={onSubmit}>
<input value={longUrl} onChange={(e) => setLongUrl(e.target.value)} placeholder="Paste long URL" />
<button type="submit">Shorten</button>
{shortUrl && <p>{shortUrl}</p>}
</form>
);
}Service Communication Patterns
- Sync REST: Gateway -> URL/Redirect services qua internal HTTP (WebClient).
- Async event: Redirect service -> Kafka -> Analytics service.
- Shared libs: common error model, tracing interceptor, auth principal extractor.
10. 🏛️ Architecture Design
- Pattern chính: Microservices + Event-driven analytics.
- Redirect path tối ưu read latency: CloudFront -> Gateway -> Redis -> PostgreSQL fallback.
- Deployment trên AWS EKS multi-AZ, tách node group cho redirect workload.
- RDS PostgreSQL Multi-AZ + read replicas cho traffic đọc metadata.
- ElastiCache Redis cluster mode enabled để scale ngang.
Scaling Strategy
- HPA theo CPU + custom metric (
redirect_rps) choredirect-service: target peak ~70K QPS[C2]. Giả sử mỗi pod xử lý ~5K RPS → cần ~14 pods peak, HPA rangemin=4, max=20. - HPA cho
url-service: target peak ~1.7K write QPS[C1]. Mỗi pod ~500 RPS → cần ~4 pods peak, HPA rangemin=2, max=6. - VPA cho
analytics-service(batch workload biến động). - PostgreSQL: RDS r6g.xlarge Multi-AZ cho primary (cần chứa 15GB/day
[C3]write + index). Scale-up lên r6g.2xlarge khi data vượt 10TB. Read replica cho dashboard APIs. - Redis shard rebalancing khi memory >70% của ~40GB
[C6]→ alert tại 28GB used.
Caching Strategy
- L1: CloudFront cache cho popular short links — với 1.8TB bandwidth/day
[C5], CloudFront absorb 30-50% traffic giúp giảm origin bandwidth xuống ~0.9-1.3TB/day và tiết kiệm ~$200-400/tháng data transfer. - L2: Redis cache-aside tại redirect-service — cluster cần ~40GB
[C6], chọn ElastiCache r6g.large (2 nodes × 26GB = 52GB usable) đủ chứa 50M hot entries + headroom. - Eviction policy Redis:
allkeys-lru, TTL dynamic theo popularity.
Load Balancing / Gateway / Mesh
- ALB route vào EKS ingress controller.
- Spring Cloud Gateway xử lý auth/rate-limit.
- Service mesh (Istio hoặc Linkerd) optional cho mTLS và traffic policy nội bộ.
Resilience Patterns
- Circuit Breaker (Resilience4j): redirect-service gọi Redis/PostgreSQL qua circuit breaker.
- Failure threshold: 50% errors trong 10 requests sliding window.
- Open state duration: 30s → half-open → thử 3 requests → close nếu thành công.
- Fallback khi Redis circuit open: đọc thẳng PostgreSQL (degraded latency nhưng vẫn redirect được).
- Retry with Backoff: URL service retry gọi ID generator với exponential backoff (100ms → 200ms → 400ms, max 3 retries) + jitter ±50ms để tránh thundering herd.
- Bulkhead: redirect-service và url-service dùng separate thread pools (redirect: 200 threads, url-create: 50 threads) để isolate workload, tránh create traffic ảnh hưởng redirect critical path.
- Timeout: Redis GET timeout 5ms, PostgreSQL query timeout 50ms, ID generator call timeout 100ms. Nếu vượt timeout → circuit breaker ghi nhận failure.
- Graceful Degradation:
- Redis down → fallback DB (latency tăng từ ~5ms lên ~30ms nhưng vẫn hoạt động).
- Kafka down → buffer click events in-memory (bounded queue 10K events) và retry publish; redirect vẫn trả response bình thường, chỉ analytics bị delay.
- ID generator down → url-service trả
503 Service UnavailablevớiRetry-Afterheader, redirect path không bị ảnh hưởng.
- Request Coalescing: khi cache miss đồng thời cho cùng
short_code, dùng singleflight pattern (chỉ 1 request đọc DB, các request khác chờ kết quả) để tránh stampede lên PostgreSQL.
11. 🧪 Testing Strategy
- Unit Testing: JUnit 5 + Mockito cho service logic, coverage target >80%.
- Integration Testing: Spring Boot Test + Testcontainers (PostgreSQL, Redis, Kafka).
- API Contract Testing: Spring Cloud Contract giữa gateway và downstream services.
- Load Testing: Gatling kịch bản 70K redirect QPS
[C2]+ 1.7K write QPS[C1], xác nhận redirect p95 < 50ms (cache hit), create p95 < 200ms. - Chaos Engineering: AWS Fault Injection Simulator để test Redis node failure, AZ outage.
- E2E Testing: Playwright cho web UI tạo link + validate redirect behavior.
12. 🔒 Security
- Authentication: OAuth2/JWT cho management APIs, anonymous only cho redirect endpoint.
- Authorization: owner-based access control cho metadata/stats/delete.
- TLS everywhere: HTTPS public, mTLS nội bộ (nếu bật service mesh).
- Input validation: chặn SSRF patterns, chặn private CIDR targets nếu policy yêu cầu.
- DDoS/bot protection: WAF rate rules + AWS Shield Standard.
- Data protection: encryption at rest (RDS/Redis/S3 KMS), encryption in transit.
- Secrets management: DB credentials, JWT signing keys, API keys lưu trong AWS Secrets Manager; inject vào pods qua External Secrets Operator, rotate tự động mỗi 90 ngày.
- OWASP Top 10: chống injection, broken auth, security misconfiguration qua secure defaults và SAST/DAST.
- Compliance: hỗ trợ GDPR right-to-erasure (xóa URL + analytics data theo user request), data residency EU nếu cần qua dedicated RDS instance.
13. 📊 Monitoring & Logging
Key Metrics
| Nhóm | Metrics |
|---|---|
| Latency | p50/p95/p99 redirect latency, create latency |
| Traffic | requests per second, redirects per short code |
| Errors | 4xx/5xx rate, DB timeout rate, cache miss ratio |
| Saturation | CPU/memory pods, Redis memory%, DB connections |
Logging Strategy
- Structured JSON logs với
traceId,shortCode,userId,statusCode. - Log level: INFO cho business events, WARN cho retry, ERROR cho failures.
- Centralized logging qua ELK/OpenSearch, retention theo compliance.
SLI / SLO / Error Budget (SRE)
- SLI redirect: tỷ lệ redirect requests trả về
301/302/404/410(không phải5xx) trong tổng redirect requests. - SLI create: p99 latency của
POST /api/v1/urlsresponse time. - SLO redirect availability: 99.99% → error budget = 0.01% = tối đa 4.3 phút downtime/tháng hoặc ~4,320 failed requests/tháng (trên 43.2M requests/tháng).
- SLO create latency: p99 < 300ms cho 99.5% thời gian đo trong 30 ngày rolling window.
- Error budget policy:
- Khi error budget còn > 50%: deploy bình thường, cho phép feature releases.
- Khi error budget còn 20-50%: chỉ deploy với canary chặt (5% → 10% → 25% → 100%), tăng thời gian bake giữa các stage.
- Khi error budget cạn (< 20%): freeze feature deployments, chỉ cho phép reliability fixes và rollbacks. Postmortem bắt buộc cho mọi incident tiêu tốn > 10% error budget.
Alerting & Incident Response
- Alert nếu
redirect p95 > 100mstrong 5 phút. - Alert nếu
5xx > 1%hoặccache hit ratio < 80%. - Runbook: detect -> triage -> mitigate -> postmortem trong 24h.
- Distributed tracing bằng OpenTelemetry + Jaeger/X-Ray.
🔎 Đọc trace của một cache miss
Trace dưới đây là dữ liệu minh họa, không phải benchmark hay bằng chứng đạt p95/p99 ở §2.2. Span dùng chung mốc 0; tổng latency là 42ms của root span, không phải tổng duration các span lồng nhau. Kafka publish được xử lý ngoài response path theo §6, không cộng vào latency redirect.
- GET /abc123x → 301gateway · OKBắt đầu 0 ms, thời lượng 42 ms, cấp 0.
- Resolve short coderedirect-service · OKBắt đầu 4 ms, thời lượng 34 ms, cấp 1.
- GET redirect cache — missredis · OKBắt đầu 6 ms, thời lượng 2 ms, cấp 2.
- SELECT mappingpostgres · OKBắt đầu 9 ms, thời lượng 23 ms, cấp 2.
- SET mapping với TTLredis · OKBắt đầu 33 ms, thời lượng 2 ms, cấp 2.
- Cache miss không phải lỗi
Không có mapping trong cache vẫn là Redis operation thành công; DB phục vụ fallback.
- Khoanh vùng database
Query chiếm 23ms trong trace minh họa; kiểm tra query plan, connection wait và saturation trước khi tăng cache TTL.
Chi tiết span
Chi tiết span
GET /abc123x → 301 gateway · OK · 42 ms
- ID
- request
- Cha
- Không có (root)
- Bắt đầu
- 0 ms
- Kết thúc
- 42 ms
Không khai báo attributes.
Resolve short code redirect-service · OK · 34 ms
- ID
- resolve
- Cha
- request
- Bắt đầu
- 4 ms
- Kết thúc
- 38 ms
Không khai báo attributes.
GET redirect cache — miss redis · OK · 2 ms
- ID
- cache
- Cha
- resolve
- Bắt đầu
- 6 ms
- Kết thúc
- 8 ms
{
"cache.hit": false,
"db.system.name": "redis"
}SELECT mapping postgres · OK · 23 ms
- ID
- database
- Cha
- resolve
- Bắt đầu
- 9 ms
- Kết thúc
- 32 ms
{
"db.system.name": "postgresql",
"db.operation.name": "SELECT"
}SET mapping với TTL redis · OK · 2 ms
- ID
- populate
- Cha
- resolve
- Bắt đầu
- 33 ms
- Kết thúc
- 35 ms
Không khai báo attributes.
Bảng thời gian đầy đủ
| Span / ID | Cha | Service | Bắt đầu | Thời lượng | Kết thúc | Trạng thái |
|---|---|---|---|---|---|---|
| GET /abc123x → 301request | — | gateway | 0 ms | 42 ms | 42 ms | OK |
| Resolve short coderesolve | request | redirect-service | 4 ms | 34 ms | 38 ms | OK |
| GET redirect cache — misscache | resolve | redis | 6 ms | 2 ms | 8 ms | OK |
| SELECT mappingdatabase | resolve | postgres | 9 ms | 23 ms | 32 ms | OK |
| SET mapping với TTLpopulate | resolve | redis | 33 ms | 2 ms | 35 ms | OK |
Về trace
Timeline do tác giả biên soạn để hướng dẫn đọc OpenTelemetry trace; không đo từ production.
Thời gian tương đối từ mốc 0; không cộng thời lượng các span chồng nhau. Quan hệ cha/con không khẳng định thứ tự nhân quả.
- gateway
- redirect-service
- redis
- postgres
14. 🔧 Maintenance
- CI/CD: GitHub Actions pipeline
build -> test -> security scan -> deploy. - Database migration: Flyway versioned migrations, backward-compatible trước.
- Dependency/security maintenance: Renovate + SCA scan định kỳ.
- Feature flags: LaunchDarkly (hoặc config service) cho rollout custom alias/analytics.
- Documentation: OpenAPI/Swagger auto-publish, cập nhật decision records (ADR).
- Technical debt review: sprint cuối tháng dành 10-15% capacity xử lý debt.
15. 🚀 Deployment Plans
- Deployment strategy: Canary (5% -> 25% -> 100%) cho redirect-service, blue-green cho gateway.
- Rollback plan:
kubectl rollout undo, rollback Flyway theo migration policy, disable feature flags. - IaC: Terraform modules cho VPC, EKS, RDS, ElastiCache, MSK, S3, IAM.
- Auto-scaling: HPA/VPA + cluster autoscaler + ASG cho worker nodes.
- Multi-region: active-passive (primary + DR), Route53 health-check failover.
- Artifacts: Docker multi-stage build cho Spring Boot, Helm charts cho từng service.
- Pre-prod gate: bắt buộc qua load test + smoke test trước production rollout.
16. ⏱️ Effort Estimation
Phase Breakdown & Timeline
| Phase | Duration | Deliverables |
|---|---|---|
| Discovery & Requirements | 1 tuần | Scope, SLA, API contract draft |
| Core URL + Redirect MVP | 2 tuần | Create/redirect APIs, PostgreSQL + Redis |
| Analytics + Observability | 1.5 tuần | Kafka pipeline, dashboards, alerts |
| Security + Hardening | 1 tuần | AuthZ, WAF rules, abuse protections |
| Performance + Production Readiness | 1.5 tuần | Load test, chaos test, runbooks |
| Total | ~7 tuần | Production v1 |
Team Composition
- 1 Tech Lead (architecture, trade-offs, review).
- 2 Backend Engineers (URL/redirect/analytics services).
- 1 Frontend Engineer (dashboard + URL management UI).
- 1 DevOps Engineer (EKS/Terraform/CI-CD/monitoring).
- 1 QA Engineer (test automation + performance validation).
Risk Assessment
| Risk | Impact | Mitigation |
|---|---|---|
| Cache stampede khi hot link viral | Tăng latency đột biến | request coalescing + short TTL jitter |
| Abuse/spam links | Reputation risk | domain blocklist + rate limits + moderation queue |
| DB hotspot trên short_code | Throughput giảm | hash partition + read replicas + cache tuning |
| Analytics lag khi Kafka backlog | Stats trễ | autoscale consumers + lag alert + replay tooling |
Dependencies & Blockers
- Cần IAM/security baseline từ platform team trước khi lên production.
- Cần domain + TLS certificate + WAF policy approved.
- Cần budget approval cho MSK và cross-region DR.
17. 💰 Cost Estimation & Optimization
17.1 Chi phí hàng tháng theo từng resource (AWS On-Demand, region ap-southeast-1)
Compute (EKS)
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| EKS Control Plane | Managed | 1 | ~$73 | $73 | Cố định |
| Redirect Service nodes | c6g.xlarge (4 vCPU, 8GB) | 4-20 pods, cần ~4 nodes avg | ~$100/node | $400 | HPA min=4, max=20 [C2] peak ~70K QPS |
| URL Service nodes | c6g.large (2 vCPU, 4GB) | 2-6 pods, cần ~2 nodes avg | ~$62/node | $124 | HPA min=2, max=6 [C1] peak ~1.7K QPS |
| Gateway nodes | c6g.large | 2 nodes (HA) | ~$62/node | $124 | Always-on, rate limiting |
| Analytics Service nodes | c6g.large | 2-4 pods, ~2 nodes avg | ~$62/node | $124 | VPA, consumer Kafka [C7] |
Subtotal Compute: ~$845/tháng
Database
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| RDS PostgreSQL Primary | r6g.xlarge Multi-AZ (4 vCPU, 32GB) | 1 | ~$580 | $580 | Write path, 15GB/day [C3] |
| RDS Read Replica | r6g.large (2 vCPU, 16GB) | 1 | ~$200 | $200 | Dashboard/stats queries |
| RDS Storage (gp3) | 500GB initial (grow ~15GB/day [C3]) | 1 | ~$0.116/GB | $58 | Auto-scale, 5.48TB/yr [C4] |
Subtotal Database: ~$838/tháng
Cache
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| ElastiCache Redis (Redirect) | r6g.large (2 nodes, cluster mode) | 2 | ~$200/node | $400 | ~40GB total [C6], redirect cache |
| ElastiCache Redis (Rate Limit) | r6g.medium (1 node + replica) | 2 | ~$100/node | $200 | Gateway rate limiting, vài GB |
Subtotal Cache: ~$600/tháng
Message Queue
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| Amazon MSK | kafka.m5.large (3 brokers, Multi-AZ) | 3 | ~$165/broker | $495 | 1.2B events/day [C7], retention 7 days |
| MSK Storage | 500GB per broker | 3 | ~$0.10/GB | $150 | Click events + replay buffer |
Subtotal Message Queue: ~$645/tháng
Network / CDN
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| CloudFront | ~0.9-1.3TB origin bandwidth/day (sau cache absorb 30-50% [C5]) | 1 | ~$0.085/GB first 10TB | $250 | Edge cache cho redirect 301 |
| ALB | 1 ALB + LCU usage | 1 | ~$22 base + ~$80 LCU | $100 | Route vào EKS |
| NAT Gateway | 2 AZ | 2 | ~$32/gateway + data | $120 | Outbound traffic |
| Route53 | Hosted zone + queries | 1 | ~$0.50 + queries | $10 | DNS |
Subtotal Network: ~$480/tháng
Storage
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| S3 (Data Lake) | ~7.2TB/tháng raw click events [C7] | 1 | ~$0.025/GB (Standard) | $180 | 90 ngày hot, sau đó Glacier |
| S3 (Logs/Backups) | ~500GB | 1 | ~$0.025/GB | $13 | ELK ingest, DB backups |
Subtotal Storage: ~$193/tháng
Monitoring / Logging
| Resource | Spec / Sizing | Số lượng | Đơn giá (USD/tháng) | Thành tiền (USD/tháng) | Ghi chú |
|---|---|---|---|---|---|
| CloudWatch | Metrics + logs + alarms | 1 | — | $100 | Basic metrics + log groups |
| Managed Prometheus + Grafana | AMP + AMG | 1 | — | $120 | Custom metrics, dashboards |
Subtotal Monitoring: ~$220/tháng
17.2 Tổng hợp cost theo giai đoạn
| Giai đoạn | Monthly Cost | Annual Cost | Ghi chú |
|---|---|---|---|
| MVP (10% traffic, minimal replicas) | ~$2,800 | ~$33,600 | 1 RDS r6g.large, 1 Redis node, 2 redirect pods, MSK smallest |
| Growth (avg traffic — bảng 17.1) | ~$3,821 | ~$45,852 | Full setup như 17.1, avg load |
| Peak / Scale (peak traffic, max HPA) | ~$6,500-8,000 | ~$78,000-96,000 | HPA max out, RDS scale-up r6g.2xlarge, thêm Redis shards, CloudFront bandwidth tăng |
17.3 Cost Breakdown theo category
| Category | USD/tháng (Growth) | % tổng cost |
|---|---|---|
| Compute (EKS) | $845 | 22% |
| Database (RDS) | $838 | 22% |
| Message Queue (MSK) | $645 | 17% |
| Cache (ElastiCache) | $600 | 16% |
| Network / CDN | $480 | 13% |
| Monitoring | $220 | 6% |
| Storage (S3) | $193 | 5% |
| Tổng | ~$3,821 | 100% |
📌 Database + Compute chiếm ~44% tổng cost — đây là 2 category ưu tiên optimize đầu tiên (Reserved Instances, right-sizing).
17.4 Cost Optimization Strategies
| Strategy | Mô tả | Tiết kiệm ước tính | Trade-off |
|---|---|---|---|
| Reserved Instances (1 năm) | Commit RDS + ElastiCache (always-on workload) | Lock-in 1 năm, khó đổi instance type | |
| Savings Plans (Compute) | Commit compute spend cho EKS nodes | Lock-in 1-3 năm | |
| Spot Instances | Dùng cho analytics-service nodes (fault-tolerant, stateless) | Có thể bị interrupt, cần graceful shutdown | |
| Right-sizing review | Quarterly review CPU/memory utilization, downgrade over-provisioned nodes | Cần monitoring data đủ lâu | |
| S3 Lifecycle Policies | Click events > 90 ngày → Glacier Deep Archive ($0.002/GB) | Restore time 12-48h cho Glacier | |
| CloudFront cache optimization | Tăng cache hit ratio từ 30-50% lên 60-70% (tune Cache-Control headers) | Giảm origin bandwidth ~$50-100/tháng | Stale content risk nếu TTL quá dài |
| VPC Endpoints | Thay NAT Gateway bằng VPC endpoints cho S3/DynamoDB/CloudWatch | Giảm NAT data processing → ~$50-80/tháng | Cần setup endpoint policies |
| MSK Serverless | Chuyển từ provisioned MSK sang serverless (nếu traffic biến động lớn) | Giảm | Latency có thể cao hơn khi cold start |
| Log sampling | Sample debug logs 10%, giữ 100% error/warn | Giảm CloudWatch ingest → ~$30-50/tháng | Mất một phần debug context |
Tổng tiết kiệm ước tính khi áp dụng RI + Savings Plans + Spot + S3 lifecycle: ~$900-1,100/tháng (giảm ~25-30% so với On-Demand)
17.5 Cost Projection (12 tháng, growth rate ~20%/quý)
| Tháng | Traffic estimate | Infra changes | Monthly Cost |
|---|---|---|---|
| 1-3 (MVP) | 10% design load | Minimal setup | ~$2,800 |
| 4-6 (Growth) | 30-50% design load | Full setup, HPA active | ~$3,200-3,800 |
| 7-9 (Scale) | 70-100% design load | RDS scale-up, thêm Redis shard | ~$4,500-5,500 |
| 10-12 (Peak) | 100-120% design load | HPA max, xem xét thêm read replica | ~$6,000-7,500 |
| Năm thứ 2 | Nếu traffic tiếp tục tăng 20%/quý | Cân nhắc shard DB khi > 30TB [C4], thêm AZ | ~$8,000-12,000 |
📌 Điểm inflection quan trọng:
- Tháng 9-12: RDS storage vượt 2TB → cần evaluate upgrade lên r6g.2xlarge (~+$400/tháng).
- Năm thứ 2-3: Data vượt 15-30TB
[C4]→ cần shard PostgreSQL hoặc migrate hot data sang dedicated cluster.- Redis: Khi memory vượt 70% (~28GB)
[C6]→ thêm shard hoặc upgrade node type.
17.6 Cost Alerts & Governance
- AWS Budget alerts:
- 80% budget ($3,057): warning notification → team review.
- 100% budget ($3,821): alert → investigate unexpected cost increase.
- 120% budget ($4,585): critical → immediate action, check for runaway resources.
- Review cadence: monthly cost review (DevOps + Tech Lead), quarterly deep-dive với optimization recommendations.
- Tagging strategy: tất cả resources tag theo:
team: url-shortenerservice: redirect | url | analytics | gatewayenvironment: dev | staging | production- Dùng AWS Cost Explorer group by tag để phân bổ cost chính xác theo service.