System Design Practice

Paste Bin - System Design

Thiết kế hệ thống Paste Bin tương tự Pastebin.com / GitHub Gist, cho phép người dùng lưu trữ và chia sẻ đoạn text/code qua một URL ngắn duy nhất.

1. 📋 Đề Bài (Problem Statement)

  • Thiết kế hệ thống Paste Bin tương tự Pastebin.com / GitHub Gist, cho phép người dùng lưu trữ và chia sẻ đoạn text/code qua một URL ngắn duy nhất.
  • Hệ thống phải hỗ trợ paste lớn (lên đến vài MB), syntax highlighting, và các chế độ truy cập (public, unlisted, private).
  • Scope chính (in scope):
    • Tạo paste mới (với nội dung text/code)
    • Đọc paste qua unique URL
    • Syntax highlighting cho nhiều ngôn ngữ
    • Chế độ truy cập: public, unlisted, private
    • Thời gian hết hạn (expiration)
    • Basic analytics (view count)
  • Scope ngoài bài (out of scope): real-time collaborative editing, version history/diff, file attachments (binary), comment system, fork/clone.
  • Mục tiêu business: cung cấp nền tảng chia sẻ code/text nhanh chóng, an toàn, hỗ trợ developer workflow và troubleshooting.

2. 🔍 Requirement Gathering & Analysis

2.1 Functional Requirements

PriorityRequirementMô tả
MUST-HAVECreate pasteUser nhập nội dung text/code, chọn ngôn ngữ, nhận về unique URL
MUST-HAVERead pasteTruy cập URL để xem nội dung paste với syntax highlighting
MUST-HAVEExpirationPaste tự hết hạn theo thời gian (10 min, 1 hour, 1 day, 1 week, 1 month, never)
MUST-HAVEAccess control3 chế độ: public (searchable), unlisted (chỉ ai có link), private (chỉ owner)
MUST-HAVERaw contentEndpoint trả về raw text (không HTML) để dễ curl/wget
NICE-TO-HAVESyntax highlightingHighlight code theo ngôn ngữ được chọn (client-side rendering)
NICE-TO-HAVEUser managementĐăng ký/đăng nhập để quản lý pastes, xem history
NICE-TO-HAVEDelete pasteOwner có thể xóa paste trước khi hết hạn
NICE-TO-HAVEBurn after readPaste tự hủy sau lần đọc đầu tiên

2.2 Non-Functional Requirements

  • Performance: Read paste p95 < 100ms (cache hit), create paste p95 < 300ms (bao gồm upload content lên S3).
  • Scalability: Hỗ trợ peak ~1,500 read QPS và ~300 write QPS.
  • Availability: SLA 99.99% cho read path, 99.9% cho create/manage API.
  • Consistency: Read-after-write consistency cho paste mới tạo (<2s). View count chấp nhận eventual consistency.
  • Security: JWT/OAuth2 cho user APIs, TLS end-to-end, content scanning chống abuse (malware links, PII leak).
  • Cost: Ước lượng ~$2,500-4,000/tháng cho MVP (EKS cluster ~$800, RDS Multi-AZ ~$500, ElastiCache ~$300, S3 ~$200, CloudFront ~$300, MSK ~$400, monitoring ~$200). Scale lên peak traffic có thể đạt $6,000-8,000/tháng.
  • Observability: Golden Signals (latency, error, traffic, saturation), distributed tracing cho read/write paths.

2.3 Capacity Estimation (Back-of-the-envelope)

Bước 0: Quy ước đơn vị

  • 1 day = 86,400 seconds
  • 1M = 1,000,000, 1B = 1,000,000,000
  • Dùng đơn vị thập phân: 1KB = 1,000B, 1GB = 1,000,000,000B

Bước 1: Inputs giả định

InputGiá trịTại sao chọn
Daily Active Visitors (DAV)50M visitors/dayBao gồm cả anonymous readers (click link từ chat, forum, StackOverflow) — chiếm phần lớn traffic
DAU (registered)10M users/daySubset của DAV, chỉ tính logged-in users
New pastes/day5M pastes/day~50% DAU tạo 1 paste/ngày (chỉ registered + anonymous guest)
Avg reads per visitor/day0.5 readsĐa số anonymous visitor chỉ xem 1 paste rồi rời đi; registered user xem nhiều hơn → trung bình 0.5
Read:Write ratio~5:1Cross-check: 25M reads / 5M writes — phù hợp hệ thống read-heavy vừa phải
Avg paste content size5KBCode snippets, logs, configs trung bình
Metadata per paste300Bid, short_code, title, language, visibility, user_id, timestamps, s3_key
Avg read response payload8KBContent + HTML wrapper + headers

📌 5KB là trung bình; hệ thống hỗ trợ paste lên đến 10MB nhưng đa số paste < 10KB.

Bước 2: Tính write traffic (create paste)

  • Công thức: write_qps_avg = new_pastes_per_day / 86,400
  • Thay số: 5,000,000 / 86,400 = 57.87
  • Kết quả: write QPS trung bình ~58
  • Peak factor x5: 58 * 5 = 290
  • Kết quả: peak write QPS ~290

Bước 3: Tính read traffic (view paste)

  • Công thức: daily_views = DAV * avg_reads_per_visitor
  • Thay số: 50,000,000 * 0.5 = 25,000,000 views/day
  • Cross-check: Read:Write ratio = 25M / 5M = 5:1 ✅ (phù hợp hệ thống read-heavy vừa phải)
  • Công thức: read_qps_avg = daily_views / 86,400
  • Thay số: 25,000,000 / 86,400 = 289.35
  • Kết quả: read QPS trung bình ~289
  • Peak factor x5: 289 * 5 = 1,445
  • Kết quả: peak read QPS ~1,445

Bước 4: Tính content storage (S3)

  • Daily raw content: 5,000,000 * 5KB = 25,000,000KB = 25GB/day
  • Yearly raw content: 25GB * 365 = 9,125GB ≈ 9.13TB/year
  • 5-year raw content: 9.13TB * 5 = 45.63TB
  • Tuy nhiên, nhiều paste sẽ expire trước 5 năm. Giả sử ~60% paste expire trong 30 ngày:
    • Active storage sau 5 năm ước lượng: 45.63TB * 0.4 = 18.25TB (active) + rolling expired data

📌 Content được gzip compress trước khi lưu S3, ratio trung bình ~3:1 cho text → actual storage ~15TB sau 5 năm.

Bước 5: Tính metadata storage (PostgreSQL)

  • Daily metadata: 5,000,000 * 300B = 1,500,000,000B = 1.5GB/day
  • Yearly metadata: 1.5GB * 365 = 547.5GB/year
  • 5-year metadata: 547.5GB * 5 = 2,737.5GB ≈ 2.74TB
  • Cộng index + replication (3x): ~8.2TB

Bước 6: Tính bandwidth

  • Read bandwidth/day: 25,000,000 * 8KB = 200,000,000KB = 200GB/day
  • Write bandwidth/day: 5,000,000 * 5KB = 25GB/day
  • Total bandwidth/day: 225GB/day

Bước 7: Redis cache memory estimate

  • Hot pastes (top 5% được truy cập nhiều): 5,000,000 * 0.05 * 5KB = 1,250,000KB = 1.25GB active set mỗi ngày
  • Giả sử cache window 7 ngày hot pastes: 1.25GB * 7 = 8.75GB
  • Cộng Redis overhead + replication (2x): ~18GB

Bước 8: So sánh kịch bản

Kịch bảnAvg paste sizeDaily content storageDaily metadataPeak read QPS
Base (small pastes)2KB10GB/day1.5GB/day~1,445
Conservative (đang dùng)5KB25GB/day1.5GB/day~1,445
Large pastes scenario10KB50GB/day1.5GB/day~1,445

📌 Content size ảnh hưởng chủ yếu đến storage và bandwidth, không ảnh hưởng nhiều đến QPS.

Bước 9: 📊 Bảng tổng hợp Capacity Estimation

IDMetricAvgPeak
C1Write QPS~58~290
C2Read QPS~289~1,445
C3Content storage/year (S3)~9.13TB—
C4Metadata storage/year (PostgreSQL)~547.5GB—
C5Read bandwidth/day200GB—
C6Redis cache memory~18GB—
C7Daily new pastes5M—

📌 Nguyên tắc cốt lõi: Mỗi metric trên trực tiếp justify ít nhất một quyết định thiết kế ở §3–§16. Ngược lại, mỗi quyết định sizing/scaling phải truy nguồn về một metric trong bảng này.

3. ⚖️ Trade-offs

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

DecisionOption AOption BChọnLý do chính
Content storagePostgreSQL (inline)S3 (object store)BContent lớn (lên đến 10MB), tách biệt metadata vs blob
ID generationUUID v4Snowflake + Base62BConsistent với URL shortener, sortable, compact URL
Syntax highlightingServer-side renderingClient-side (Prism.js)BGiảm CPU server, flexible, không block response
Cache layerWrite-throughCache-aside RedisBPhù hợp read-heavy, tránh cache pollution từ one-time pastes
Content compressionKhông compressgzip trước khi lưu S3BGiảm 60-70% storage cost, text compress rất tốt
Expiration cleanupSync delete on readAsync background jobBKhông ảnh hưởng read latency, batch delete hiệu quả

3.2 Decision #1: Content Storage (PostgreSQL inline vs S3)

