Skip to content

Cầu nối — Từ DSA đến System Design

Nhiều kỹ sư nghĩ DSA và System Design là hai thế giới riêng biệt — giải LeetCode xong rồi quên. Thực tế, MỌI quyết định kiến trúc hệ thống đều có gốc rễ từ DSA. Redis dùng hash table. PostgreSQL dùng B-Tree. Kafka dùng queue. Kubernetes scheduler dùng priority queue. Bài này kết nối những gì bạn vừa học trong Phase 1 với thế giới system design thực tế.

🎯 Mục tiêu

Sau bài này, bạn sẽ:

  • Mapping được 8 DSA concepts sang production equivalents tương ứng
  • Hiểu tại sao interviewer hỏi DSA TRƯỚC system design
  • Chuẩn bị cho interview crossover questions — dạng câu hỏi lai giữa hai thể loại
  • Biết khi nào và cách nào reference DSA knowledge trong system design interview

Bức tranh tổng quan — Bridge Map

Trước khi đi sâu từng cặp, hãy nhìn toàn bộ bản đồ cầu nối:

┌─────────────────────┐          ┌──────────────────────────┐
│    DSA Phase 1      │          │     System Design        │
├─────────────────────┤          ├──────────────────────────┤
│ Hash Table          │────────► │ Distributed Cache        │
│ Tree (BST / B-Tree) │────────► │ Database Index           │
│ Graph (BFS/DFS)     │────────► │ Service Dependency       │
│ Heap / Priority Q   │────────► │ Task Scheduler           │
│ Queue (FIFO)        │────────► │ Message Broker           │
│ Dynamic Programming │────────► │ Resource Optimization    │
│ Sorting             │────────► │ External Sort            │
│ Binary Search       │────────► │ Distributed Lookup       │
└─────────────────────┘          └──────────────────────────┘

Mỗi mũi tên không phải phép so sánh ẩn dụ — nó là quan hệ trực tiếp. Cùng cấu trúc dữ liệu, cùng thuật toán, chỉ khác quy mô: từ 1 máy lên hàng nghìn máy.


1. Hash Table → Distributed Cache

DSA Recap

Hash table cho phép tra cứu key → value với O(1) average. Collision được xử lý bằng chaining hoặc open addressing. Trong Phase 1, bạn đã dùng nó cho two-sum, frequency counting, và deduplication.

Production Equivalent

Ở quy mô production, hash table trở thành distributed cache:

  • Redis / Memcached — distributed hash table trải trên nhiều server
  • Consistent hashing — khi server join/leave, chỉ ~K/N keys cần redistribute (thay vì rehash toàn bộ)
  • Cache eviction — LRU chính là combo Doubly Linked List + Hash Map mà bạn đã học!
Single Machine:                    Distributed (3 nodes):
┌──────────────────┐         ┌──────────────────────────────┐
│    Hash Table    │         │     Consistent Hash Ring     │
│  key → value     │   →     │                              │
│  O(1) lookup     │         │   Node A: keys hash 0..99    │
└──────────────────┘         │   Node B: keys hash 100..199 │
                             │   Node C: keys hash 200..299 │
                             │                              │
                             │   Node B chết? → keys 100-199│
                             │   chỉ chuyển sang C, A giữ   │
                             │   nguyên (minimal disruption) │
                             └──────────────────────────────┘

Tại sao cần Consistent Hashing?

Với hash table thông thường, thêm 1 server = rehash gần như toàn bộ keys. Consistent hashing giải quyết bằng cách đặt cả keys và servers trên cùng một "vòng tròn hash". Khi server C chết, chỉ keys thuộc C chuyển sang server kế tiếp trên ring — các server khác không bị ảnh hưởng.

🎯 Interview Crossover Question

"Design a distributed cache with LRU eviction for 10 million users."

DSA cần: Hash table (O(1) lookup) + Doubly Linked List (O(1) move-to-front) = LRU Cache. System Design cần: Consistent hashing (phân phối keys), replication (fault tolerance), TTL (expiration).

Một câu hỏi — hai thế giới giao nhau.


2. Tree (BST / B-Tree) → Database Index

DSA Recap

