System Design Practice

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

PriorityRequirementMô tả
MUST-HAVECreate short URLUser nhập long URL và nhận về short URL duy nhất
MUST-HAVERedirectKhi truy cập short URL, hệ thống trả về HTTP redirect đến long URL
MUST-HAVEHigh availability redirectRedirect vẫn hoạt động khi một phần service lỗi
MUST-HAVEURL validationValidate format URL, block schema không hợp lệ
NICE-TO-HAVECustom aliasUser chọn alias riêng (ví dụ tiny.ly/sale2026)
NICE-TO-HAVEExpiration timeLink tự hết hạn theo thời gian
NICE-TO-HAVEBasic analyticsTheo 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 seconds
  • 1M = 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

InputGiá trịTại sao chọn
DAU100M users/dayBài toán consumer scale lớn
New short URLs/day30M links/dayGiả sử khoảng 30% DAU tạo 1 link/ngày
Read:Write ratio40:1Hệ 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 size300BKịch bản conservative (URL có query params/UTM)
Metadata per URL200Bid, short_code, status, user_id, timestamps + overhead row/index
Avg redirect payload1.5KB/clickRequest + response headers và overhead mạng cơ bản

📌 300B cho long_url là 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 = 20GB raw
  • 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ảnAvg long URLRecord sizeDaily storage (30M links/day)
Base120B320B9.6GB/day
Conservative (đang dùng)300B500B15GB/day

📊 Bảng tổng hợp Capacity Estimation

IDMetricAvgPeak
C1Write QPS~347~1,735
C2Read QPS (redirect)~13,889~69,445
C3Daily storage15GB/day—
C4Yearly / 5-year storage5.48TB/yr~82TB/5yr
C5Bandwidth (redirect)1.8TB/day—
C6Redis cache memory~40GB—
C7Daily click events1.2B/day—

3. ⚖️ Trade-offs

3.1 Bảng tổng quan quyết định

DecisionOption AOption BChọnLý do chính
ID generationRandom hash + collision checkSnowflake ID + Base62BKhông cần collision check runtime, latency ổn định khi write tăng
Redirect type302 (temporary)301 (permanent)BCache tốt ở browser/CDN, giảm request quay về origin
Data store chínhPostgreSQLCassandraACần unique constraints + query quản trị linh hoạt
Cache strategyCache-aside RedisWrite-throughAPhù hợp workload read-heavy, giảm write amplification
Analytics pipelinePostgreSQL sync writeKafka async eventsBTá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 checkSnowflake + Base62
UniquenessProbabilistic, cần check DBDeterministic unique theo node+timestamp+sequence
Write latencyCó thể tăng khi phải retry collisionỔn định hơn, không cần retry collision
Độ dài short codeDễ ép cố định 7-8 charsEncode full ID thường 10-11 chars
Độ phức tạp vận hànhĐơn giản lúc đầuCần đồng bộ clock và worker ID

Cách 1: Random Hash + Collision Check hoạt động thế nào?

  1. Nhận long_url.
  2. Tạo seed: long_url + "|" + nonce + "|" + timestamp.
  3. Băm SHA-256(seed).
  4. Convert hash sang Base62, lấy 7 ký tự đầu làm short_code.
  5. Check DB: nếu trùng thì tăng nonce và lặp lại.

Ví dụ từng bước:

  1. long_url = https://shop.example.com/deal?utm_campaign=sale&utm_source=facebook
  2. timestamp = 2026-02-28T10:00:00Z
  3. 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
  4. 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
  • Đ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ý:

  1. id_generator_service tự quản lý sequence và sinh snowflake_id.
  2. URL service encode snowflake_id sang Base62.
  3. Insert DB một lần (UNIQUE index chỉ là safety net).

Flow end-to-end cụ thể (với số thật):

  1. Cấu hình:
    • epoch = 2024-01-01T00:00:00Z
    • workerId = 17
    • Generator state ban đầu: lastTimestamp = null, sequence = 0
  2. 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) | 0
    • snowflake_id = 286075021418369024
    • Base62 -> L8E3B1JoxM
    • Insert DB:
      • id = 286075021418369024
      • short_code = L8E3B1JoxM
      • long_url = ...
  3. Request B vẫn trong cùng ms .123:
    • timestamp không đổi -> tăng sequence = 1
    • snowflake_id = 286075021418369025
    • Base62 -> L8E3B1JoxN
    • Insert DB 1 lần thành công
  4. Request C vẫn trong cùng ms .123:
    • sequence = 2
    • snowflake_id = 286075021418369026
    • Base62 -> L8E3B1JoxO
  5. 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, reset sequence = 0
    • ID mới: 286075021422563328 -> L8E3B1bQ5Q
  6. 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).