Tiêu chíPostgreSQL inlineS3 object store
Max content sizeBị giới hạn bởi row size (1GB TOAST nhưng thực tế ~10MB hiệu quả)Gần như không giới hạn (5TB/object)
Read latencyNhanh cho small content (single query)Thêm 1 hop đến S3 (~20-50ms)
Storage costĐắt (EBS-backed RDS)Rẻ hơn ~10x (S3 Standard)
Backup/restoreChậm hơn khi DB lớnContent tách riêng, DB backup nhẹ hơn
CDN integrationKhó cache từ DB trực tiếpDễ dàng serve qua CloudFront + S3 origin
Query complexitySimple JOINCần 2 calls (metadata DB + content S3)

Option A: PostgreSQL inline hoạt động thế nào?

  1. User submit paste content.
  2. Service INSERT cả metadata + content vào cùng 1 row (hoặc linked table).
  3. PostgreSQL tự động TOAST nếu content > 2KB (compress + out-of-line storage).
  4. Read: single SELECT query trả về metadata + content.

Ví dụ:

  1. User paste 8KB code Python.
  2. INSERT INTO pastes (id, short_code, title, language, content, ...) VALUES (...).
  3. PostgreSQL TOAST compress content column → lưu ngoài main table page.
  4. Read: SELECT * FROM pastes WHERE short_code = 'abc123' → trả cả content trong 1 query.
  5. Vấn đề: DB phình nhanh (25GB content/ngày), backup chậm, DB connection bị hold lâu khi đọc large paste.

Option B: S3 object store hoạt động thế nào?

  1. User submit paste content.
  2. Service upload content lên S3 (key = pastes/{short_code}).
  3. Lưu metadata + s3_key vào PostgreSQL.
  4. Read: query metadata từ DB → fetch content từ S3 (hoặc CloudFront cache).

Ví dụ:

  1. User paste 8KB code Python.
  2. Service gzip compress: 8KB → ~2.5KB.
  3. Upload S3: PUT s3://paste-content/pastes/L8E3B1JoxM (2.5KB).
  4. Insert DB: INSERT INTO paste_metadata (id, short_code, s3_key, content_size, ...) VALUES (...) (~300B row).
  5. Read flow:
    • Client GET /p/L8E3B1JoxM
    • Check Redis cache → miss
    • Query DB: metadata (1ms)
    • Fetch S3: content (~20ms, hoặc CloudFront hit ~5ms)
    • Response: metadata + content (~25ms total)
  6. Ưu điểm: DB chỉ lưu metadata (1.5GB/day vs 26.5GB/day), backup nhanh, S3 rẻ và bền.

Pseudo-code so sánh

PostgreSQL inline:
content = request.body
record = { shortCode, title, language, content, ... }
db.insert("pastes", record)       // single insert, DB grows fast
return db.select("pastes", shortCode)  // single query

S3 + PostgreSQL:
content = gzip(request.body)
s3.put("pastes/" + shortCode, content)        // upload to S3
metadata = { shortCode, title, language, s3Key, ... }
db.insert("paste_metadata", metadata)         // lightweight insert
// read:
meta = db.select("paste_metadata", shortCode) // fast query
content = s3.get(meta.s3Key)                  // separate fetch
return { meta, gunzip(content) }

Kết luận

  • Context: paste content lớn (avg 5KB, max 10MB), storage growth 25GB/day, cần CDN integration.
  • Chọn S3 vì: tách biệt hot metadata (DB nhỏ, query nhanh) và cold content (S3 rẻ, scalable). CloudFront có thể cache S3 objects trực tiếp.
  • Mitigation cho thêm 1 hop: cache popular pastes trong Redis (content + metadata), serve từ CloudFront cho raw content.

3.3 Decision #2: Syntax Highlighting (Server-side vs Client-side)

Tiêu chíServer-side (Pygments/highlight.js SSR)Client-side (Prism.js/highlight.js)
Server CPU costCao — mỗi request cần render HTMLThấp — server chỉ trả raw text + language hint
Cache efficiencyPhải cache rendered HTML (lớn hơn raw)Cache raw content (nhỏ hơn), client render
Time to First ByteChậm hơn (render trước khi trả)Nhanh hơn (trả raw ngay)
Language support updateCần deploy lại serverUpdate JS bundle, không cần deploy backend
SEOHTML sẵn sàng cho crawlersCần SSR fallback cho SEO (nếu cần)

Kết luận

  • Chọn client-side (Prism.js) vì: giảm CPU server, cache hiệu quả hơn (raw text nhỏ hơn rendered HTML), và thêm ngôn ngữ mới chỉ cần update frontend bundle.
  • Mitigation: server trả language field trong metadata để client biết dùng grammar nào. Fallback: nếu client không hỗ trợ language → hiển thị plain text.

3.4 Decision #3: Expiration Cleanup Strategy

Tiêu chíSync delete on readAsync background job
Read latency impactThêm delete operation trên critical pathKhông ảnh hưởng read
Cleanup completenessChỉ cleanup khi có accessCleanup mọi expired paste theo schedule
Storage reclaim speedChậm (chỉ khi access)Nhanh (batch job chạy định kỳ)
Implementation complexityĐơn giản (check TTL trong read)Cần scheduled job + S3 lifecycle

Kết luận

  • Chọn async background job kết hợp với:
    • S3 Lifecycle Policy: tự động delete objects sau TTL (dựa trên object tags).
    • DB cleanup job: chạy mỗi 15 phút, batch delete expired metadata (soft delete → hard delete sau 7 ngày).
    • Read-time check: vẫn check expire_at khi read, trả 410 Gone nếu expired (lazy validation).
  • Mitigation: S3 lifecycle là hàng rào cuối cùng đảm bảo không tốn storage cho expired content.

4. 🧩 Defining Entities / Components

direction: right

Edge: "Edge Layer" {
}
Application: "Application Layer" {
}
Data: "Data Layer" {
}
Async: "Async Layer" {
}
Edge.CDN: "CloudFront CDN" {
  icon: ../../diagrams/icons/cloudfront.svg
}
Edge.WAF: "AWS WAF" {
  icon: ../../diagrams/icons/waf.svg
}
Application.GW: "API Gateway"
Application.PS: "Paste Service"
Application.RS: "Read Service"
Application.US: "User Service"
Application.CS: "Cleanup Service"
Data.DB: "PostgreSQL" {
  shape: cylinder
  icon: ../../diagrams/icons/postgres.svg
}
Data.CACHE: "Redis" {
  shape: cylinder
  icon: ../../diagrams/icons/redis.svg
}
Data.S3: "S3 Content Store" {
  shape: cylinder
  icon: ../../diagrams/icons/s3.svg
}
Async.KAFKA: "Kafka"
Async.ANALYTICS: "Analytics Service"

Edge.CDN -> Edge.WAF
Edge.WAF -> Application.GW
Application.GW -> Application.PS
Application.GW -> Application.RS
Application.GW -> Application.US
Application.PS -> Data.DB
Application.PS -> Data.S3
Application.RS -> Data.CACHE
Application.RS -> Data.DB
Application.RS -> Data.S3
Application.RS -> Async.KAFKA
Application.CS -> Data.DB
Application.CS -> Data.S3
Async.KAFKA -> Async.ANALYTICS
Async.ANALYTICS -> Data.DB
Edge LayerApplication LayerData LayerAsync LayerCloudFront CDNAWS WAFAPI GatewayPaste ServiceRead ServiceUser ServiceCleanup ServicePostgreSQLRedisS3 Content StoreKafkaAnalytics Service
Edge LayerApplication LayerData LayerAsync LayerCloudFront CDNAWS WAFAPI GatewayPaste ServiceRead ServiceUser ServiceCleanup ServicePostgreSQLRedisS3 Content StoreKafkaAnalytics Service
paste-bin — Thành phần hệ thống
ComponentVai trò
CloudFront CDNCache raw content, giảm latency cho users toàn cầu
AWS WAFChặn DDoS, rate limit, content filtering
API GatewayRouting, authentication, rate limiting, request validation
Paste ServiceXử lý tạo paste mới: validate, compress, upload S3, lưu metadata
Read ServiceXử lý đọc paste: check cache → DB metadata → S3 content
User ServiceĐăng ký, đăng nhập, quản lý user profile và paste history
Cleanup ServiceBackground job xóa expired pastes (DB metadata + S3 objects)
PostgreSQLLưu paste metadata, user data, index cho search
RedisCache hot paste metadata + content, session cache
S3Lưu paste content (gzip compressed), lifecycle policy cho auto-expiry
KafkaEvent stream cho analytics (view events, create events)
Analytics ServiceConsume events từ Kafka, aggregate view counts, update DB
Prometheus + GrafanaMetrics collection và dashboards
ELK StackCentralized logging và search

5. 🔗 Client-Server Connection

  • Protocol:

    • REST (HTTPS) cho tất cả CRUD operations (create, read, delete paste).
    • REST cho raw content endpoint (GET /raw/{shortCode} trả text/plain).
    • WebSocket: không cần (không có real-time features trong scope).
  • Authentication:

    • JWT Bearer token cho authenticated endpoints (create paste with user, delete, list my pastes).
    • Anonymous access cho: tạo paste không cần login (guest paste), đọc public/unlisted paste.
    • Private paste: yêu cầu JWT + owner check.
  • Connection patterns:

    • Request-Response: tất cả client interactions.
    • Async event publishing: Read Service → Kafka (view event) sau khi trả response.
  • Rate limiting & throttling:

    RoleCreate limitRead limitThuật toán
    Anonymous10 pastes/hour, max 64KB/paste60 reads/minToken bucket
    Authenticated (free)50 pastes/hour, max 1MB/paste300 reads/minToken bucket
    Authenticated (pro)500 pastes/hour, max 10MB/paste3000 reads/minToken bucket
  • Idempotency:

    • POST /api/v1/pastes hỗ trợ Idempotency-Key header để tránh duplicate paste khi client retry.
    • Server lưu idempotency key trong Redis (TTL 24h), trả về kết quả cũ nếu key đã tồn tại.

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: Create Paste