BST cho phép search, insert, delete trong O(log n) khi cân bằng. B-Tree mở rộng ý tưởng này với branching factor lớn — mỗi node chứa nhiều keys, giảm chiều sâu cây.

Production Equivalent

Mọi database bạn từng dùng đều sống nhờ tree:

  • PostgreSQL / MySQL — B+ Tree index cho range queries (WHERE age BETWEEN 18 AND 25)
  • LSM Tree (RocksDB, LevelDB) — write-optimized, nền tảng của Cassandra, CockroachDB
  • Tại sao B-Tree thay vì BST? → Disk I/O alignment. Mỗi node B-Tree = 1 disk page (4KB), đọc 1 lần thay vì nhảy qua nhiều pointer
BST (in-memory):                  B+ Tree (on-disk):
       [50]                         [30 | 70]
      /    \                     /      |       \
   [25]    [75]            [10|20]  [40|50|60]  [80|90]
   /  \    /  \              ↓         ↓           ↓
 [10] [30][60][90]       (leaf)    (leaf)       (leaf)
                         ← linked list giữa leaves →
 Depth: ~20 cho 1M keys
 = 20 disk reads ❌       Depth: ~3-4 cho 1M keys
                          = 3-4 disk reads ✅

Insight quan trọng

BST có depth ~log₂(n) = ~20 cho 1 triệu keys → 20 random disk reads. B-Tree với branching factor 100 có depth ~log₁₀₀(n) = ~3 → chỉ 3 disk reads. Ở quy mô database, mỗi disk read = ~10ms. Khác biệt: 200ms vs 30ms cho mỗi query.

🎯 Interview Crossover Question

"Tại sao database dùng B-Tree thay vì BST hay Hash Index?"

Trả lời: B-Tree tối ưu disk I/O (node = disk page), hỗ trợ range queries (hash index không làm được), và depth thấp (~3-4 cho hàng triệu records). Hash index chỉ hỗ trợ equality lookup.


3. Graph → Service Dependency

DSA Recap

Graph = vertices + edges. BFS khám phá theo tầng, DFS đi sâu trước. Topological sort sắp xếp DAG theo dependency order. Cycle detection phát hiện vòng lặp.

Production Equivalent

Kiến trúc microservice chính là một đồ thị có hướng:

  • Service dependency graph — Service A gọi B, B gọi C → hình thành DAG
  • Circuit breaker — nếu node fail, cắt edges ngăn cascade failure (tư duy DFS)
  • Topological sort — deployment order: deploy dependencies trước
  • Cycle detection — circular dependency = deadlock tiềm ẩn
Microservice Dependency Graph:

  ┌──────┐     ┌──────┐     ┌─────────┐
  │ Auth │────►│ User │────►│ Payment │
  └──┬───┘     └──────┘     └────▲────┘
     │                           │
     │         ┌──────────────┐  │
     └────────►│ Notification │──┘
               └──────────────┘

Deployment order (topological sort):
  1. Auth → 2. User → 3. Notification → 4. Payment

Nếu Payment gọi ngược Auth → CYCLE DETECTED!
  → Circular dependency → cần refactor

Bài học từ Production

Netflix's microservice architecture có hàng trăm services. Họ dùng dependency graph analysis để:

  • Detect circular dependencies trước khi deploy
  • Tính toán blast radius khi 1 service chết (BFS từ node bị lỗi)
  • Xác định deployment order (topological sort)

🎯 Interview Crossover Question

"How would you detect circular dependencies in your microservice architecture?"

DSA cần: DFS-based cycle detection trên directed graph. System Design cần: Service registry, health checks, dependency manifest.


4. Heap / Priority Queue → Task Scheduler

DSA Recap

Heap (min/max) hỗ trợ insert O(log n), extract-min/max O(log n). Priority Queue = abstract data type, heap là implementation phổ biến nhất.

Production Equivalent

Bất kỳ hệ thống nào cần xử lý theo mức ưu tiên đều dùng priority queue:

  • OS process scheduler — Linux CFS dùng red-black tree (variant của balanced BST, tương tự heap behavior)
  • Kubernetes scheduler — assign pods vào nodes dựa trên priority, resource request
  • Job queue (Celery, Sidekiq) — process high-priority jobs trước
  • Rate limiter — token bucket + priority queue cho fair scheduling