Chi tiết bước 2: URL service encode Snowflake ID sang Base62

  • Bảng ký tự Base62: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  • Nguyên tắc:
    1. Lấy id chia cho 62.
    2. Lấy remainder (0..61) map sang 1 ký tự.
    3. Lấy quotient chia tiếp cho 62 đến khi bằng 0.
    4. Ghép các ký tự theo thứ tự ngược lại.

Ví dụ với id = 286075021418369024:

Vòngn hiện tạiq = n / 62r = n % 62Ký tự
1286075021418369024461411324868337122M
246141132486833717442118143037659x
374421181430376120034163597350o
412003416359731936034896719J
51936034896731226369311
6312263693503651111B
750365118123433
881234131014E
913102188
1021021L
  • 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?

  • workerId phải unique giữa các node.

  • Trên mỗi node, sequence tăng dần trong cùng ms; sang ms mới thì reset.

  • Nếu sequence trà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 net

Kế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 Temporary301 Permanent
Cache browser/CDNThấp hơnCao hơn
Latency trung bìnhCao hơn do quay lại origin nhiều hơnThấp hơn cho traffic lặp
Khả năng đổi target URLLinh hoạt hơnKém linh hoạt hơn (client cache lâu)
SEOTrung tínhTố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ốngNếu dùng 302Nếu dùng 301
User click lần 1Trình duyệt vẫn phải hỏi originTrình duyệt nhận redirect và có thể cache
User click lần 2 cùng linkThường vẫn gọi lại originNhiề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ơnGiảm đáng kể origin QPS
Owner đổi target URLDễ cập nhật ngayKhó hơn do client/CDN có thể cache lâu

Ví dụ end-to-end cụ thể

  1. Giả sử một short link được click 10M lần/ngày, trong đó 60% là revisit từ user/client đã từng click.
  2. Nếu dùng 302, phần lớn 10M request vẫn quay về origin để lấy redirect.
  3. Nếu dùng 301 + Cache-Control: public, max-age=86400, phần revisit có thể được phục vụ từ browser/CDN.
  4. Giả sử cache absorb được 40% traffic revisit, origin giảm khoảng:
    • 10M * 60% * 40% = 2.4M requests/day
  5. 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, set Cache-Control: no-store cho response lỗi, trigger CDN invalidation cho key nóng.
  • 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ả 410 ngay.

3.4 Decision #3: Primary Data Store (PostgreSQL vs Cassandra)

Tiêu chíPostgreSQLCassandra
Unique alias constraintsMạnh (UNIQUE index)Phức tạp hơn (cần design riêng)
Transaction supportACID tốtEventual 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ớnScale vertical + partition/read replicaScale ngang rất tốt

Access patterns cần support

  1. GET /{shortCode}: lookup theo short_code (cực nhiều).
  2. POST /api/v1/urls: insert mới + kiểm tra unique alias.
  3. GET /api/v1/urls?cursor=...: list URL theo user_id, sort theo created_at.
  4. DELETE /api/v1/urls/{shortCode}: update status/soft-delete.
  5. 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

  1. Create link:
    • Validate URL.
    • Sinh short_code.
    • INSERT vào short_urls.
    • Nếu trùng unique -> 409 Conflict.
  2. Redirect:
    • Đọc Redis trước.
    • Miss thì SELECT long_url, status, expires_at FROM short_urls WHERE short_code=?.
  3. 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_urls theo short_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àiRDS bắt đầu là bottleneck ghi
Dữ liệu phân tán đa region active-active mạnhCassandra replication model có lợi hơn
Access pattern đơn giản dạng key-value khối lượng cực lớnCassandra 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-asideWrite-through
Độ phức tạpĐơn giản, app kiểm soát cacheLogic ghi đồng thời DB + cache
Cache miss đầu tiênCó penaltyÍt hơn
Write costThấp hơnCao hơn (mọi write đi qua cache)
Phù hợp read-heavyTốtTrung 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

  1. GET /{shortCode} vào redirect-service.
  2. Service gọi Redis:
    • Hit: trả redirect ngay (không chạm DB).
    • Miss: đọc PostgreSQL -> validate status/expiry -> set Redis -> trả redirect.
  3. 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 ~25ms baseline 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_url gầ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 PostgreSQLKafka async events
Redirect latencyTăng theo DB writeThấp hơn, tách khỏi critical path
Độ bền dữ liệu clickCao nhưng đắtCao nếu cấu hình durability đúng
Khả năng scale analyticsHạn chếRất tốt, consumer scale ngang
Độ phức tạpĐơn giản ban đầuCao 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ànhSync DB writeKafka async
Redirect p95Dễ tăng theo DB contentionỔn định hơn vì tách luồng
Khả năng buffer burst trafficThấpCao (Kafka làm buffer)
Khả năng replay dữ liệuKhóDễ (re-consume theo offset)
Phức tạp hệ thốngThấpTrung bình-cao