Luồng dưới đây đi từ trên xuống; mũi tên nét đứt là response. Publish PasteCreatedEvent là async, không chờ consumer xử lý trước khi trả 201 Created.

# viewport-height: 130vh
shape: sequence_diagram
U: "User"
GW: "API Gateway"
PS: "Paste Service"
IDG: "ID Generator"
S3: "S3" {
  icon: ../../diagrams/icons/s3.svg
}
DB: "PostgreSQL" {
  icon: ../../diagrams/icons/postgres.svg
}
CACHE: "Redis" {
  icon: ../../diagrams/icons/redis.svg
}
K: "Kafka"

U -> GW: "POST /api/v1/pastes {content,\nlanguage, visibility, expireIn}"
GW -> GW: "Validate JWT (if present), rate\nlimit check"
GW -> PS: "Forward request"

PS -> PS: "Validate input (size, content\ntype)"
PS -> IDG: "Generate Snowflake ID"
IDG -> PS: "snowflake_id" {style.stroke-dash: 4}

PS -> PS: "Base62 encode → short_code"
PS -> PS: "gzip compress content"

PS -> S3: "PUT pastes/{short_code}\n(compressed content)"
S3 -> PS: "200 OK" {style.stroke-dash: 4}

PS -> DB: "INSERT paste_metadata (short_code,\nlanguage, visibility, expire_at,\ns3_key, user_id)"
DB -> PS: "Created" {style.stroke-dash: 4}

PS -> CACHE: "SET paste:{short_code} (metadata +\ncontent, TTL=1h)"
CACHE -> PS: "OK" {style.stroke-dash: 4}

PS -> K: "Publish PasteCreatedEvent (async)"

PS -> GW: "201 Created {shortCode, pasteUrl,\nrawUrl, expireAt}" {style.stroke-dash: 4}
GW -> U: "201 Created" {style.stroke-dash: 4}
UserAPI GatewayPaste ServiceID GeneratorS3PostgreSQLRedisKafka POST /api/v1/pastes {content,language, visibility, expireIn}Validate JWT (if present), ratelimit checkForward requestValidate input (size, contenttype)Generate Snowflake ID snowflake_idBase62 encode → short_codegzip compress contentPUT pastes/{short_code}(compressed content)200 OKINSERT paste_metadata (short_code,language, visibility, expire_at,s3_key, user_id)CreatedSET paste:{short_code} (metadata +content, TTL=1h)OKPublish PasteCreatedEvent (async)201 Created {shortCode, pasteUrl,rawUrl, expireAt}201 Created
UserAPI GatewayPaste ServiceID GeneratorS3PostgreSQLRedisKafka POST /api/v1/pastes {content,language, visibility, expireIn}Validate JWT (if present), ratelimit checkForward requestValidate input (size, contenttype)Generate Snowflake ID snowflake_idBase62 encode → short_codegzip compress contentPUT pastes/{short_code}(compressed content)200 OKINSERT paste_metadata (short_code,language, visibility, expire_at,s3_key, user_id)CreatedSET paste:{short_code} (metadata +content, TTL=1h)OKPublish PasteCreatedEvent (async)201 Created {shortCode, pasteUrl,rawUrl, expireAt}201 Created
Create Paste — lưu content và metadata

Flow 2: Read Paste

# viewport-height: 180vh
shape: sequence_diagram
U: "User"
CDN: "CloudFront" {
  icon: ../../diagrams/icons/cloudfront.svg
}
GW: "API Gateway"
RS: "Read Service"
CACHE: "Redis" {
  icon: ../../diagrams/icons/redis.svg
}
DB: "PostgreSQL" {
  icon: ../../diagrams/icons/postgres.svg
}
S3: "S3" {
  icon: ../../diagrams/icons/s3.svg
}
K: "Kafka"

U -> CDN: "GET /p/{shortCode}"
CDN -> CDN: "Check cache"

group_1: "alt — chỉ chọn một nhánh" {
  group_2: "if: CDN cache hit" {
    style: {
      stroke-dash: 4
    }
    CDN -> U: "200 OK (cached HTML)" {style.stroke-dash: 4}
  }
  group_3: "else: CDN cache miss" {
    style: {
      stroke-dash: 4
    }
    CDN -> GW: "Forward request"
    GW -> RS: "GET /p/{shortCode}"

    RS -> CACHE: "GET paste:{shortCode}"
    group_4: "alt — chỉ chọn một nhánh" {
      group_5: "if: Cache hit" {
        style: {
          stroke-dash: 4
        }
        CACHE -> RS: "metadata + content" {style.stroke-dash: 4}
      }
      group_6: "else: Cache miss" {
        style: {
          stroke-dash: 4
        }
        RS -> DB: "SELECT * FROM paste_metadata WHERE\nshort_code = ?"
        DB -> RS: "metadata" {style.stroke-dash: 4}

        group_7: "alt — chỉ chọn một nhánh" {
          group_8: "if: Paste not found" {
            style: {
              stroke-dash: 4
            }
            RS -> GW: "404 Not Found" {style.stroke-dash: 4}
            GW -> CDN: "404" {style.stroke-dash: 4}
            CDN -> U: "404 Not Found" {style.stroke-dash: 4}
          }
          group_9: "else: Paste expired" {
            style: {
              stroke-dash: 4
            }
            RS -> GW: "410 Gone" {style.stroke-dash: 4}
            GW -> CDN: "410" {style.stroke-dash: 4}
            CDN -> U: "410 Gone" {style.stroke-dash: 4}
          }
          group_10: "else: Paste found" {
            style: {
              stroke-dash: 4
            }
            RS -> RS: "Check visibility (private →\nrequire auth)"
            RS -> S3: "GET pastes/{short_code}"
            S3 -> RS: "compressed content" {style.stroke-dash: 4}
            RS -> RS: "gunzip decompress"
            RS -> CACHE: "SET paste:{shortCode} (TTL=1h)"
          }
        }
      }
    }

    RS -> K: "Publish ViewEvent (async,\nfire-and-forget)"
    RS -> GW: "200 OK {metadata, content,\nlanguage}" {style.stroke-dash: 4}
    GW -> CDN: "200 OK" {style.stroke-dash: 4}
    CDN -> CDN: "Cache response (TTL=5min for\nunlisted)"
    CDN -> U: "200 OK" {style.stroke-dash: 4}
  }
}
UserCloudFrontAPI GatewayRead ServiceRedisPostgreSQLS3Kafkaalt — chỉ chọn một nhánhif: CDN cache hitelse: CDN cache missalt — chỉ chọn một nhánhif: Cache hitelse: Cache missalt — chỉ chọn một nhánhif: Paste not foundelse: Paste expiredelse: Paste found GET /p/{shortCode}Check cache 200 OK (cached HTML)Forward requestGET /p/{shortCode}GET paste:{shortCode}metadata + contentSELECT * FROM paste_metadata WHEREshort_code = ?metadata404 Not Found404404 Not Found410 Gone410410 GoneCheck visibility (private →require auth)GET pastes/{short_code}compressed contentgunzip decompressSET paste:{shortCode} (TTL=1h)Publish ViewEvent (async,fire-and-forget)200 OK {metadata, content,language}200 OKCache response (TTL=5min forunlisted)200 OK
UserCloudFrontAPI GatewayRead ServiceRedisPostgreSQLS3Kafkaalt — chỉ chọn một nhánhif: CDN cache hitelse: CDN cache missalt — chỉ chọn một nhánhif: Cache hitelse: Cache missalt — chỉ chọn một nhánhif: Paste not foundelse: Paste expiredelse: Paste found GET /p/{shortCode}Check cache 200 OK (cached HTML)Forward requestGET /p/{shortCode}GET paste:{shortCode}metadata + contentSELECT * FROM paste_metadata WHEREshort_code = ?metadata404 Not Found404404 Not Found410 Gone410410 GoneCheck visibility (private →require auth)GET pastes/{short_code}compressed contentgunzip decompressSET paste:{shortCode} (TTL=1h)Publish ViewEvent (async,fire-and-forget)200 OK {metadata, content,language}200 OKCache response (TTL=5min forunlisted)200 OK
paste-bin — Flow 2: Read Paste

Flow 3: Burn After Read

Read Service lấy content, đánh dấu paste đã burned rồi xóa object và cache trước khi trả response. Lần đọc tiếp theo nhận 410 Gone.

# viewport-height: 100vh
shape: sequence_diagram
U: "User"
GW: "API Gateway"
RS: "Read Service"
DB: "PostgreSQL" {
  icon: ../../diagrams/icons/postgres.svg
}
S3: "S3" {
  icon: ../../diagrams/icons/s3.svg
}
CACHE: "Redis" {
  icon: ../../diagrams/icons/redis.svg
}

U -> GW: "GET /p/{shortCode}"
GW -> RS: "Forward"

RS -> DB: "SELECT * FROM paste_metadata WHERE\nshort_code = ? FOR UPDATE"
DB -> RS: "metadata (burn_after_read = true,\nread_count = 0)" {style.stroke-dash: 4}

RS -> S3: "GET pastes/{short_code}"
S3 -> RS: "content" {style.stroke-dash: 4}

RS -> DB: "UPDATE paste_metadata SET status =\n'BURNED', read_count = 1"
RS -> S3: "DELETE pastes/{short_code}"
RS -> CACHE: "DEL paste:{shortCode}"

RS -> GW: "200 OK {content, burned: true}" {style.stroke-dash: 4}
GW -> U: "200 OK (lần truy cập duy nhất)" {style.stroke-dash: 4}