Simple Queue (FIFO):           Priority Queue Scheduler:
                               ┌─────────────────────────┐
┌──────────────────┐           │  Priority Heap           │
│ → [A][B][C][D] → │           │                          │
└──────────────────┘           │  [P1: urgent-deploy]     │
 Ai vào trước, ra trước       │  [P2: batch-process]     │
                               │  [P3: send-email]        │
                               │  [P5: cleanup-logs]      │
                               │                          │
                               │  Extract-min → P1 first! │
                               └─────────────────────────┘

Real-World: Kubernetes Scheduler

Khi bạn kubectl apply một deployment, Kubernetes scheduler:

  1. Đưa pod vào priority queue (dựa trên PriorityClass)
  2. Extract pod có priority cao nhất
  3. Chạy scoring algorithm cho mỗi node (tương tự weighted graph)
  4. Assign pod vào node có score cao nhất

Toàn bộ flow: heap extract → score (graph traversal) → assign.

🎯 Interview Crossover Question

"Design a task scheduler that processes high-priority tasks first, with support for delayed execution."

DSA cần: Min-heap keyed on (priority, scheduled_time). Extract-min lấy task cần chạy sớm nhất. System Design cần: Distributed coordination, persistence, retry logic.


5. Queue → Message Broker

DSA Recap

Queue = FIFO. Enqueue O(1), dequeue O(1). Đơn giản nhưng mạnh mẽ — decouples producer và consumer.

Production Equivalent

Queue ở quy mô distributed trở thành message broker:

  • Kafka — distributed commit log (append-only queue with partitions)
  • RabbitMQ — traditional message queue với routing rules
  • AWS SQS — managed queue cho decoupling services
  • Event-driven architecture — producer → queue → consumer, xử lý async
Single Queue:                  Kafka (Distributed Log):
┌───────────────────┐     ┌────────────────────────────────┐
│  → [A][B][C][D] → │     │  Topic: "orders"               │
└───────────────────┘     │                                │
                          │  Partition 0: [A][D][G][J]...  │
                          │  Partition 1: [B][E][H][K]...  │
                          │  Partition 2: [C][F][I][L]...  │
                          │                                │
                          │  3 Consumer Groups đọc song    │
                          │  song → throughput x3          │
                          └────────────────────────────────┘

Tại sao Kafka dùng append-only log?

Queue thông thường: message bị xóa sau khi consumer đọc. Kafka giữ lại toàn bộ messages (configurable retention) — cho phép:

  • Replay: consumer mới có thể đọc lại từ đầu
  • Multiple consumers: mỗi consumer group track offset riêng
  • Audit trail: mọi event được lưu trữ

Đây chính là ý tưởng immutable append-only data structure — tương tự cách bạn implement queue bằng array với head/tail pointer, nhưng không bao giờ xóa.

🎯 Interview Crossover Question

"Design a notification system that sends push notifications, emails, and SMS."

DSA cần: Queue (FIFO processing), Priority Queue (urgent notifications first). System Design cần: Message broker (decouple senders/receivers), fan-out pattern, retry with dead-letter queue.


6. Dynamic Programming → Resource Optimization

DSA Recap

DP = tối ưu hóa bằng cách nhớ kết quả đã tính. Hai cách tiếp cận: top-down (memoization) và bottom-up (tabulation). Pattern cốt lõi: optimal substructure + overlapping subproblems.

Production Equivalent

DP xuất hiện ở những nơi bạn không ngờ:

  • Query optimizer — database query planner dùng DP để tìm optimal join order cho multi-table queries
  • Resource allocation — cloud instance sizing (variant của knapsack problem)
  • Ad bidding — maximize revenue với budget constraint
  • CDN cache — chọn content nào cache ở edge location nào (knapsack variant)