Flow Kafka async chi tiết

  1. Redirect service resolve short code và trả 301 cho client trước.
  2. Cùng lúc publish ClickEvent vào Kafka topic url-click-events.
  3. Analytics consumer đọc event theo partition.
  4. Consumer aggregate theo (short_code, stat_date) và upsert vào url_stats_daily.
  5. Raw events đồng thời đẩy sang S3 để phân tích sâu/offline.
  6. 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 eventId trong 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

direction: right

U: "User / Browser / Mobile App"
CF: "CloudFront + WAF" {
  icon: ../../diagrams/icons/cloudfront.svg
}
ALB: "ALB" {
  icon: ../../diagrams/icons/load-balancer.svg
}
GW: "Spring Cloud Gateway"
RL_REDIS: "ElastiCache Redis Rate Limit" {
  shape: cylinder
  icon: ../../diagrams/icons/redis.svg
}
URLSVC: "URL Management Service\n+ ID Generator lib"
REDIRSVC: "Redirect Service"
PG: "PostgreSQL RDS" {
  shape: cylinder
  icon: ../../diagrams/icons/rds.svg
}
REDIS: "ElastiCache Redis\nRedirect Cache" {
  shape: cylinder
  icon: ../../diagrams/icons/redis.svg
}
KAFKA: "Kafka / MSK" {
  shape: cylinder
  icon: ../../diagrams/icons/msk.svg
}
ANSVC: "Analytics Service"
PGS: "PostgreSQL Stats" {
  shape: cylinder
  icon: ../../diagrams/icons/postgres.svg
}
S3: "S3 Data Lake" {
  shape: cylinder
  icon: ../../diagrams/icons/s3.svg
}
OBS: "Prometheus + Grafana + CloudWatch"

U -> CF
CF -> ALB
ALB -> GW
GW -> RL_REDIS
GW -> URLSVC
GW -> REDIRSVC
URLSVC -> PG
REDIRSVC -> REDIS
REDIRSVC -> PG
REDIRSVC -> KAFKA
KAFKA -> ANSVC
ANSVC -> PGS
ANSVC -> S3
OBS -> GW: "monitor" {style.stroke-dash: 4}
OBS -> URLSVC: "monitor" {style.stroke-dash: 4}
OBS -> REDIRSVC: "monitor" {style.stroke-dash: 4}
User / Browser / Mobile AppCloudFront + WAFALBSpring Cloud GatewayElastiCache Redis Rate LimitURL Management Service+ ID Generator libRedirect ServicePostgreSQL RDSElastiCache RedisRedirect CacheKafka / MSKAnalytics ServicePostgreSQL StatsS3 Data LakePrometheus + Grafana + CloudWatch monitormonitormonitor
User / Browser / Mobile AppCloudFront + WAFALBSpring Cloud GatewayElastiCache Redis Rate LimitURL Management Service+ ID Generator libRedirect ServicePostgreSQL RDSElastiCache RedisRedirect CacheKafka / MSKAnalytics ServicePostgreSQL StatsS3 Data LakePrometheus + Grafana + CloudWatch monitormonitormonitor
url-shortener — Thành phần hệ thống
ComponentVai trò
CloudFront + WAFEdge caching, DDoS/basic bot protection, giảm latency toàn cầu
Spring Cloud GatewayAPI routing, auth filter, rate limiting
URL Management ServiceCreate/update/delete URL, custom alias validation, sinh Snowflake ID (embedded library)
Redirect ServiceResolve short code và trả redirect response cực nhanh
RedisCache mapping short_code -> long_url cho hot traffic
PostgreSQLSource of truth cho URL metadata, ownership, expiration
Kafka + Analytics ServiceThu 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ý workerId qua 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ý workerId tập trung.

5. 🔗 Client-Server Connection

  • Protocol:
    • Management APIs: HTTPS REST/JSON (/api/v1/...).
    • Redirect: HTTP GET /{shortCode} trả về 301 Location.
  • 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-Key cho POST /api/v1/urls để tránh tạo trùng khi retry.

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

# viewport-height: 120vh
shape: sequence_diagram
C: "Client"
G: "API Gateway"
U: "URL Service"
I: "ID Service"
P: "PostgreSQL" {
  icon: ../../diagrams/icons/postgres.svg
}
R: "Redis" {
  icon: ../../diagrams/icons/redis.svg
}