U."Lần truy cập sau → 410 Gone"
UserAPI GatewayRead ServicePostgreSQLS3Redis GET /p/{shortCode}ForwardSELECT * FROM paste_metadata WHEREshort_code = ? FOR UPDATE metadata (burn_after_read = true,read_count = 0)GET pastes/{short_code}contentUPDATE paste_metadata SET status ='BURNED', read_count = 1DELETE pastes/{short_code}DEL paste:{shortCode}200 OK {content, burned: true}200 OK (lần truy cập duy nhất)Lần truy cập sau → 410 Gone
UserAPI GatewayRead ServicePostgreSQLS3Redis GET /p/{shortCode}ForwardSELECT * FROM paste_metadata WHEREshort_code = ? FOR UPDATE metadata (burn_after_read = true,read_count = 0)GET pastes/{short_code}contentUPDATE paste_metadata SET status ='BURNED', read_count = 1DELETE pastes/{short_code}DEL paste:{shortCode}200 OK {content, burned: true}200 OK (lần truy cập duy nhất)Lần truy cập sau → 410 Gone
Burn After Read — đọc một lần rồi xóa

Error handling & Edge cases

Error caseHTTP StatusBehavior
Paste not found404 Not FoundTrả error response chuẩn
Paste expired410 GoneTrả thông báo paste đã hết hạn
Paste burned (đã đọc)410 GoneTrả thông báo paste đã bị xóa
Private paste, no auth401 UnauthorizedYêu cầu đăng nhập
Private paste, wrong user403 ForbiddenKhông có quyền truy cập
Content too large413 Payload Too LargeReject paste > size limit theo plan
Rate limit exceeded429 Too Many RequestsTrả Retry-After header
Malformed request400 Bad RequestValidation error details
S3 down503 (degraded)Serve từ Redis cache nếu có, nếu không → 503 với Retry-After
Redis down200 (degraded)Fallback đọc trực tiếp từ DB + S3, latency tăng

7. 📡 API Modeling

Endpoint Definitions

MethodPathAuthMô tả
POST/api/v1/pastesOptional (guest hoặc authenticated)Tạo paste mới
GET/api/v1/pastes/{shortCode}Conditional (private cần auth)Lấy paste metadata + content
GET/api/v1/pastes/{shortCode}/rawConditionalLấy raw content (text/plain)
DELETE/api/v1/pastes/{shortCode}Required (owner only)Xóa paste
GET/api/v1/users/me/pastesRequiredLiệt kê pastes của user
GET/api/v1/pastes/publicNoneLiệt kê public pastes (recent)

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ụ.

Create Paste

POST /api/v1/pastes
201 CreatedPOST → 201

Request

POST/api/v1/pastes
Headers
TênGiá trị
Hostapi.pastebin.example.com
Content-Typeapplication/json
AuthorizationBearer eyJhbGciOiJSUzI1NiIs...
Idempotency-Key550e8400-e29b-41d4-a716-446655440000
{
  "title": "Quick sort implementation",
  "content": "def quick_sort(arr):\n    if len(arr) <= 1:\n        return arr\n    pivot = arr[len(arr) // 2]\n    left = [x for x in arr if x < pivot]\n    middle = [x for x in arr if x == pivot]\n    right = [x for x in arr if x > pivot]\n    return quick_sort(left) + middle + quick_sort(right)",
  "language": "python",
  "visibility": "unlisted",
  "expireIn": "7d",
  "burnAfterRead": false
}

Response

201Created
Headers
TênGiá trị
Content-Typeapplication/json
Locationhttps://pastebin.example.com/p/K9xM3bR2w
{
  "id": "290184726153420800",
  "shortCode": "K9xM3bR2w",
  "title": "Quick sort implementation",
  "language": "python",
  "visibility": "unlisted",
  "pasteUrl": "https://pastebin.example.com/p/K9xM3bR2w",
  "rawUrl": "https://pastebin.example.com/api/v1/pastes/K9xM3bR2w/raw",
  "contentSize": 312,
  "createdAt": "2026-02-28T10:30:00Z",
  "expireAt": "2026-03-07T10:30:00Z",
  "burnAfterRead": false,
  "viewCount": 0
}

Read Paste

GET /api/v1/pastes/K9xM3bR2w
200 OKGET → 200

Request

GET/api/v1/pastes/K9xM3bR2w
Headers
TênGiá trị
Hostapi.pastebin.example.com
Acceptapplication/json

Response

200OK
Headers
TênGiá trị
Content-Typeapplication/json
Cache-Controlpublic, max-age=300
{
  "id": "290184726153420800",
  "shortCode": "K9xM3bR2w",
  "title": "Quick sort implementation",
  "language": "python",
  "visibility": "unlisted",
  "content": "def quick_sort(arr):\n    if len(arr) <= 1:\n        return arr\n    pivot = arr[len(arr) // 2]\n    left = [x for x in arr if x < pivot]\n    middle = [x for x in arr if x == pivot]\n    right = [x for x in arr if x > pivot]\n    return quick_sort(left) + middle + quick_sort(right)",
  "contentSize": 312,
  "createdAt": "2026-02-28T10:30:00Z",
  "expireAt": "2026-03-07T10:30:00Z",
  "viewCount": 42
}

Read Raw Content

GET /api/v1/pastes/K9xM3bR2w/raw
200 OKGET → 200

Request

GET/api/v1/pastes/K9xM3bR2w/raw
Headers
TênGiá trị
Hostapi.pastebin.example.com

Response

200OK
Headers
TênGiá trị
Content-Typetext/plain; charset=utf-8
Cache-Controlpublic, max-age=300
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

Error Response

HTTP/1.1 410 Gone
Content-Type: application/json

{
  "timestamp": "2026-03-08T10:30:00Z",
  "status": 410,
  "error": "Gone",
  "code": "PASTE_EXPIRED",
  "message": "This paste has expired and is no longer available.",
  "path": "/api/v1/pastes/K9xM3bR2w"
}

Pagination / Filtering / Sorting

  • Strategy: Cursor-based pagination (dùng createdAt + id làm cursor) — phù hợp hơn offset cho dataset lớn và liên tục thêm dữ liệu.
  • Filter fields: language, visibility, createdAfter, createdBefore.
  • Sort: createdAt (desc mặc định), viewCount.
  • Page size: default 20, max 100.
  • Ví dụ: GET /api/v1/users/me/pastes?language=python&cursor=eyJpZCI6MjkwMTg0...&limit=20

API Versioning

  • Strategy: path-based (/api/v1/...).
  • Deprecation policy: dual-run ít nhất 6 tháng, gửi Deprecation header trên v1 khi v2 sẵn sàng.

8. 🗄️ Data Modeling

Database Schema

CREATE TABLE users (
    id              BIGINT          PRIMARY KEY,
    username        VARCHAR(50)     NOT NULL UNIQUE,
    email           VARCHAR(255)    NOT NULL UNIQUE,
    password_hash   VARCHAR(255)    NOT NULL,
    plan            VARCHAR(20)     NOT NULL DEFAULT 'free'
                                    CHECK (plan IN ('free', 'pro', 'enterprise')),
    created_at      TIMESTAMPTZ     NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ     NOT NULL DEFAULT NOW()
);

CREATE TABLE paste_metadata (
    id              BIGINT          PRIMARY KEY,
    short_code      VARCHAR(12)     NOT NULL UNIQUE,
    title           VARCHAR(255),
    language        VARCHAR(50)     NOT NULL DEFAULT 'plaintext',
    visibility      VARCHAR(10)     NOT NULL DEFAULT 'unlisted'
                                    CHECK (visibility IN ('public', 'unlisted', 'private')),
    status          VARCHAR(10)     NOT NULL DEFAULT 'active'
                                    CHECK (status IN ('active', 'expired', 'burned', 'deleted')),
    s3_key          VARCHAR(255)    NOT NULL,
    content_size    INTEGER         NOT NULL,
    user_id         BIGINT          REFERENCES users(id) ON DELETE SET NULL,
    burn_after_read BOOLEAN         NOT NULL DEFAULT FALSE,
    view_count      INTEGER         NOT NULL DEFAULT 0,
    expire_at       TIMESTAMPTZ,
    created_at      TIMESTAMPTZ     NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ     NOT NULL DEFAULT NOW()
);

CREATE TABLE paste_view_daily (
    paste_id        BIGINT          NOT NULL REFERENCES paste_metadata(id) ON DELETE CASCADE,
    view_date       DATE            NOT NULL,
    view_count      INTEGER         NOT NULL DEFAULT 0,
    PRIMARY KEY (paste_id, view_date)
);

CREATE TABLE idempotency_keys (
    idempotency_key VARCHAR(64)     PRIMARY KEY,
    response_body   JSONB           NOT NULL,
    created_at      TIMESTAMPTZ     NOT NULL DEFAULT NOW()
);

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: right
USERS: {
  shape: sql_table
  "id": bigint {constraint: primary_key}
  "username": varchar {constraint: unique}
  "email": varchar {constraint: unique}
  "password_hash": varchar
  "plan": varchar
  "created_at": timestamptz
  "updated_at": timestamptz
}

PASTE_METADATA: {
  shape: sql_table
  "id": bigint {constraint: primary_key}
  "short_code": varchar {constraint: unique}
  "title": varchar
  "language": varchar
  "visibility": varchar
  "status": varchar
  "s3_key": varchar
  "content_size": integer
  "user_id": bigint {constraint: foreign_key}
  "burn_after_read": boolean
  "view_count": integer
  "expire_at": timestamptz
  "created_at": timestamptz
  "updated_at": timestamptz
}

PASTE_VIEW_DAILY: {
  shape: sql_table
  "paste_id": bigint {constraint: [primary_key; foreign_key]}
  "view_date": date {constraint: primary_key}
  "view_count": integer
}

