Skip to content

Part 11: Networking & Serialization HFT Grade

Every microsecond counts. Module này chuyển đổi kỹ sư từ "Socket Chat App" sang "Microservices với gRPC/Protobuf" — tiêu chuẩn của HPN Tunnel, Trading Engines, và Game Servers.

Performance Profile Analysis (@[/perf-profile])

Trước khi bắt đầu, hãy hiểu tại sao chúng ta cần module này:

┌─────────────────────────────────────────────────────────────────────────┐
│                    SERIALIZATION BENCHMARK                               │
├─────────────────────────────────────────────────────────────────────────┤
│   Message: LoginRequest { username: "hpn_user", password: "***" }       │
│                                                                         │
│   Format          Size (bytes)    Serialize    Deserialize    Total     │
│   ──────────────  ──────────────  ───────────  ─────────────  ────────  │
│   JSON            67 bytes        850 µs       920 µs         1.77 ms   │
│   Protobuf        24 bytes        45 µs        38 µs          83 µs     │
│                                                                         │
│   Improvement:    2.8x smaller    19x faster   24x faster     21x faster│
│                                                                         │
│   At 100K req/s:  JSON = 177 seconds CPU time                           │
│                   Protobuf = 8.3 seconds CPU time                       │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

⚠️ HPN ENGINEERING RULE

JSON is STRICTLY PROHIBITED cho internal backend-to-backend communication.

Text parsing overhead phá hủy latency budgets. Trong HFT: 1ms delay = $1M potential loss.


The C10K Problem (@[/architect])

Vấn đề cổ điển

Năm 1999, Dan Kegel đặt câu hỏi: "Làm thế nào để 1 server xử lý 10,000 concurrent connections?"

┌─────────────────────────────────────────────────────────────────────────┐
│                    C10K PROBLEM VISUALIZATION                            │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   BLOCKING I/O (Thread-per-Connection):                                 │
│   ─────────────────────────────────────                                 │
│                                                                         │
│   Client 1 ──► [Thread 1] ──► Waiting for data... (BLOCKED)             │
│   Client 2 ──► [Thread 2] ──► Waiting for data... (BLOCKED)             │
│   Client 3 ──► [Thread 3] ──► Waiting for data... (BLOCKED)             │
│   ...                                                                   │
│   Client 10000 ──► [Thread 10000] ──► Waiting... (BLOCKED)              │
│                                                                         │
│   📊 Resource Usage:                                                    │
│   • 10,000 threads × 1MB stack = 10GB RAM (chỉ cho stacks!)            │
│   • Context switch overhead = CPU thrashing                             │
│   • Scheduler overwhelmed                                               │
│                                                                         │
│   ❌ KHÔNG SCALE ĐƯỢC!                                                  │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Giải pháp: Event-Driven Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                    EVENT-DRIVEN I/O (Reactor Pattern)                    │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│   Client 1 ──┐                                                          │
│   Client 2 ──┤     ┌─────────────────────────────────┐                  │
│   Client 3 ──┼────►│       EVENT LOOP                │                  │
│   ...        │     │   (epoll/kqueue/IOCP)           │                  │
│   Client 10K ┘     │                                 │                  │
│                    │   "Wake me when data ready"     │                  │
│                    └─────────────────────────────────┘                  │
│                              │                                          │
│                              ▼                                          │
│                    ┌─────────────────────────────────┐                  │
│                    │  Worker Thread Pool (4-8 threads)│                 │
│                    │  Only process READY connections │                  │
│                    └─────────────────────────────────┘                  │
│                                                                         │
│   📊 Resource Usage:                                                    │
│   • 4-8 threads × 1MB = 8MB RAM                                         │
│   • No context switch overhead                                          │
│   • O(1) event notification (epoll)                                     │
│                                                                         │
│   ✅ Examples: Nginx (10M+ connections), Node.js, HPN Tunnel           │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Architecture Patterns Comparison

PatternConnectionsLatencyComplexityUse Case
Thread-per-connection~100HighLowLearning/Prototypes
Thread Pool~1,000MediumMediumTraditional web servers
Reactor (epoll/kqueue)~100,000Very LowHighNginx, HPN Tunnel
Proactor (io_uring)~1,000,000LowestVery HighCutting-edge Linux 5.1+

🎯 HPN TECHNOLOGY CHOICE

Module này tập trung vào Reactor Pattern với Boost.Asio — được sử dụng trong production tại HPN Tunnel và các trading systems.

Lý do:

  • Cross-platform (Windows IOCP, Linux epoll, macOS kqueue)
  • Mature, battle-tested (15+ years)
  • C++ native, zero overhead abstraction

The Technology Stack


Module Structure

Bài họcNội dung chínhWorkflow
📦 SerializationProtobuf vs JSON, .proto files@[/perf-profile]
🔌 gRPC FrameworkRPC, Service definition, Async server@[/api-design]
⚡ Async I/OEvent Loop, Boost.Asio, Coroutines@[/architect]
🛡️ Production PatternsZero-copy, Load testing, TLS, Security@[/security-scan]

Prerequisites

Trước khi học module này, bạn cần:


Learning Path

  1. 📦 Serialization — Hiểu data format trước
  2. 🔌 gRPC Framework — Transport layer
  3. Async I/O — The engine underneath
  4. 🛡️ Production Patterns — Battle-tested techniques

HPN Tunnel Insight

💡 PRODUCTION SECRET

Trong HPN Tunnel, chúng tôi áp dụng:

  • Zero-copy buffers: Data di chuyển từ NIC → App memory mà không cần CPU copy
  • Memory pool: Pre-allocated buffers để tránh malloc() trong hot path
  • Lock-free queues: Tránh mutex contention giữa threads
  • Batch processing: Xử lý nhiều packets cùng lúc để amortize syscall overhead

Những kỹ thuật này sẽ được đề cập trong bài Production Patterns.