C -> G: "POST /api/v1/urls { longUrl,\ncustomAlias? }"
G -> U: "Forward request + JWT claims"
U -> U: "Validate URL + policy"
group_1: "alt — chỉ chọn một nhánh" {
  group_2: "if: custom alias provided" {
    style: {
      stroke-dash: 4
    }
    U -> P: "Check alias uniqueness"
    P -> U: "available / conflict" {style.stroke-dash: 4}
  }
  group_3: "else: auto generated" {
    style: {
      stroke-dash: 4
    }
    U -> I: "nextId()"
    I -> U: "64-bit id" {style.stroke-dash: 4}
    U -> U: "Base62 encode -> shortCode"
  }
}
U -> P: "Insert short_url record"
U -> R: "Cache shortCode -> longUrl (TTL\noptional)"
U -> G: "201 Created + shortUrl" {style.stroke-dash: 4}
G -> C: "Response" {style.stroke-dash: 4}
ClientAPI GatewayURL ServiceID ServicePostgreSQLRedisalt — chỉ chọn một nhánhif: custom alias providedelse: auto generated POST /api/v1/urls { longUrl,customAlias? }Forward request + JWT claimsValidate URL + policyCheck alias uniqueness available / conflictnextId()64-bit idBase62 encode -> shortCodeInsert short_url recordCache shortCode -> longUrl (TTLoptional)201 Created + shortUrlResponse
ClientAPI GatewayURL ServiceID ServicePostgreSQLRedisalt — chỉ chọn một nhánhif: custom alias providedelse: auto generated POST /api/v1/urls { longUrl,customAlias? }Forward request + JWT claimsValidate URL + policyCheck alias uniqueness available / conflictnextId()64-bit idBase62 encode -> shortCodeInsert short_url recordCache shortCode -> longUrl (TTLoptional)201 Created + shortUrlResponse
url-shortener — Flow 1: Tạo short URL

Flow 2: Redirect short URL

shape: sequence_diagram
B: "Browser"
E: "Edge (CloudFront)" {
  icon: ../../diagrams/icons/cloudfront.svg
}
G: "Gateway"
R: "Redis" {
  icon: ../../diagrams/icons/redis.svg
}
S: "Redirect Service"
P: "PostgreSQL" {
  icon: ../../diagrams/icons/postgres.svg
}
K: "Kafka"

B -> E: "GET /abc123x"
E -> G: "Cache miss (or bypass)"
G -> S: "Resolve shortCode"
S -> R: "GET abc123x"
group_1: "alt — chỉ chọn một nhánh" {
  group_2: "if: Cache hit" {
    style: {
      stroke-dash: 4
    }
    R -> S: "longUrl" {style.stroke-dash: 4}
  }
  group_3: "else: Cache miss" {
    style: {
      stroke-dash: 4
    }
    S -> P: "SELECT long_url, expires_at,\nstatus"
    P -> S: "row data" {style.stroke-dash: 4}
    S -> R: "SET abc123x -> longUrl"
  }
}
S -> K: "Publish click event async"
S -> B: "301 Location: https://target-url" {style.stroke-dash: 4}
BrowserEdge (CloudFront)GatewayRedisRedirect ServicePostgreSQLKafkaalt — chỉ chọn một nhánhif: Cache hitelse: Cache miss GET /abc123xCache miss (or bypass)Resolve shortCodeGET abc123x longUrlSELECT long_url, expires_at,statusrow dataSET abc123x -> longUrlPublish click event async301 Location: https://target-url
BrowserEdge (CloudFront)GatewayRedisRedirect ServicePostgreSQLKafkaalt — chỉ chọn một nhánhif: Cache hitelse: Cache miss GET /abc123xCache miss (or bypass)Resolve shortCodeGET abc123x longUrlSELECT long_url, expires_at,statusrow dataSET abc123x -> longUrlPublish click event async301 Location: https://target-url
url-shortener — Flow 2: Redirect short URL

Error handling & Edge cases

  • Short code không tồn tại: trả 404 vớ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

MethodPathAuthMô tả
POST/api/v1/urlsJWT optional (required để quản lý ownership)Tạo short URL
GET/{shortCode}NoneRedirect đến long URL
GET/api/v1/urls/{shortCode}JWT owner/adminLấy metadata URL
GET/api/v1/urls/{shortCode}/stats?from=...&to=...JWT owner/adminLấy analytics
DELETE/api/v1/urls/{shortCode}JWT owner/adminDisable URL
GET/api/v1/urls?cursor=...&limit=20JWTDanh 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ụ.

Tạo short URL
201 CreatedPOST → 201

Request

POST/api/v1/urls
Headers
TênGiá trị
Content-Typeapplication/json
Idempotency-Key3f8f5e18-1fd3-4d16-8fdb-8bd1519e41d5
AuthorizationBearer <token>
{
  "longUrl": "https://example.com/products/spring-boot-url-shortener-guide",
  "customAlias": "spring-guide-2026",
  "expireAt": "2026-12-31T23:59:59Z"
}

Response

201Created
Headers
TênGiá trị
Content-Typeapplication/json
{
  "id": "01J7W6FQ3PR8M1H9B2Y7TZ0Y4D",
  "shortCode": "spring-guide-2026",
  "shortUrl": "https://tiny.example.com/spring-guide-2026",
  "longUrl": "https://example.com/products/spring-boot-url-shortener-guide",
  "createdAt": "2026-02-28T10:00:00Z",
  "expireAt": "2026-12-31T23:59:59Z"
}
GET /abc123x
301 Moved PermanentlyGET → 301