USERS."id" <-> PASTE_METADATA."user_id": "owns" {
  source-arrowhead: "1" {shape: cf-one-required}
  target-arrowhead: "0..N" {shape: cf-many}
}
PASTE_METADATA."id" <-> PASTE_VIEW_DAILY."paste_id": "has daily views" {
  source-arrowhead: "1" {shape: cf-one-required}
  target-arrowhead: "0..N" {shape: cf-many}
}
USERSidbigintPKusernamevarcharUNQemailvarcharUNQpassword_hashvarcharplanvarcharcreated_attimestamptzupdated_attimestamptzPASTE_METADATAidbigintPKshort_codevarcharUNQtitlevarcharlanguagevarcharvisibilityvarcharstatusvarchars3_keyvarcharcontent_sizeintegeruser_idbigintFKburn_after_readbooleanview_countintegerexpire_attimestamptzcreated_attimestamptzupdated_attimestamptzPASTE_VIEW_DAILYpaste_idbigintPK, FKview_datedatePKview_countinteger owns10..Nhas daily views10..N
USERSidbigintPKusernamevarcharUNQemailvarcharUNQpassword_hashvarcharplanvarcharcreated_attimestamptzupdated_attimestamptzPASTE_METADATAidbigintPKshort_codevarcharUNQtitlevarcharlanguagevarcharvisibilityvarcharstatusvarchars3_keyvarcharcontent_sizeintegeruser_idbigintFKburn_after_readbooleanview_countintegerexpire_attimestamptzcreated_attimestamptzupdated_attimestamptzPASTE_VIEW_DAILYpaste_idbigintPK, FKview_datedatePKview_countinteger owns10..Nhas daily views10..N
paste-bin — ER Diagram

Indexing Strategy

IndexColumnsLoạiPhục vụ query
idx_paste_short_codeshort_codeUNIQUELookup paste by short code (read path critical)
idx_paste_user_iduser_idB-treeList pastes by user (GET /users/me/pastes)
idx_paste_visibility_createdvisibility, created_at DESCCompositeList public pastes sorted by recent
idx_paste_expire_atexpire_atB-tree, partial (WHERE status = 'active' AND expire_at IS NOT NULL)Cleanup job tìm expired pastes
idx_paste_statusstatusB-tree, partial (WHERE status = 'active')Filter active pastes
idx_view_daily_dateview_dateB-treeCleanup old analytics data

Partitioning / Sharding Strategy

  • paste_metadata: Range partition theo created_at (monthly partitions).
    • Partition giúp cleanup nhanh: DROP PARTITION cho tháng cũ thay vì DELETE hàng triệu rows.
    • Khi cần shard (>10TB metadata): hash partition theo short_code trên application level (consistent hashing).
  • paste_view_daily: Range partition theo view_date (monthly).
    • Dễ dàng drop partition cũ sau khi rollup vào monthly aggregate.
  • S3: tự động distributed, key prefix pastes/{YYYY}/{MM}/{short_code} để tránh S3 hot partition.

Data Retention Policy

Loại dataRetentionStrategy
Active paste content (S3)Theo expire_at user chọnS3 Lifecycle + cleanup job
Expired paste metadata30 ngày sau expirySoft delete → hard delete bởi cleanup job
Never-expire pastesVĩnh viễn (hoặc 5 năm inactive)Archive to S3 Glacier sau 1 năm không access
Daily view analytics90 ngày chi tiếtRollup → monthly aggregate → delete detail
Idempotency keys24 giờTTL-based cleanup
User dataVĩnh viễn (hoặc theo GDPR request)Soft delete + anonymize

💡 Tại sao tách content ra S3? PostgreSQL row chỉ lưu ~300B metadata, giúp DB size kiểm soát được (~2.74TB/5 năm thay vì ~50TB nếu inline content). Backup nhanh hơn, query nhanh hơn, cost thấp hơn.

9. ⚙️ Manager Classes / Services

Service Decomposition

ServiceVai trò
paste-serviceXử lý tạo paste: validate input, generate ID, compress, upload S3, save metadata
read-serviceXử lý đọc paste: cache lookup, fetch metadata + content, decompress, publish view event
user-serviceQuản lý user registration, authentication, profile
cleanup-serviceScheduled job xóa expired paste metadata + S3 objects
analytics-serviceConsume view events từ Kafka, aggregate view counts

Core Service Classes & Responsibilities

  • PasteCreationService (@Service): orchestrate tạo paste (validate → generate ID → compress → S3 upload → DB insert → cache warm).
  • PasteReadService (@Service): orchestrate đọc paste (cache → DB → S3 → decompress → publish event).
  • ContentStorageService (@Service): abstract S3 operations (upload, download, delete) với gzip compression.
  • IdGeneratorClient (@Component): gọi ID generator service để lấy Snowflake ID.
  • PasteCleanupJob (@Component, @Scheduled): batch tìm và xóa expired pastes.
  • ViewEventPublisher (@Component): publish view events tới Kafka (async, fire-and-forget).
  • SecurityConfig (@Configuration): Spring Security + JWT validation, endpoint access rules.
  • CacheService (@Service): abstract Redis operations cho paste caching.

Backend Code Example (Java / Spring Boot)

PasteCreationService.java · PasteCreationService — đọc luồng xử lý
@Servicepublic class PasteCreationService {    private final PasteMetadataRepository metadataRepository;    private final ContentStorageService contentStorage;    private final IdGeneratorClient idGenerator;    private final CacheService cacheService;    public PasteCreationService(PasteMetadataRepository metadataRepository,                                 ContentStorageService contentStorage,                                 IdGeneratorClient idGenerator,                                 CacheService cacheService) {        this.metadataRepository = metadataRepository;        this.contentStorage = contentStorage;        this.idGenerator = idGenerator;        this.cacheService = cacheService;    }    @Transactional    public PasteResponse create(CreatePasteRequest req, Long userId) {        validateContent(req.content(), req.language());        long snowflakeId = idGenerator.nextId();        String shortCode = Base62.encode(snowflakeId);        String s3Key = "pastes/" + shortCode;        contentStorage.upload(s3Key, req.content());        Instant expireAt = req.expireIn() != null                ? Instant.now().plus(parseDuration(req.expireIn()))                : null;        PasteMetadata metadata = PasteMetadata.builder()                .id(snowflakeId)                .shortCode(shortCode)                .title(req.title())                .language(req.language())                .visibility(req.visibility())                .s3Key(s3Key)                .contentSize(req.content().length())                .userId(userId)                .burnAfterRead(req.burnAfterRead())                .expireAt(expireAt)                .build();        metadataRepository.save(metadata);        cacheService.cachePaste(shortCode, metadata, req.content());        return PasteResponse.from(metadata);    }    private void validateContent(String content, String language) {        if (content == null || content.isBlank()) {            throw new BadRequestException("CONTENT_REQUIRED");        }        if (content.length() > 10_485_760) { // 10MB            throw new PayloadTooLargeException("CONTENT_TOO_LARGE");        }    }}

PostgreSQL lưu metadata, S3 lưu nội dung; các client được inject qua constructor.

@Service
public class PasteReadService {

    private final PasteMetadataRepository metadataRepository;
    private final ContentStorageService contentStorage;
    private final CacheService cacheService;
    private final ViewEventPublisher viewEventPublisher;

    public PasteReadService(PasteMetadataRepository metadataRepository,
                            ContentStorageService contentStorage,
                            CacheService cacheService,
                            ViewEventPublisher viewEventPublisher) {
        this.metadataRepository = metadataRepository;
        this.contentStorage = contentStorage;
        this.cacheService = cacheService;
        this.viewEventPublisher = viewEventPublisher;
    }

    public PasteDetailResponse read(String shortCode, Long currentUserId) {
        // 1. Try cache
        CachedPaste cached = cacheService.getPaste(shortCode);
        if (cached != null) {
            checkAccess(cached.metadata(), currentUserId);
            checkExpiry(cached.metadata());
            viewEventPublisher.publish(shortCode);
            return PasteDetailResponse.from(cached);
        }

        // 2. DB lookup
        PasteMetadata metadata = metadataRepository.findByShortCode(shortCode)
                .orElseThrow(() -> new NotFoundException("PASTE_NOT_FOUND"));

        checkAccess(metadata, currentUserId);
        checkExpiry(metadata);

        // 3. Handle burn after read
        if (metadata.isBurnAfterRead()) {
            return handleBurnAfterRead(metadata);
        }

        // 4. Fetch content from S3
        String content = contentStorage.download(metadata.getS3Key());

        // 5. Cache for next reads
        cacheService.cachePaste(shortCode, metadata, content);

        // 6. Publish view event (async)
        viewEventPublisher.publish(shortCode);

        return PasteDetailResponse.from(metadata, content);
    }

    private void checkExpiry(PasteMetadata metadata) {
        if (metadata.getExpireAt() != null && Instant.now().isAfter(metadata.getExpireAt())) {
            throw new GoneException("PASTE_EXPIRED");
        }
        if ("burned".equals(metadata.getStatus()) || "expired".equals(metadata.getStatus())) {
            throw new GoneException("PASTE_NO_LONGER_AVAILABLE");
        }
    }

    private void checkAccess(PasteMetadata metadata, Long currentUserId) {
        if ("private".equals(metadata.getVisibility())) {
            if (currentUserId == null || !currentUserId.equals(metadata.getUserId())) {
                throw new ForbiddenException("PASTE_PRIVATE");
            }
        }
    }