DP: 0/1 Knapsack                  Production: Query Optimizer
┌───────────────────────┐    ┌──────────────────────────────────┐
│ Items: [(w=2,v=3),    │    │ Tables: [Users, Orders, Items]   │
│         (w=3,v=4),    │    │                                  │
│         (w=4,v=5)]    │    │ Join Orders:                     │
│ Capacity: 5           │    │   (Users ⋈ Orders) ⋈ Items      │
│                       │    │   (Users ⋈ Items) ⋈ Orders      │
│ DP table tìm max      │    │   (Orders ⋈ Items) ⋈ Users      │
│ value = 7             │    │                                  │
│ (items 1+2)           │    │ DP tìm join order có cost thấp   │
│                       │    │ nhất dựa trên table sizes và     │
└───────────────────────┘    │ available indexes                │
                             └──────────────────────────────────┘

PostgreSQL EXPLAIN và DP

Khi bạn chạy EXPLAIN ANALYZE trên một query phức tạp, PostgreSQL internally dùng DP (với n ≤ ~12 tables) hoặc genetic algorithm (n > 12) để tìm execution plan tối ưu. Mỗi sub-plan = subproblem, kết quả được cache để tránh tính lại.

🎯 Interview Crossover Question

"How does a database optimize a multi-table JOIN query?"

DSA cần: DP cho optimal join ordering (subproblem = subset of tables, optimal cost to join that subset). System Design cần: Statistics (table sizes, cardinality), index selection, cost model.


7. Sorting → External Sort

DSA Recap

Merge Sort chạy O(n log n), hoạt động tốt với sequential access — không cần random access vào dữ liệu. Đây là lý do nó được chọn cho external sorting.

Production Equivalent

Khi dữ liệu lớn hơn RAM, sorting trở thành bài toán I/O:

  • MapReduce sort phase — mỗi mapper sort locally, reducer merge
  • External merge sort — chia file thành chunks vừa RAM, sort từng chunk, merge từ disk
  • Database ORDER BY — khi result set lớn, spill to disk và merge sort
Data: 1TB          RAM: 16GB

Step 1 — Chunk & Sort:
┌────────┐ ┌────────┐ ┌────────┐     ┌────────┐
│ 16GB   │ │ 16GB   │ │ 16GB   │ ... │ 16GB   │  ← 64 chunks
│ chunk  │ │ chunk  │ │ chunk  │     │ chunk  │
│ (sort) │ │ (sort) │ │ (sort) │     │ (sort) │
└───┬────┘ └───┬────┘ └───┬────┘     └───┬────┘
    │          │          │               │
Step 2 — K-way Merge:
    └──────────┴──────┬───┴───────────────┘

            ┌──────────────────┐
            │  Min-Heap (K=64) │  ← mỗi lần extract-min
            │  merge K streams │    từ heap, đọc phần tử
            └────────┬─────────┘    tiếp theo từ chunk đó

            ┌──────────────────┐
            │  Sorted 1TB file │
            └──────────────────┘

K-way Merge = Heap!

Bước merge dùng min-heap với K phần tử (mỗi phần tử là head của 1 sorted chunk). Extract-min → ghi vào output → đọc phần tử tiếp theo từ chunk đó → insert vào heap. Tổng: O(N log K) với K = số chunks.

Phase 1 dạy bạn heap và merge sort riêng lẻ. Production kết hợp cả hai.

🎯 Interview Crossover Question

"How would you sort 1TB of data with only 16GB RAM?"

DSA cần: External merge sort (divide into chunks, sort in-memory, k-way merge with heap). System Design cần: Disk I/O optimization, parallel processing, fault tolerance (checkpoint giữa các merge pass).


8. Binary Search → Distributed Lookup

DSA Recap

Binary search = O(log n) trên dữ liệu đã sắp xếp. Mỗi bước loại bỏ một nửa search space.

Production Equivalent

Ý tưởng "chia đôi để tìm nhanh" xuất hiện khắp nơi:

  • Consistent hashing ring — binary search tìm server chịu trách nhiệm cho key
  • Load balancer — weighted round-robin dùng binary search trên cumulative weights
  • Version resolution — npm/pip tìm compatible version range bằng binary search
  • Feature flags — gradual rollout dùng binary search trên user ID ranges
Weighted Load Balancer:

Servers:  [A: w=5] [B: w=3] [C: w=2]
Cumulative: [5, 8, 10]