Request

GET/abc123x

Response

301Moved Permanently
Headers
TênGiá trị
Locationhttps://example.com/products/spring-boot-url-shortener-guide
Cache-Controlpublic, max-age=86400

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.

direction: down
SHORT_URLS: {
  shape: sql_table
  "id": bigint {constraint: primary_key}
  "short_code": varchar {constraint: unique}
  "long_url": text
  "user_id": bigint
  "status": varchar
  "expires_at": timestamptz
  "created_at": timestamptz
  "updated_at": timestamptz
}

URL_STATS_DAILY: {
  shape: sql_table
  "short_code": varchar {constraint: foreign_key}
  "stat_date": date {constraint: primary_key}
  "click_count": bigint
  "unique_ip_count": bigint
  "top_country": varchar
  "updated_at": timestamptz
}

SHORT_URLS."short_code" <-> URL_STATS_DAILY."short_code": "has" {
  source-arrowhead: "1" {shape: cf-one-required}
  target-arrowhead: "0..N" {shape: cf-many}
}
SHORT_URLSidbigintPKshort_codevarcharUNQlong_urltextuser_idbigintstatusvarcharexpires_attimestamptzcreated_attimestamptzupdated_attimestamptzURL_STATS_DAILYshort_codevarcharFKstat_datedatePKclick_countbigintunique_ip_countbiginttop_countryvarcharupdated_attimestamptz has10..N
SHORT_URLSidbigintPKshort_codevarcharUNQlong_urltextuser_idbigintstatusvarcharexpires_attimestamptzcreated_attimestamptzupdated_attimestamptzURL_STATS_DAILYshort_codevarcharFKstat_datedatePKclick_countbigintunique_ip_countbiginttop_countryvarcharupdated_attimestamptz has10..N
url-shortener — ER Diagram

Indexing Strategy

  • UNIQUE INDEX idx_short_urls_short_code cho lookup redirect.
  • INDEX idx_short_urls_user_created trên (user_id, created_at DESC) cho dashboard user.
  • PARTIAL INDEX idx_short_urls_active trên status='ACTIVE' để giảm scan.
  • INDEX idx_url_stats_daily_date trê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_urls bình thường, PostgreSQL tự route: hash(short_code) MOD 32 → đúng partition.

Tại sao chọn 32 partitions?

Số partitionData/partition/year (5.48TB total [C4])Đánh giá
8~685GBQuá lớn, vacuum chậm, index khó fit RAM
32~170GBVừa phải, vacuum nhanh, index fit RAM trên RDS r6g.large
64~85GBNhỏ 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 theo stat_date theo 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 prefix short_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, aggregate url_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)

ShortUrlService.java · ShortUrlService — đọc luồng xử lý
@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.
direction: down

Internet: "Internet" {
}
AWS_Edge: "AWS Edge" {
}
AWS_VPC: "AWS VPC" {
}
AWS_VPC.EKS: "EKS" {
  icon: ../../diagrams/icons/eks.svg
}
Internet.C: "Client/Browsers"
AWS_Edge.R53: "Route53" {
  icon: ../../diagrams/icons/route53.svg
}
AWS_Edge.CF: "CloudFront" {
  icon: ../../diagrams/icons/cloudfront.svg
}
AWS_Edge.WAF: "AWS WAF" {
  icon: ../../diagrams/icons/waf.svg
}
AWS_VPC.ALB: "Application Load Balancer" {
  icon: ../../diagrams/icons/load-balancer.svg
}
AWS_VPC.EKS.GW: "Gateway Pods"
AWS_VPC.EKS.US: "URL Service Pods"
AWS_VPC.EKS.RS: "Redirect Service Pods"
AWS_VPC.EKS.AS: "Analytics Service Pods"
AWS_VPC.REDIS: "ElastiCache Redis" {
  shape: cylinder
  icon: ../../diagrams/icons/redis.svg
}
AWS_VPC.RDS: "RDS PostgreSQL Multi-AZ" {
  shape: cylinder
  icon: ../../diagrams/icons/rds.svg
}
AWS_VPC.RR: "RDS Read Replicas" {
  shape: cylinder
  icon: ../../diagrams/icons/rds.svg
}
AWS_VPC.MSK: "Amazon MSK / Kafka" {
  shape: cylinder
  icon: ../../diagrams/icons/msk.svg
}
AWS_VPC.S3: "S3 Data Lake" {
  shape: cylinder
  icon: ../../diagrams/icons/s3.svg
}
AWS_VPC.CW: "CloudWatch" {
  icon: ../../diagrams/icons/cloudwatch.svg
}
AWS_VPC.AMG: "Managed Prometheus/Grafana"