    @Transactional
    private PasteDetailResponse handleBurnAfterRead(PasteMetadata metadata) {
        String content = contentStorage.download(metadata.getS3Key());
        metadata.setStatus("burned");
        metadataRepository.save(metadata);
        contentStorage.delete(metadata.getS3Key());
        cacheService.evictPaste(metadata.getShortCode());
        return PasteDetailResponse.burned(metadata, content);
    }
}

Frontend Code Example (React + TypeScript)

import { useState } from "react";

const LANGUAGES = ["plaintext", "python", "java", "javascript", "typescript", "go", "rust", "sql", "bash", "json", "yaml", "markdown"];
const EXPIRE_OPTIONS = [
  { label: "10 Minutes", value: "10m" },
  { label: "1 Hour", value: "1h" },
  { label: "1 Day", value: "1d" },
  { label: "1 Week", value: "7d" },
  { label: "1 Month", value: "30d" },
  { label: "Never", value: null },
];

interface PasteResponse {
  shortCode: string;
  pasteUrl: string;
  rawUrl: string;
  expireAt: string | null;
}

export function CreatePasteForm() {
  const [content, setContent] = useState("");
  const [title, setTitle] = useState("");
  const [language, setLanguage] = useState("plaintext");
  const [visibility, setVisibility] = useState<"public" | "unlisted" | "private">("unlisted");
  const [expireIn, setExpireIn] = useState<string | null>("7d");
  const [burnAfterRead, setBurnAfterRead] = useState(false);
  const [result, setResult] = useState<PasteResponse | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/v1/pastes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, content, language, visibility, expireIn, burnAfterRead }),
      });
      const data: PasteResponse = await res.json();
      setResult(data);
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title (optional)" />

      <textarea value={content} onChange={(e) => setContent(e.target.value)} placeholder="Paste your code or text here..." rows={20} required />

      <select value={language} onChange={(e) => setLanguage(e.target.value)}>
        {LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
      </select>

      <select value={visibility} onChange={(e) => setVisibility(e.target.value as "public" | "unlisted" | "private")}>
        <option value="public">Public</option>
        <option value="unlisted">Unlisted</option>
        <option value="private">Private</option>
      </select>

      <select value={expireIn ?? ""} onChange={(e) => setExpireIn(e.target.value || null)}>
        {EXPIRE_OPTIONS.map((o) => <option key={o.label} value={o.value ?? ""}>{o.label}</option>)}
      </select>

      <label>
        <input type="checkbox" checked={burnAfterRead} onChange={(e) => setBurnAfterRead(e.target.checked)} />
        Burn after read
      </label>

      <button type="submit" disabled={loading || !content}>
        {loading ? "Creating..." : "Create Paste"}
      </button>

      {result && (
        <div>
          <p>Paste URL: <a href={result.pasteUrl}>{result.pasteUrl}</a></p>
          <p>Raw URL: <a href={result.rawUrl}>{result.rawUrl}</a></p>
          {result.expireAt && <p>Expires: {new Date(result.expireAt).toLocaleString()}</p>}
        </div>
      )}
    </form>
  );
}

Service Communication Patterns

  • Sync REST: Gateway → Paste Service / Read Service / User Service qua internal HTTP.
  • Async event: Read Service → Kafka → Analytics Service (view events).
  • Async event: Paste Service → Kafka → Analytics Service (create events, optional).
  • Shared libs: common error model, tracing interceptor, auth principal extractor, Base62 encoder.