Random(1..10) = 6
Binary search trên [5, 8, 10]:
  → 6 > 5, 6 ≤ 8 → Server B!

  ┌─────────┬──────┬────┐
  │ A (50%) │B(30%)│C(20%)│
  └─────────┴──────┴────┘
  0    5    8   10

Mỗi request: O(log K) thay vì O(K)
với K = số servers

Git Bisect — Binary Search trong thực tế

git bisect là ứng dụng trực tiếp nhất: tìm commit gây bug trong hàng nghìn commits bằng binary search. O(log n) commits cần test thay vì O(n). Với 1000 commits → chỉ ~10 lần test.

🎯 Interview Crossover Question

"How does a load balancer with weighted routing distribute traffic efficiently?"

DSA cần: Binary search trên sorted cumulative weight array. System Design cần: Health checks, failover khi server chết, dynamic weight adjustment.


Interview Strategy — Khi nào reference DSA trong System Design?

💡 HPN Pro Tip

Trong system design interview, khi bạn nói "tôi sẽ dùng Redis cho caching" — hãy thêm: "Redis internally uses hash table with O(1) lookup, and we can use LRU eviction which is a doubly linked list + hash map combination." Điều này cho thấy bạn hiểu SÂU, không chỉ biết tên công nghệ.

4 thời điểm vàng để reference DSA

Thời điểmVí dụHiệu quả
Chọn data store"B+ Tree index cho range queries, hash index cho point lookups"Giải thích tại sao chọn technology
Thiết kế algorithm"Consistent hashing dùng binary search trên ring"Chứng minh hiểu implementation
Phân tích bottleneck"JOIN 5 tables = DP problem, optimizer cần O(2ⁿ)"Quantify complexity
Đề xuất optimization"Priority queue cho task scheduling thay vì polling"Cải thiện từ O(n) → O(log n)

Khi KHÔNG nên reference DSA

  • Đừng biến system design interview thành buổi giảng thuật toán
  • Đừng nói "tôi sẽ implement B-Tree từ đầu" — dùng PostgreSQL
  • Focus vào trade-offs, không phải implementation details
  • DSA là foundation, không phải trọng tâm

Tổng kết Phase 1 — Hành trình của bạn

Nhìn lại toàn bộ Phase 1, mỗi bài đều xây nền cho bài tiếp theo:

BàiChủ đềDSA SkillSystem Design Connection
00Bản đồ lộ trìnhTổng quan
01Sorting O(n²)Bubble, Selection, InsertionComparison-based fundamentals
02Sorting EfficientMerge Sort, Quick SortExternal sort, distributed sort
03SearchingBinary SearchDistributed lookup, load balancing
04Linear DSArray, List, Stack, QueueCache (LRU), Message broker
05Non-linear DSTree, Heap, GraphDatabase index, scheduler, service graph
06Graph AlgorithmsBFS, DFS, DijkstraService discovery, shortest path routing
07DP IntroMemoization, TabulationQuery optimization, resource allocation
08Interview TrapsCommon mistakes
09DSA→System DesignBridgeBẠN Ở ĐÂY ✅

Phase 1 Dependency Map

00 Bản đồ
 └► 01 Sorting O(n²)
     └► 02 Sorting Efficient
         └► 03 Searching
             └► 04 Linear DS
                 └► 05 Trees / Heaps / Graphs
                     └► 06 BFS / DFS / Dijkstra
                         └► 07 DP Intro
                             └► 08 Interview Traps
                                 └► 09 DSA → System Design ✅ BẠN Ở ĐÂY

What's Next? — Phase 2 Preview

Phase 1 cho bạn nền tảng. Phase 2 đi sâu hơn:

Phase 2 DSA (Nâng cao)

  • Knapsack variants — 0/1, unbounded, fractional
  • LCS / LIS — Longest Common Subsequence, Longest Increasing Subsequence
  • Bitmask DP — state compression cho NP-hard problems
  • Tree DP — DP trên cấu trúc cây
  • Advanced Graph — MST (Kruskal, Prim), Network Flow, Strongly Connected Components

System Design Track

  • Thiết kế hệ thống cụ thể: URL Shortener, Chat System, News Feed
  • Distributed systems patterns: CAP theorem, consensus, sharding
  • Hands-on: từ whiteboard → implementation