Internet.C -> AWS_Edge.R53
AWS_Edge.R53 -> AWS_Edge.CF
AWS_Edge.CF -> AWS_Edge.WAF
AWS_Edge.WAF -> AWS_VPC.ALB
AWS_VPC.ALB -> AWS_VPC.EKS.GW
AWS_VPC.EKS.GW -> AWS_VPC.EKS.US
AWS_VPC.EKS.GW -> AWS_VPC.EKS.RS
AWS_VPC.EKS.US -> AWS_VPC.RDS
AWS_VPC.EKS.RS -> AWS_VPC.REDIS
AWS_VPC.EKS.RS -> AWS_VPC.RDS
AWS_VPC.EKS.RS -> AWS_VPC.MSK
AWS_VPC.EKS.AS -> AWS_VPC.MSK
AWS_VPC.EKS.AS -> AWS_VPC.RDS
AWS_VPC.EKS.AS -> AWS_VPC.S3
AWS_VPC.RDS -> AWS_VPC.RR
AWS_VPC.EKS.GW -> AWS_VPC.CW: "metrics/logs" {style.stroke-dash: 4}
AWS_VPC.EKS.US -> AWS_VPC.AMG: "metrics/logs" {style.stroke-dash: 4}
AWS_VPC.EKS.RS -> AWS_VPC.AMG: "metrics/logs" {style.stroke-dash: 4}
InternetAWS EdgeAWS VPCEKSClient/BrowsersRoute53CloudFrontAWS WAFApplication Load BalancerElastiCache RedisRDS PostgreSQL Multi-AZRDS Read ReplicasAmazon MSK / KafkaS3 Data LakeCloudWatchManaged Prometheus/GrafanaGateway PodsURL Service PodsRedirect Service PodsAnalytics Service Pods metrics/logsmetrics/logsmetrics/logs
InternetAWS EdgeAWS VPCEKSClient/BrowsersRoute53CloudFrontAWS WAFApplication Load BalancerElastiCache RedisRDS PostgreSQL Multi-AZRDS Read ReplicasAmazon MSK / KafkaS3 Data LakeCloudWatchManaged Prometheus/GrafanaGateway PodsURL Service PodsRedirect Service PodsAnalytics Service Pods metrics/logsmetrics/logsmetrics/logs
url-shortener — Kiến trúc triển khai AWS

Scaling Strategy

  • HPA theo CPU + custom metric (redirect_rps) cho redirect-service: target peak ~70K QPS [C2]. Giả sử mỗi pod xử lý ~5K RPS → cần ~14 pods peak, HPA range min=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 range min=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 Unavailable với Retry-After header, 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ómMetrics
Latencyp50/p95/p99 redirect latency, create latency
Trafficrequests per second, redirects per short code
Errors4xx/5xx rate, DB timeout rate, cache miss ratio
SaturationCPU/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ải 5xx) trong tổng redirect requests.
  • SLI create: p99 latency của POST /api/v1/urls response 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 > 100ms trong 5 phút.
  • Alert nếu 5xx > 1% hoặc cache 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.

Redirect — Redis miss và fallback PostgreSQLTrace minh họa · 42 ms
  1. 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.

  2. 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 đủ
Redirect — Redis miss và fallback PostgreSQL · ms từ mốc 0
Span / IDChaServiceBắt đầuThời lượngKết thúcTrạng thái
GET /abc123x → 301request—gateway0 ms42 ms42 msOK
Resolve short coderesolverequestredirect-service4 ms34 ms38 msOK
GET redirect cache — misscacheresolveredis6 ms2 ms8 msOK
SELECT mappingdatabaseresolvepostgres9 ms23 ms32 msOK
SET mapping với TTLpopulateresolveredis33 ms2 ms35 msOK
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

PhaseDurationDeliverables
Discovery & Requirements1 tuầnScope, SLA, API contract draft
Core URL + Redirect MVP2 tuầnCreate/redirect APIs, PostgreSQL + Redis
Analytics + Observability1.5 tuầnKafka pipeline, dashboards, alerts
Security + Hardening1 tuầnAuthZ, WAF rules, abuse protections
Performance + Production Readiness1.5 tuầnLoad test, chaos test, runbooks
Total~7 tuầnProduction 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

RiskImpactMitigation
Cache stampede khi hot link viralTăng latency đột biếnrequest coalescing + short TTL jitter
Abuse/spam linksReputation riskdomain blocklist + rate limits + moderation queue
DB hotspot trên short_codeThroughput giảmhash partition + read replicas + cache tuning
Analytics lag khi Kafka backlogStats 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)

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
EKS Control PlaneManaged1~$73$73Cố định
Redirect Service nodesc6g.xlarge (4 vCPU, 8GB)4-20 pods, cần ~4 nodes avg~$100/node$400HPA min=4, max=20 [C2] peak ~70K QPS
URL Service nodesc6g.large (2 vCPU, 4GB)2-6 pods, cần ~2 nodes avg~$62/node$124HPA min=2, max=6 [C1] peak ~1.7K QPS
Gateway nodesc6g.large2 nodes (HA)~$62/node$124Always-on, rate limiting
Analytics Service nodesc6g.large2-4 pods, ~2 nodes avg~$62/node$124VPA, consumer Kafka [C7]