10. 🏛️ Architecture Design

  • Pattern chính: Microservices + Event-driven analytics + S3 content offload.
  • Read path tối ưu: CloudFront cache (L1) → Redis cache (L2) → DB metadata + S3 content.
  • Write path: Gateway → Paste Service → S3 upload (async) + DB insert.
  • Deployment trên AWS EKS multi-AZ, tách node group cho read-heavy workload.
  • RDS PostgreSQL Multi-AZ cho metadata, S3 cho content, ElastiCache Redis cho caching.
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.PS: "Paste Service Pods"
AWS_VPC.EKS.RS: "Read Service Pods"
AWS_VPC.EKS.US: "User Service Pods"
AWS_VPC.EKS.AS: "Analytics Service Pods"
AWS_VPC.EKS.CJ: "Cleanup CronJob 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 Content Store" {
  shape: cylinder
  icon: ../../diagrams/icons/s3.svg
}
AWS_VPC.S3G: "S3 Glacier Archive" {
  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.PS
AWS_VPC.EKS.GW -> AWS_VPC.EKS.RS
AWS_VPC.EKS.GW -> AWS_VPC.EKS.US
AWS_VPC.EKS.PS -> AWS_VPC.S3
AWS_VPC.EKS.PS -> AWS_VPC.RDS
AWS_VPC.EKS.RS -> AWS_VPC.REDIS
AWS_VPC.EKS.RS -> AWS_VPC.RDS
AWS_VPC.EKS.RS -> AWS_VPC.S3
AWS_VPC.EKS.RS -> AWS_VPC.MSK
AWS_VPC.EKS.AS -> AWS_VPC.MSK
AWS_VPC.EKS.AS -> AWS_VPC.RDS
AWS_VPC.EKS.CJ -> AWS_VPC.RDS
AWS_VPC.EKS.CJ -> AWS_VPC.S3
AWS_VPC.RDS -> AWS_VPC.RR
AWS_VPC.S3 -> AWS_VPC.S3G: "lifecycle" {style.stroke-dash: 4}
AWS_VPC.EKS.GW -> AWS_VPC.CW: "metrics/logs" {style.stroke-dash: 4}
AWS_VPC.EKS.PS -> AWS_VPC.AMG: "metrics/logs" {style.stroke-dash: 4}
AWS_VPC.EKS.RS -> AWS_VPC.AMG: "metrics/logs" {style.stroke-dash: 4}
AWS_VPC.EKS.AS -> AWS_VPC.AMG: "metrics/logs" {style.stroke-dash: 4}
InternetAWS EdgeAWS VPCEKSClient/BrowsersRoute53CloudFrontAWS WAFApplication Load BalancerElastiCache RedisRDS PostgreSQL Multi-AZRDS Read ReplicasAmazon MSK / KafkaS3 Content StoreS3 Glacier ArchiveCloudWatchManaged Prometheus/GrafanaGateway PodsPaste Service PodsRead Service PodsUser Service PodsAnalytics Service PodsCleanup CronJob Pods lifecyclemetrics/logsmetrics/logsmetrics/logsmetrics/logs
InternetAWS EdgeAWS VPCEKSClient/BrowsersRoute53CloudFrontAWS WAFApplication Load BalancerElastiCache RedisRDS PostgreSQL Multi-AZRDS Read ReplicasAmazon MSK / KafkaS3 Content StoreS3 Glacier ArchiveCloudWatchManaged Prometheus/GrafanaGateway PodsPaste Service PodsRead Service PodsUser Service PodsAnalytics Service PodsCleanup CronJob Pods lifecyclemetrics/logsmetrics/logsmetrics/logsmetrics/logs
paste-bin — Kiến trúc triển khai AWS

Scaling Strategy

  • Read Service: HPA theo CPU + custom metric (read_rps), min 3 → max 20 pods.
  • Paste Service: HPA theo CPU, min 2 → max 10 pods.
  • Analytics Service: VPA (batch workload, memory-intensive Kafka consumer).
  • PostgreSQL: scale-up instance + read replicas cho list/search queries.
  • Redis: cluster mode enabled, shard rebalancing khi memory >70%.
  • S3: tự động scale, không cần quản lý.

Caching Strategy

  • L1 — CloudFront: cache public/unlisted paste HTML pages (TTL 5 min). Raw content endpoint cache lâu hơn (TTL 1 hour). Private paste: Cache-Control: no-store.
  • L2 — Redis cache-aside: cache paste metadata + content (decompressed) cho hot pastes. TTL dynamic:
    • Paste mới tạo: TTL 1 hour (warming period).
    • Paste có view_count > 100: TTL 6 hours.
    • Burn-after-read: không cache.
  • Eviction: allkeys-lru trong Redis. Paste lớn (>100KB) không cache content trong Redis, chỉ cache metadata.

Load Balancing / Gateway / Mesh

  • ALB: route tất cả traffic vào EKS ingress controller, health check /actuator/health.
  • Spring Cloud Gateway: routing rules, JWT validation, rate limiting (Redis-backed), request logging.
  • Service mesh (optional): Istio/Linkerd cho mTLS giữa services nội bộ và traffic observability.

Resilience Patterns

  • Circuit Breaker (Resilience4j):
    • Read Service → S3: failure threshold 50% trong 20 requests, open 30s.
    • Read Service → Redis: failure threshold 40%, open 15s. Fallback: skip cache, đọc DB + S3.
    • Paste Service → ID Generator: threshold 50%, open 10s. Fallback: trả 503 Retry-After.
  • Retry with Backoff:
    • S3 operations: exponential backoff 100ms → 200ms → 400ms, max 3 retries, jitter ±50ms.
    • DB transient errors: 50ms → 100ms → 200ms, max 3 retries.
  • Bulkhead:
    • Read Service: separate thread pool (read: 100 threads, burn-after-read: 20 threads).
    • Paste Service: create pool 50 threads, S3 upload pool 30 threads.
  • Timeout:
    • Redis GET: 5ms. Redis SET: 10ms.
    • S3 GET: 200ms (content có thể lớn). S3 PUT: 2000ms.
    • DB query: 50ms. DB write: 100ms.
  • Graceful Degradation:
    • Redis down → skip cache, serve từ DB + S3 (latency tăng ~50-100ms nhưng vẫn hoạt động).
    • Kafka down → buffer view events in-memory (bounded queue 5K events), retry publish. Read vẫn trả response, chỉ analytics delay.
    • S3 down → serve từ Redis cache nếu có. Nếu cache miss → 503 với Retry-After header.
  • Request Coalescing: khi multiple requests đọc cùng paste miss cache đồng thời, dùng singleflight pattern — chỉ 1 request fetch S3, các request khác chờ kết quả.

11. 🧪 Testing Strategy

  • Unit Testing: JUnit 5 + Mockito cho service logic (PasteCreationService, PasteReadService, ContentStorageService), coverage target >80%.
  • Integration Testing: Spring Boot Test + Testcontainers (PostgreSQL, Redis, Kafka, LocalStack cho S3).
  • API Contract Testing: Spring Cloud Contract giữa Gateway và downstream services.
  • Load Testing: Gatling kịch bản:
    • Sustained 1,500 read QPS, xác nhận p95 < 100ms.
    • Burst 300 write QPS với 5KB payload, xác nhận p95 < 300ms.
    • Large paste (5MB) upload, xác nhận hoàn thành < 3s.
  • Chaos Engineering: AWS Fault Injection Simulator:
    • Redis node failure → verify fallback to DB + S3.
    • S3 latency injection (500ms) → verify circuit breaker opens.
    • AZ outage → verify multi-AZ failover < 30s.
  • E2E Testing: Playwright cho web UI tạo paste, đọc paste, verify syntax highlighting, test burn-after-read.

12. 🔒 Security

  • Authentication: OAuth2/JWT cho management APIs (create authenticated, delete, list my pastes). Anonymous access cho đọc public/unlisted paste và tạo guest paste.
  • Authorization: Owner-based access control — chỉ owner được delete, edit, hoặc xem private paste.
  • TLS: HTTPS cho tất cả public endpoints. mTLS nội bộ nếu bật service mesh.
  • Input validation:
    • Content size limit theo plan (64KB guest, 1MB free, 10MB pro).
    • Chống XSS: sanitize title field. Content hiển thị trong <pre><code> escaped context.
    • Chống SSRF: không applicable (paste không fetch external URLs).
  • Content scanning: optional — scan paste content cho malware signatures, PII patterns (credit card, SSN) bằng async job post-creation. Flag nhưng không block (để giảm false positive impact).
  • DDoS/bot protection: WAF rate rules + AWS Shield Standard. CAPTCHA cho anonymous paste creation khi rate limit gần ngưỡng.
  • Data protection: encryption at rest (S3 SSE-KMS, RDS encryption, ElastiCache encryption), encryption in transit (TLS 1.2+).
  • Secrets management: DB credentials, JWT signing keys, S3 access 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 mitigations:
    • Injection: parameterized queries (Spring Data JPA), no dynamic SQL.
    • Broken auth: JWT short-lived (15 min access token), refresh token rotation.
    • Security misconfiguration: hardened container images, read-only filesystem, non-root user.
  • Compliance: GDPR right-to-erasure (xóa paste + S3 content + analytics data theo user request). Burn-after-read tự nhiên hỗ trợ privacy-sensitive use cases.

13. 📊 Monitoring & Logging

Key Metrics

NhómMetrics
Latencyp50/p95/p99 read paste latency, create paste latency, S3 upload/download latency
Trafficread RPS, create RPS, raw content RPS, S3 GET/PUT RPS
Errors4xx/5xx rate, S3 error rate, DB timeout rate, cache miss ratio
SaturationCPU/memory pods, Redis memory%, DB connections, Kafka consumer lag, S3 request rate

Logging Strategy

  • Structured JSON logs với fields: traceId, shortCode, userId, statusCode, contentSize, cacheHit.
  • Log levels:
    • INFO: paste created, paste read, paste deleted, cleanup job completed.
    • WARN: cache miss, retry attempt, rate limit triggered.
    • ERROR: S3 failure, DB failure, circuit breaker opened.
  • Centralized logging: ELK/OpenSearch, retention 30 ngày hot + 90 ngày warm.

SLI / SLO / Error Budget (SRE)

  • SLI read: tỷ lệ read requests trả về 200/404/410 (non-5xx) trong tổng read requests.
  • SLI create: p99 latency của POST /api/v1/pastes response time.
  • SLO read availability: 99.99% → error budget = 0.01% = tối đa 4.3 phút downtime/tháng.
  • SLO create latency: p99 < 500ms cho 99.5% thời gian đo trong 30-day rolling window.
  • Error budget policy:
    • Budget > 50%: deploy bình thường, feature releases.
    • Budget 20-50%: canary chặt (5% → 10% → 25% → 100%), tăng bake time.
    • Budget < 20%: freeze feature deployments, chỉ reliability fixes. Postmortem bắt buộc cho incident tiêu > 10% budget.

Alerting & Incident Response

  • Alert nếu read p95 > 200ms trong 5 phút.
  • Alert nếu 5xx > 1% trong 3 phút.
  • Alert nếu cache hit ratio < 70% trong 10 phút.
  • Alert nếu S3 error rate > 0.5% trong 5 phút.
  • Alert nếu Kafka consumer lag > 100K messages trong 10 phút.
  • Runbook: detect → triage → mitigate → postmortem trong 24h.
  • Distributed tracing: OpenTelemetry + Jaeger/X-Ray, trace read flow end-to-end (Gateway → Cache → DB → S3).

14. 🔧 Maintenance

  • CI/CD: GitHub Actions pipeline build → unit test → integration test → security scan (Trivy + SAST) → build Docker image → deploy staging → smoke test → deploy production.
  • Database migration: Flyway versioned migrations, backward-compatible strategy (add column → migrate data → drop old column trong separate release).
  • Dependency management: Renovate auto-update PRs, SCA scan (Snyk) cho vulnerabilities.
  • Feature flags: LaunchDarkly (hoặc config service nội bộ) cho rollout burn-after-read, content scanning, new syntax languages.
  • S3 lifecycle management: review lifecycle rules quarterly, adjust archive thresholds dựa trên access patterns thực tế.
  • Documentation: OpenAPI/Swagger auto-publish từ Spring annotations, ADR cho mọi architecture decisions.
  • Technical debt: sprint cuối tháng dành 10-15% capacity xử lý tech debt. Review backlog debt items mỗi quarter.

15. 🚀 Deployment Plans

  • Deployment strategy:
    • Read Service: Canary (5% → 25% → 100%) vì đây là critical path.
    • Paste Service: Rolling update (ít critical hơn, downtime tolerance cao hơn).
    • Gateway: Blue-Green để minimize downtime.
  • Rollback plan: kubectl rollout undo, Flyway undo migration (nếu backward-compatible), feature flag kill-switch cho new features.
  • IaC: Terraform modules cho:
    • VPC (multi-AZ, public/private subnets)
    • EKS (managed node groups, Fargate profiles)
    • RDS PostgreSQL (Multi-AZ, parameter groups, backup)
    • ElastiCache Redis (cluster mode, encryption)
    • MSK/Kafka (multi-AZ brokers)
    • S3 (content bucket + lifecycle rules + replication)
    • IAM (service roles, pod identity)
    • CloudFront (distribution + S3 origin)
  • Auto-scaling:
    • HPA: CPU 70% threshold, custom metric rps cho read/paste services.
    • VPA: analytics service (memory-intensive).
    • Cluster Autoscaler + Karpenter cho node scaling.
  • Multi-region: Active-passive (primary region + DR). Route53 health-check failover. S3 cross-region replication cho content. RDS cross-region read replica promote khi failover.
  • Artifacts: Docker multi-stage build cho Spring Boot apps. Helm charts cho từng service với environment-specific values.
  • Pre-prod gate: bắt buộc qua integration test + load test (shadow traffic) + smoke test trước production rollout.

16. ⏱️ Effort Estimation

Phase Breakdown & Timeline

PhaseDurationDeliverables
Discovery & Requirements1 tuầnScope, SLA, API contract draft, S3 bucket design
Core Paste CRUD MVP2 tuầnCreate/read/delete APIs, PostgreSQL metadata, S3 content storage, Redis cache
User Management & Access Control1 tuầnRegistration, JWT auth, visibility enforcement, user paste listing
Burn-after-read & Expiration1 tuầnBurn logic, cleanup scheduled job, S3 lifecycle policies
Analytics & Observability1 tuầnKafka view events, view count aggregation, dashboards, alerts
Security & Hardening1 tuầnWAF rules, content scanning, rate limiting tuning, penetration testing
Performance & Production Readiness1.5 tuầnLoad test, chaos test, runbooks, documentation
Total~8.5 tuầnProduction v1

Team Composition

RoleSố lượngResponsibilities
Tech Lead1Architecture decisions, trade-offs review, code review
Backend Engineers2Paste/Read/Cleanup services, S3 integration, Kafka pipeline
Frontend Engineer1Paste creation UI, paste viewer with syntax highlighting, user dashboard
DevOps Engineer1EKS/Terraform/CI-CD, S3 lifecycle, monitoring setup
QA Engineer1Test automation, load testing, chaos testing

Risk Assessment

RiskImpactMitigation
Large paste upload timeoutUser experience kém, data lossClient-side chunked upload, progress indicator, retry logic
S3 outage ảnh hưởng read pathKhông serve được contentRedis cache L2 cho hot pastes, multi-region S3 replication
Content abuse (malware/spam paste)Reputation risk, legal issuesContent scanning async job, report mechanism, rate limit anonymous
DB growth nhanh hơn dự kiếnPerformance degradationPartition strategy sẵn sàng, archive policy, monitor table size
Burn-after-read race conditionMultiple users đọc được contentSELECT ... FOR UPDATE lock, atomic DB update + S3 delete

Dependencies & Blockers

  • Cần IAM/security baseline từ platform team trước khi lên production.
  • Cần S3 bucket policy review và KMS key provisioning.
  • Cần domain + TLS certificate + WAF policy approved.
  • Cần Kafka topic provisioning và retention policy agreement với platform team.
  • Cần budget approval cho MSK, ElastiCache, và S3 cross-region replication (nếu multi-region).

17. 💰 Cost Estimation & Optimization

17.1 Chi phí hàng tháng theo từng resource

📌 Giá tham chiếu theo AWS On-Demand ở region ap-southeast-1 (Singapore). Sizing truy nguồn về Capacity Estimation §2.3.

Compute

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
EKS Control PlaneManaged1 cluster$73$73Fixed cost
Read Service podsc6g.large (2 vCPU, 4GB)3–20 pods~$50/node$150–$400HPA theo read QPS [C2]
Paste Service podsc6g.large2–10 pods~$50/node$100–$200HPA theo write QPS [C1]
User Service podst3.medium (2 vCPU, 4GB)2 pods~$30/node$60Low traffic
Analytics Service podsr6g.medium (1 vCPU, 8GB)2 pods~$45/node$90Kafka consumer, memory-intensive
Cleanup CronJobt3.small1 pod (intermittent)~$15$15Chạy mỗi 15 phút
Gateway podsc6g.medium2–4 pods~$25/node$50–$100Routing + rate limiting
Subtotal Compute$538–$938

Database

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
RDS PostgreSQL Multi-AZdb.r6g.xlarge (4 vCPU, 32GB)1 primary + 1 standby$548 x 2$1,096Metadata ~547GB/year [C4]
RDS Read Replicadb.r6g.large (2 vCPU, 16GB)1$274$274List/search queries
RDS Storage (gp3)500GB initial—$0.08/GB$40Auto-scale khi cần
Subtotal Database$1,410

Cache

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
ElastiCache Redisr6g.large (2 vCPU, 13GB)2-node cluster (primary + replica)$219/node$438~18GB cache [C6]
Subtotal Cache$438

Message Queue

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
Amazon MSKkafka.m5.large (2 vCPU, 8GB)3 brokers (multi-AZ)$130/broker$390View events + create events
MSK Storage100GB/broker3$0.10/GB$30Retention 7 ngày
Subtotal Message Queue$420

Network / CDN

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
CloudFront~200GB/day data transfer [C5]~6TB/month~$0.085/GB (first 10TB)$510Cache ratio ~60% giảm origin traffic
ALBStandard1$22 + LCU$50LCU based on request count
NAT GatewayStandard2 (multi-AZ)$32 + data$100Outbound traffic cho pods
Route53Hosted zone + queries1 zone$0.50 + queries$5
Subtotal Network$665

Storage

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
S3 Standard~25GB/day compressed → ~250GB/month activeGrowing$0.025/GB$6 (month 1) → $75 (year 1)Content store [C3], gzip ~3:1
S3 GlacierArchived expired pastes—$0.005/GB~$10After 1 year inactive
S3 RequestsPUT ~5M/month, GET ~750M/month—$0.005/1K PUT, $0.0004/1K GET$325GET giảm nhờ CloudFront cache
Subtotal Storage$341–$410

Monitoring / Logging

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
CloudWatchMetrics + logs——$80Custom metrics + log ingestion
Amazon Managed Grafana1 workspace1$9/editor$273 editors
Amazon Managed PrometheusMetrics ingestion—$0.003/10K samples$50~500 metrics
OpenSearch (logs)t3.medium.search2 nodes$54/node$10830-day retention hot
Subtotal Monitoring$265

Misc

ResourceSpec / SizingSố lượngĐơn giá (USD/tháng)Thành tiền (USD/tháng)Ghi chú
AWS WAFWeb ACL + rules1 ACL, 5 rules$5 ACL + $1/rule$10Rate limit + bot protection
AWS Secrets ManagerSecrets5 secrets$0.40/secret$2DB creds, JWT keys, S3 keys
ECRContainer images—$0.10/GB$5~50GB images
Subtotal Misc$17

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

Giai đoạnMonthly CostAnnual CostGhi chú
MVP (low traffic, 10% peak)~$2,800~$33,600Min replicas, single read replica, nhỏ S3
Growth (avg traffic)~$4,100~$49,200Mid-range scaling, S3 tăng dần
Peak / Scale (peak traffic)~$6,500~$78,000Max HPA, full CDN bandwidth, large S3

17.3 Cost Breakdown theo category

Category% tổng cost (Growth)
Database (RDS)~34%
Compute (EKS pods)~18%
Network / CDN~16%
Cache (ElastiCache)~11%
Message Queue (MSK)~10%
Storage (S3)~5%
Monitoring / Logging~5%
Misc~1%

📌 Database chiếm tỷ trọng lớn nhất (~34%). Đây là target ưu tiên cho cost optimization (Reserved Instances, right-sizing).

17.4 Cost Optimization Strategies

StrategyMô tảTiết kiệm ước tínhTrade-off
Reserved Instances (1-year)RI cho RDS, ElastiCache, MSK — workload ổn định 24/730-40% DB + cache = **$700/tháng**Commit 1 năm, mất flexibility
Savings Plans (Compute)Compute Savings Plan cho EKS node groups20-30% compute = **$150/tháng**Commit 1-3 năm
Spot InstancesDùng cho Analytics Service, Cleanup CronJob (fault-tolerant)60-70% cho spot workload = **$60/tháng**Có thể bị interrupt, cần retry logic
Right-sizing RDSStart db.r6g.large (MVP) → upgrade lên xlarge khi cần~$500/tháng ở MVP phaseMonitor performance sát
CloudFront cache optimizationTăng cache hit ratio từ 60% → 80% cho public/unlisted pastes~$100/tháng bandwidth savingStale content tối đa TTL window
S3 Intelligent-TieringTự động move infrequent access content xuống cheaper tier~20-30% S3 storage costAccess latency tăng cho cold objects
VPC EndpointsS3 Gateway Endpoint thay NAT Gateway cho S3 traffic~$50/tháng NAT data costKhông có
Log samplingSample 10% debug logs, 100% error/warn logs ở production~$30/tháng log ingestionMất context khi debug
Scale-to-zeroAnalytics Service + Cleanup ngoài peak → scale về 0 (KEDA)~$40/thángDelay khi cold start

17.5 Cost Projection (12-24 tháng)

Giả sử traffic tăng 20%/quý:

ThángTraffic estimateInfra changesMonthly Cost
1-3 (MVP)10% peak QPSMin sizing, single region~$2,800
4-625% peak QPSScale up Read Service replicas~$3,200
7-950% peak QPSUpgrade RDS → r6g.xlarge, thêm read replica~$4,100
10-1275% peak QPSRedis cluster scale, thêm EKS nodes~$5,200
13-18100% peak QPSFull HPA range, CDN bandwidth tăng~$6,500
19-24120% peak QPSEvaluate DB sharding, thêm AZ, multi-region DR~$8,000

📌 Điểm inflection chính: tháng 7-9 cần upgrade RDS (cost jump ~$500/tháng), tháng 19+ cần evaluate sharding strategy nếu metadata > 1TB.

17.6 Cost Alerts & Governance

  • AWS Budget alerts:
    • 80% budget ($3,280): email notification cho tech lead + DevOps.
    • 100% budget ($4,100): alert Slack channel + email manager.
    • 120% budget ($4,920): auto-trigger cost review meeting.
  • Quy trình review cost:
    • Monthly: DevOps engineer review cost dashboard, identify anomalies (>10% unexpected increase).
    • Quarterly: Tech lead + PM review cost projection, adjust RI/SP commitments, right-sizing audit.
  • Tagging strategy: tất cả resources tagged theo:
    • team:paste-bin
    • service:{paste-service|read-service|analytics-service|...}
    • environment:{dev|staging|production}
    • cost-center:engineering
  • Cost allocation: AWS Cost Explorer filtered theo tags, monthly report chia cost theo service để identify service nào tăng bất thường.

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ịBước 1: Inputs giả địnhBước 2: Tính write traffic (create paste)Bước 3: Tính read traffic (view paste)Bước 4: Tính content storage (S3)Bước 5: Tính metadata storage (PostgreSQL)Bước 6: Tính bandwidthBước 7: Redis cache memory estimateBước 8: So sánh kịch bảnBước 9: 📊 Bảng tổng hợp Capacity Estimation3. ⚖️ Trade-offs3.1 Bảng tổng quan quyết định3.2 Decision #1: Content Storage (PostgreSQL inline vs S3)Option A: PostgreSQL inline hoạt động thế nào?Option B: S3 object store hoạt động thế nào?Pseudo-code so sánhKết luận3.3 Decision #2: Syntax Highlighting (Server-side vs Client-side)Kết luận3.4 Decision #3: Expiration Cleanup StrategyKết luận4. 🧩 Defining Entities / Components5. 🔗 Client-Server Connection6. 🔄 System / App FlowFlow 1: Create PasteFlow 2: Read PasteFlow 3: Burn After ReadError handling & Edge cases7. 📡 API ModelingEndpoint DefinitionsRequest/Response ExamplesPagination / Filtering / SortingAPI Versioning8. 🗄️ Data ModelingDatabase SchemaER DiagramIndexing StrategyPartitioning / Sharding StrategyData Retention Policy9. ⚙️ Manager Classes / ServicesService DecompositionCore 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 Response14. 🔧 Maintenance15. 🚀 Deployment Plans16. ⏱️ Effort EstimationPhase Breakdown & TimelineTeam CompositionRisk AssessmentDependencies & Blockers17. 💰 Cost Estimation & Optimization17.1 Chi phí hàng tháng theo từng resource17.2 Tổng hợp cost theo giai đoạn17.3 Cost Breakdown theo category17.4 Cost Optimization Strategies17.5 Cost Projection (12-24 tháng)17.6 Cost Alerts & Governance