Practice

  • Mock interviews kết hợp DSA + System Design
  • Real-world case studies từ FAANG
  • Competitive programming challenges

🧠 Quiz — Kiểm tra kiến thức cầu nối

🧠 Quiz

Câu 1: Interviewer hỏi: "Design a URL shortener." Bạn cần kiến thức DSA nào?

  • [ ] A. Hash Table — cho mapping short code → original URL
  • [ ] B. B-Tree Index — cho persistent storage lookup
  • [ ] C. Queue — cho async analytics processing
  • [x] D. Tất cả các đáp án trên

Giải thích: URL shortener cần Hash Table (hash function tạo short code, in-memory cache cho hot URLs), B-Tree Index (database index cho billions of URLs), và Queue (message queue cho async click analytics, không block redirect response). Đây là ví dụ điển hình của câu hỏi crossover — một system design problem mà mọi component đều root từ DSA.

🧠 Quiz

Câu 2: Tại sao PostgreSQL dùng B+ Tree thay vì Binary Search Tree cho index?

  • [ ] A. BST nhanh hơn B+ Tree
  • [x] B. B+ Tree tối ưu disk I/O — mỗi node = 1 disk page, depth thấp hơn
  • [ ] C. BST không hỗ trợ range queries
  • [ ] D. B+ Tree dùng ít bộ nhớ hơn BST

Giải thích: B+ Tree có branching factor lớn (hàng trăm keys mỗi node), nên depth chỉ ~3-4 cho hàng triệu records. Mỗi node align với disk page (4KB), giảm thiểu disk I/O. BST có branching factor = 2, depth ~20 cho cùng dữ liệu → 20 disk reads vs 3-4. Lưu ý: BST cũng hỗ trợ range queries (in-order traversal), nên C không đúng.

🧠 Quiz

Câu 3: Team bạn phát hiện 2 microservices gọi lẫn nhau (A→B→A). Thuật toán DSA nào giúp detect vấn đề này tự động?

  • [ ] A. BFS
  • [x] B. DFS-based cycle detection
  • [ ] C. Dijkstra
  • [ ] D. Topological Sort

Giải thích: Circular dependency = cycle trong directed graph. DFS-based cycle detection (dùng 3 trạng thái: white/gray/black) phát hiện back edge = cycle. Topological sort cũng detect cycle (nếu không thể sort = có cycle), nhưng DFS cycle detection là phương pháp trực tiếp và hiệu quả hơn. BFS không detect cycle trên directed graph một cách tự nhiên.


🎯 Scenario Challenge

Tình huống: Bạn đang thiết kế hệ thống e-commerce. Trong buổi system design interview, interviewer hỏi từng component. Hãy map mỗi component với DSA concept phù hợp nhất:

ComponentMô tảDSA Concept
Product searchTìm sản phẩm theo tên, filter theo giáB+ Tree (range queries trên price index)
Shopping cartTra cứu nhanh items trong cartHash Table (O(1) lookup by product ID)
Order processingXử lý orders theo thứ tựQueue (FIFO processing)
Flash saleƯu tiên VIP customersPriority Queue / Heap (VIP orders extract first)
RecommendationTìm shortest path giữa user preferencesGraph (collaborative filtering = graph traversal)
Inventory allocationMaximize profit với limited stockDP (variant of knapsack)
Caching hot productsCache top 1000 productsHash Table + LRU (distributed cache)

Liên kết học tiếp


📍 Hoàn thành Phase 1!

🎉 Chúc mừng bạn!

Bạn đã hoàn thành toàn bộ Phase 1 DSA của Penalgo. Từ Bubble Sort đến System Design Bridge — bạn không chỉ học thuật toán, bạn đã hiểu tại sao chúng tồn tại và ở đâu chúng được dùng trong production.

Phase 1 cho bạn nền tảng. Phase 2 sẽ cho bạn chiều sâu. System Design track sẽ cho bạn bức tranh toàn cảnh.

Hãy quay lại Practice Hub để luyện tập, hoặc xem lại Bản đồ Phase 1 khi cần. 🚀