Subtotal Compute: ~$845/tháng

Database

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
RDS PostgreSQL Primaryr6g.xlarge Multi-AZ (4 vCPU, 32GB)1~$580$580Write path, 15GB/day [C3]
RDS Read Replicar6g.large (2 vCPU, 16GB)1~$200$200Dashboard/stats queries
RDS Storage (gp3)500GB initial (grow ~15GB/day [C3])1~$0.116/GB$58Auto-scale, 5.48TB/yr [C4]

Subtotal Database: ~$838/tháng

Cache

ResourceSpec / SizingSố 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$200Gateway rate limiting, vài GB

Subtotal Cache: ~$600/tháng

Message Queue

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
Amazon MSKkafka.m5.large (3 brokers, Multi-AZ)3~$165/broker$4951.2B events/day [C7], retention 7 days
MSK Storage500GB per broker3~$0.10/GB$150Click events + replay buffer

Subtotal Message Queue: ~$645/tháng

Network / CDN

ResourceSpec / SizingSố 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$250Edge cache cho redirect 301
ALB1 ALB + LCU usage1~$22 base + ~$80 LCU$100Route vào EKS
NAT Gateway2 AZ2~$32/gateway + data$120Outbound traffic
Route53Hosted zone + queries1~$0.50 + queries$10DNS

Subtotal Network: ~$480/tháng

Storage

ResourceSpec / SizingSố 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)$18090 ngày hot, sau đó Glacier
S3 (Logs/Backups)~500GB1~$0.025/GB$13ELK ingest, DB backups

Subtotal Storage: ~$193/tháng

Monitoring / Logging

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
CloudWatchMetrics + logs + alarms1—$100Basic metrics + log groups
Managed Prometheus + GrafanaAMP + AMG1—$120Custom metrics, dashboards

Subtotal Monitoring: ~$220/tháng

17.2 Tổng hợp cost theo giai đoạn

Giai đoạnMonthly CostAnnual CostGhi chú
MVP (10% traffic, minimal replicas)~$2,800~$33,6001 RDS r6g.large, 1 Redis node, 2 redirect pods, MSK smallest
Growth (avg traffic — bảng 17.1)~$3,821~$45,852Full setup như 17.1, avg load
Peak / Scale (peak traffic, max HPA)~$6,500-8,000~$78,000-96,000HPA max out, RDS scale-up r6g.2xlarge, thêm Redis shards, CloudFront bandwidth tăng

17.3 Cost Breakdown theo category

CategoryUSD/tháng (Growth)% tổng cost
Compute (EKS)$84522%
Database (RDS)$83822%
Message Queue (MSK)$64517%
Cache (ElastiCache)$60016%
Network / CDN$48013%
Monitoring$2206%
Storage (S3)$1935%
Tổng~$3,821100%

📌 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

StrategyMô tảTiết kiệm ước tínhTrade-off
Reserved Instances (1 năm)Commit RDS + ElastiCache (always-on workload)30-40% cho DB+Cache → **$430-575/tháng**Lock-in 1 năm, khó đổi instance type
Savings Plans (Compute)Commit compute spend cho EKS nodes20-30% cho compute → **$170-250/tháng**Lock-in 1-3 năm
Spot InstancesDùng cho analytics-service nodes (fault-tolerant, stateless)60-70% cho analytics compute → **$75-87/tháng**Có thể bị interrupt, cần graceful shutdown
Right-sizing reviewQuarterly review CPU/memory utilization, downgrade over-provisioned nodes10-15% tổng compute → **$85-127/tháng**Cần monitoring data đủ lâu
S3 Lifecycle PoliciesClick events > 90 ngày → Glacier Deep Archive ($0.002/GB)90% storage cost cho cold data → **$150/tháng** sau 6 thángRestore time 12-48h cho Glacier
CloudFront cache optimizationTăng cache hit ratio từ 30-50% lên 60-70% (tune Cache-Control headers)Giảm origin bandwidth ~$50-100/thángStale content risk nếu TTL quá dài
VPC EndpointsThay NAT Gateway bằng VPC endpoints cho S3/DynamoDB/CloudWatchGiảm NAT data processing → ~$50-80/thángCần setup endpoint policies
MSK ServerlessChuyển từ provisioned MSK sang serverless (nếu traffic biến động lớn)Giảm 30% khi off-peak → **$100-200/tháng**Latency có thể cao hơn khi cold start
Log samplingSample debug logs 10%, giữ 100% error/warnGiảm CloudWatch ingest → ~$30-50/thángMấ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ángTraffic estimateInfra changesMonthly Cost
1-3 (MVP)10% design loadMinimal setup~$2,800
4-6 (Growth)30-50% design loadFull setup, HPA active~$3,200-3,800
7-9 (Scale)70-100% design loadRDS scale-up, thêm Redis shard~$4,500-5,500
10-12 (Peak)100-120% design loadHPA max, xem xét thêm read replica~$6,000-7,500
Năm thứ 2Nế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-shortener
    • service: redirect | url | analytics | gateway
    • environment: dev | staging | production
    • Dùng AWS Cost Explorer group by tag để phân bổ cost chính xác theo service.

On this page

1. 📋 Đề Bài (Problem Statement)2. 🔍 Requirement Gathering & Analysis2.1 Functional Requirements2.2 Non-Functional Requirements2.3 Capacity Estimation (Back-of-the-envelope)Bước 0: Quy ước đơn vị (để tránh nhầm)Bước 1: Inputs giả địnhBước 2: Tính write traffic (create short URL)Bước 3: Tính read traffic (redirect)Bước 4: Tính storage cho bảng URLBước 5: Tính bandwidth redirect mỗi ngàyBước 6: Redis cache memory estimateBước 7: So sánh nhanh 2 kịch bản để dễ kiểm chứng📊 Bảng tổng hợp Capacity Estimation3. ⚖️ Trade-offs3.1 Bảng tổng quan quyết định3.2 Decision #1: ID Generation (Random Hash vs Snowflake + Base62)Cách 1: Random Hash + Collision Check hoạt động thế nào?Cách 2: Snowflake ID + Base62 hoạt động thế nào?Pseudo-code so sánh nhanhKết luận cho bài toán này3.3 Decision #2: Redirect Semantics (301 vs 302)Context kỹ thuậtCách 301 và 302 khác nhau trong thực tếVí dụ end-to-end cụ thểRủi ro khi dùng 301 và cách giảm rủi roRule vận hành đề xuất3.4 Decision #3: Primary Data Store (PostgreSQL vs Cassandra)Access patterns cần supportVì sao chọn PostgreSQL cho v1Flow ghi/đọc điển hình với PostgreSQLVí dụ SQL cho tính nhất quán aliasĐiểm yếu của PostgreSQL và kế hoạch giảm rủi roKhi nào nên cân nhắc Cassandra3.5 Decision #4: Cache Strategy (Cache-aside vs Write-through)Context kỹ thuậtFlow cache-aside chi tiếtVí dụ định lượng lợi íchVì sao không chọn write-through làm mặc địnhTTL StrategyFailure scenarios và mitigation3.6 Decision #5: Analytics Ingestion (Sync write DB vs Kafka async)Context kỹ thuậtSo sánh trực tiếp 2 cáchFlow Kafka async chi tiếtVí dụ event schemaDuplicate và consistency xử lý thế nàoFailure scenarios và mitigationSLA tách biệt4. 🧩 Defining Entities / Components5. 🔗 Client-Server Connection6. 🔄 System / App FlowFlow 1: Tạo short URLFlow 2: Redirect short URLError handling & Edge cases7. 📡 API ModelingEndpoint DefinitionsRequest/Response ExamplesError Response FormatPagination / Filtering / SortingAPI Versioning8. 🗄️ Data ModelingDatabase Schema (PostgreSQL)ER DiagramIndexing StrategyPartitioning / Sharding StrategyHash Partition cho short_urlsTại sao chọn 32 partitions?Range Partition cho url_stats_dailyKhi nào cần Sharding (nhiều RDS cluster)?Data Retention Policy9. ⚙️ Manager Classes / ServicesService Decomposition (Spring Boot microservices)Core Service Classes & ResponsibilitiesBackend Code Example (Java / Spring Boot)Frontend Code Example (React + TypeScript)Service Communication Patterns10. 🏛️ Architecture DesignScaling StrategyCaching StrategyLoad Balancing / Gateway / MeshResilience Patterns11. 🧪 Testing Strategy12. 🔒 Security13. 📊 Monitoring & LoggingKey MetricsLogging StrategySLI / SLO / Error Budget (SRE)Alerting & Incident Response🔎 Đọc trace của một cache miss14. 🔧 Maintenance15. 🚀 Deployment Plans16. ⏱️ Effort EstimationPhase Breakdown & TimelineTeam CompositionRisk AssessmentDependencies & Blockers17. 💰 Cost Estimation & Optimization17.1 Chi phí hàng tháng theo từng resource (AWS On-Demand, region ap-southeast-1)Compute (EKS)DatabaseCacheMessage QueueNetwork / CDNStorageMonitoring / Logging17.2 Tổng hợp cost theo giai đoạn17.3 Cost Breakdown theo category17.4 Cost Optimization Strategies17.5 Cost Projection (12 tháng, growth rate ~20%/quý)17.6 Cost Alerts & Governance