Kiến Trúc Hệ Thống Thực Dụng
Từ request đầu tiên đến hệ thống production hiện đại
Tinh thần của cuốn sách này: học kiến trúc để xây được hệ thống chạy thật, đo được, debug được, scale được, và không tự làm phức tạp khi chưa cần. Công nghệ, pattern và framework chỉ là công cụ; điều quan trọng là hiểu vấn đề, nhận ra bottleneck, chọn đúng mức phức tạp, và biết khi nào phải tiến hóa kiến trúc.
---
Phần I. Nền Tảng Chạy Thật Của Một Hệ Thống
Chương 1. Một request đi qua hệ thống như thế nào
- Client, DNS, CDN, reverse proxy, load balancer
- Web server và application server
- Database, cache, queue, object storage
- Request/response path trong một ứng dụng thật
- Các điểm có thể nghẽn trên đường đi
Chương 2. Process, thread, event loop và coroutine
- Process là gì và vì sao nó nặng
- Thread là gì và vì sao nó phù hợp I/O-bound
- Event loop hoạt động như thế nào
- Coroutine, greenlet, fiber, virtual thread
- So sánh process-based, thread-based và event-driven runtime
- Python, Node.js, Java, C#, PHP xử lý concurrency khác nhau thế nào
Chương 3. Blocking, non-blocking, sync và async
- Blocking call là gì
- Non-blocking I/O là gì
- Synchronous execution và asynchronous execution
- Async/await giải quyết vấn đề gì
- Khi async không giúp ích
- Khi async làm hệ thống khó debug hơn
- Vì sao thư viện sync bên trong async có thể làm kẹt toàn bộ event loop
Chương 4. I/O-bound, CPU-bound và workload thật
- Network I/O, disk I/O, database I/O
- CPU-bound khác I/O-bound thế nào
- Gọi API ngoài, upload file, xử lý video, chấm AI, generate báo cáo
- Chọn process, thread, async hay worker queue theo workload
- Sai lầm khi dùng cùng một runtime cho mọi loại việc
Chương 5. Latency, throughput và concurrency
- Latency là gì
- Throughput là gì
- Concurrency là gì
- Little's Law theo cách dễ hiểu
- Queueing delay
- Backpressure
- Capacity planning cơ bản
- Tính nhanh cần bao nhiêu worker/concurrency cho một workload dài
Chương 6. Bottleneck và cách tìm bottleneck
- CPU saturation
- RAM pressure
- Database connection pool
- Slow query
- External API latency
- Queue backlog
- Network timeout
- Đừng đổi kiến trúc khi chưa biết nghẽn ở đâu
---
Phần II. Kiến Trúc Ứng Dụng Trước Khi Nói Đến Microservices
Chương 7. Monolith không xấu
- Monolith là gì
- Vì sao monolith giúp đi nhanh
- Monolith tốt và monolith xấu
- Khi nào monolith đủ tốt
- Khi nào monolith bắt đầu gây đau
- Over-engineering vì sợ monolith
Chương 8. Layered Architecture thực dụng
- Presentation layer
- Application layer
- Domain layer
- Infrastructure layer
- Controller, service, repository
- Tách business logic khỏi framework
- Fat controller, fat model, god service
- Khi nào layer làm code sạch hơn, khi nào chỉ làm rườm rà
Chương 9. Modular Monolith
- Modular monolith là gì
- Module boundary
- Public interface giữa các module
- Internal import và coupling
- Shared database nhưng không shared lung tung
- Cách viết module để sau này có thể tách service
- Tách logic trước, tách runtime sau
Chương 10. Domain-Driven Design vừa đủ
- Domain, subdomain, bounded context
- Entity, value object, aggregate, aggregate root
- Domain service và application service
- Domain event
- Ubiquitous language
- DDD để chia ranh giới, không phải để làm code màu mè
Chương 11. Transaction boundary và consistency boundary
- Database transaction
transaction.atomicvà các cơ chế tương đương- Isolation level
- Locking
- Optimistic locking và pessimistic locking
- Khi nào một thao tác phải atomic
- Khi nào chấp nhận eventual consistency
- Vì sao boundary nghiệp vụ quan trọng hơn boundary bảng dữ liệu
Chương 12. Service layer và application workflow
- Service layer giải quyết vấn đề gì
- Command handler và use case
- Input validation, domain rule, side effect
- Tách read path và write path khi cần
- Workflow tuyến tính, workflow phân nhánh
- Khi nào cần state machine hoặc workflow engine
---
Phần III. Giao Tiếp Trong Hệ Thống
Chương 13. HTTP API thực dụng
- REST và JSON API
- Status code
- Timeout
- Retry
- Idempotent method
- Pagination, filtering, sorting
- API versioning
- OpenAPI
- Khi nào HTTP là đủ
Chương 14. RPC và gRPC
- RPC là gì
- gRPC và Protocol Buffers
- HTTP/2
- Unary call
- Streaming call
- Contract chặt và performance
- Khi nào gRPC đáng dùng
- Vì sao gRPC không phải mặc định tốt hơn REST
Chương 15. Polling, Long Polling, SSE và WebSocket
- Polling
- Long polling
- Server-Sent Events
- WebSocket
- Realtime notification
- Progress update
- Scaling WebSocket
- Khi nào polling đủ tốt
- Khi nào WebSocket là cần thiết
Chương 16. Webhook
- Webhook là gì
- Callback URL
- Signature verification
- Retry webhook
- Idempotency key
- Webhook timeout
- Xử lý webhook bị mất hoặc bị gửi trùng
- Webhook khác message queue thế nào
Chương 17. Message Queue
- Producer, consumer, broker, queue
- Work queue pattern
- Acknowledgement
- Visibility timeout
- Retry
- Dead letter queue
- Competing consumers
- Queue backlog
- Backpressure
- Vì sao job dài không nên xử lý trong request HTTP
Chương 18. Publish/Subscribe
- Topic và subscriber
- Fan-out
- Event broadcasting
- Durable và non-durable subscription
- Redis Pub/Sub
- Notification realtime
- Pub/Sub khác task queue thế nào
- Khi nào không được dùng Pub/Sub cho job quan trọng
Chương 19. Event Streaming
- Event log
- Append-only log
- Partition
- Offset
- Consumer group
- Replay
- Retention
- Kafka và các hệ tương tự
- Khi nào Kafka là hợp lý
- Khi nào Kafka là quá mức
Chương 20. Event-Driven Architecture
- Command vs event
- Domain event vs integration event
- Event schema
- Event versioning
- Choreography vs orchestration
- Outbox pattern
- Inbox pattern
- Eventual consistency trong hệ thống hướng sự kiện
Chương 21. Enterprise Integration Patterns vừa đủ
- Message channel
- Message router
- Message translator
- Splitter
- Aggregator
- Resequencer
- Idempotent receiver
- Dead letter channel
- Correlation ID
---
Phần IV. Worker, Queue Và Xử Lý Nền
Chương 22. Background job
- Job, task, worker
- Delayed job
- Scheduled job
- Periodic job
- Long-running job
- Job state
- Job result
- Job cancellation
- Khi nào dùng job thay vì request synchronous
Chương 23. Worker pool và concurrency
- Worker process
- Worker thread
- Worker greenlet
- Worker coroutine
- Worker concurrency
- Prefetch
- Autoscaling worker
- Worker shutdown
- Worker isolation
- Chọn concurrency theo CPU-bound và I/O-bound
Chương 24. Retry, timeout và idempotency
- Retryable error và non-retryable error
- Exponential backoff
- Jitter
- Timeout bắt buộc
- Idempotency key
- At-least-once delivery
- At-most-once delivery
- Exactly-once illusion
- Vì sao retry có thể phá dữ liệu nếu không idempotent
Chương 25. Rate limiting và quota management
- Rate limit theo user
- Rate limit theo service
- Rate limit theo provider API
- Token bucket
- Leaky bucket
- Distributed rate limit
- Global quota
- Backoff khi bị 429
- Không để retry storm làm chết hệ thống
Chương 26. Queue design trong production
- Tách queue theo loại workload
- Priority queue
- Dead letter queue
- Poison message
- Queue age
- Queue length
- Worker saturation
- Monitoring queue
- Khi nào cần nhiều broker hoặc nhiều cluster
Chương 27. Workflow engine
- Workflow tuyến tính
- Workflow phân nhánh
- DAG
- State machine
- Celery canvas, Temporal, Airflow
- Khi nào workflow engine giúp ích
- Khi nào workflow engine là quá nặng
---
Phần V. Microservices Thực Dụng
Chương 28. Microservices thật sự là gì
- Service boundary
- Independent deployment
- Independent scaling
- Database ownership
- Failure isolation
- Team ownership
- Microservices khác modular monolith thế nào
- Microservices không phải mặc định tốt hơn
Chương 29. Khi nào nên tách service
- Tách vì tải
- Tách vì failure isolation
- Tách vì dữ liệu
- Tách vì bảo mật
- Tách vì team/deployment cadence
- Tách vì domain thay đổi độc lập
- Những lý do không nên tách
- Checklist trước khi tách service
Chương 30. Service granularity
- Service quá to
- Service quá nhỏ
- Coupling và cohesion
- Chatty services
- Distributed monolith
- Architecture quantum
- Connascence vừa đủ
- Cách tìm ranh giới service thực dụng
Chương 31. Database per service
- Service sở hữu dữ liệu là gì
- Vì sao không join database service khác
- API composition
- Data duplication
- Read model
- Materialized view
- Local cache dữ liệu service khác
- Chi phí của database per service
Chương 32. Distributed transactions
- Vì sao transaction phân tán khó
- Two-phase commit
- Saga pattern
- Compensating transaction
- Orchestration saga
- Choreography saga
- Outbox + saga
- Khi nào nên tránh transaction phân tán bằng cách đổi nghiệp vụ
Chương 33. API Gateway và Backend for Frontend
- API gateway
- Backend for Frontend
- Routing
- Authentication ở gateway
- Rate limiting ở gateway
- Request aggregation
- Gateway anti-pattern
- Khi nào không cần gateway riêng
Chương 34. Service discovery và configuration
- Service registry
- Client-side discovery
- Server-side discovery
- DNS-based discovery
- Config management
- Feature flag
- Secret injection
- Environment-specific config
Chương 35. Resilience patterns
- Timeout
- Retry with backoff
- Circuit breaker
- Bulkhead
- Rate limiter
- Fallback
- Load shedding
- Graceful degradation
- Cascading failure
Chương 36. Contract và compatibility
- API contract
- OpenAPI
- Protobuf schema
- JSON Schema
- Consumer-driven contract testing
- Backward compatibility
- Schema evolution
- Breaking change
- Versioning strategy
Chương 37. Tách monolith thành services
- Strangler Fig pattern
- Extract by capability
- Extract by data ownership
- Parallel run
- Dual write và rủi ro
- Backfill dữ liệu
- Cutover
- Rollback plan
- Đừng tách khi chưa có monitoring
---
Phần VI. Dữ Liệu Và Lưu Trữ
Chương 38. Relational database
- PostgreSQL/MySQL
- Schema design
- Primary key, foreign key, constraint
- Index
- Query plan
- Migration
- Connection pool
- Transaction và lock
- Khi nào database là bottleneck
Chương 39. Replication và high availability
- Leader-follower replication
- Multi-leader replication
- Replication lag
- Read replica
- Failover
- Split brain
- Backup và restore
- Data loss window
Chương 40. Partitioning và sharding
- Vertical partitioning
- Horizontal partitioning
- Shard key
- Hot shard
- Rebalancing
- Cross-shard query
- Global ID
- Khi nào thật sự cần sharding
Chương 41. NoSQL vừa đủ
- Document database
- Key-value store
- Wide-column store
- Graph database
- Data model theo access pattern
- Consistency trade-off
- NoSQL không phải cách né thiết kế dữ liệu
Chương 42. Cache
- Cache-aside
- Read-through
- Write-through
- Write-back
- TTL
- Cache invalidation
- Cache stampede
- Distributed cache
- Redis patterns
- Khi nào cache làm hệ thống sai dữ liệu
Chương 43. Search
- Full-text search
- Inverted index
- Elasticsearch/OpenSearch
- Ranking
- Filtering
- Facet
- Sync database sang search index
- Search consistency
- Khi nào không cần search engine riêng
Chương 44. File và object storage
- Local filesystem
- Object storage
- Presigned URL
- Multipart upload
- CDN
- Metadata
- Virus scanning
- Lifecycle policy
- Không lưu file lớn trong database
Chương 45. Analytics storage
- OLTP vs OLAP
- Data warehouse
- Columnar storage
- ClickHouse, BigQuery, Redshift
- Data lake
- ETL/ELT
- Batch analytics
- Streaming analytics
- Tách dữ liệu vận hành khỏi dữ liệu phân tích
Chương 46. Distributed data fundamentals
- Consistency model
- CAP theorem theo cách thực dụng
- Consensus
- Leader election
- Distributed lock
- Clock và ordering
- Id generation
- Khi nào cần hiểu sâu các thứ này
---
Phần VII. Bảo Mật Và Định Danh
Chương 47. Authentication
- Session
- Cookie
- JWT
- OAuth2
- OpenID Connect
- Access token
- Refresh token
- Token rotation
- Login flow trong web app hiện đại
Chương 48. Authorization
- RBAC
- ABAC
- ACL
- Policy-based authorization
- Object-level permission
- Multi-tenant authorization
- Permission caching
- Audit authorization decision
Chương 49. Service-to-service security
- API key
- mTLS
- JWT giữa services
- Client credentials
- Internal network không có nghĩa là an toàn
- Secret management
- Key rotation
- Zero trust vừa đủ
Chương 50. Web security thực dụng
- HTTPS
- CORS
- CSRF
- XSS
- SQL injection
- SSRF
- File upload attack
- Rate limiting
- Audit log
- Security headers
Chương 51. Multi-tenancy
- Tenant là gì
- Single database, shared schema
- Single database, separate schema
- Database per tenant
- Tenant isolation
- Tenant-aware permission
- Noisy neighbor
- Backup/restore theo tenant
---
Phần VIII. Triển Khai Và Hạ Tầng
Chương 52. Linux và networking cơ bản
- Process, port, socket
- TCP/UDP
- DNS
- TLS
- Firewall
- Systemd
- File descriptor
- Log file
- Những lệnh cần biết khi production có vấn đề
Chương 53. Reverse proxy và load balancer
- Nginx, Caddy, HAProxy
- Layer 4 vs Layer 7
- Health check
- TLS termination
- Request buffering
- Sticky session
- Load balancing algorithm
- Timeout ở proxy
Chương 54. Container
- Docker image
- Docker container
- Dockerfile
- Layer cache
- Volume
- Network
- Docker Compose
- Image registry
- Production pitfalls với container
Chương 55. CI/CD
- Build pipeline
- Test pipeline
- Artifact
- Deployment strategy
- Rolling deploy
- Blue-green deploy
- Canary deploy
- Rollback
- Database migration trong deploy
Chương 56. Kubernetes vừa đủ
- Pod
- Deployment
- Service
- Ingress
- ConfigMap
- Secret
- Volume
- Job/CronJob
- HPA
- Khi nào chưa cần Kubernetes
- Vì sao Kubernetes không tự làm app của bạn scale tốt
Chương 57. Service mesh
- Sidecar proxy
- mTLS
- Traffic shifting
- Retry ở mesh
- Observability ở mesh
- Istio, Linkerd
- Khi nào service mesh giúp ích
- Khi nào service mesh là quá mức
Chương 58. Cloud services
- Compute
- Managed database
- Managed cache
- Managed queue
- Object storage
- CDN
- Serverless function
- Container service
- Managed Kubernetes
- Managed service vs self-host
---
Phần IX. Observability Và Reliability
Chương 59. Logging
- Structured log
- Log level
- Correlation ID
- Centralized logging
- Log sampling
- Sensitive data trong log
- Log retention
- Log để debug, không phải để trang trí
Chương 60. Metrics
- Counter
- Gauge
- Histogram
- Percentile
- p50, p95, p99
- RED metrics
- USE metrics
- Golden signals
- Prometheus và Grafana
Chương 61. Distributed tracing
- Trace
- Span
- Context propagation
- OpenTelemetry
- Trace sampling
- Trace qua HTTP
- Trace qua message queue
- Debug request chậm trong hệ nhiều service
Chương 62. Alerting và SLO
- SLI
- SLO
- SLA
- Error budget
- Alert fatigue
- Alert theo symptom
- Alert theo saturation
- Runbook cho alert
Chương 63. Performance testing
- Load test
- Stress test
- Spike test
- Soak test
- Benchmark
- Bottleneck analysis
- Capacity planning nâng cao
- Đừng benchmark sai workload
Chương 64. Failure modes trong production
- Single point of failure
- Cascading failure
- Retry storm
- Thundering herd
- Partial outage
- Queue overload
- Database overload
- External provider outage
- Brownout và graceful degradation
Chương 65. Backup, restore và disaster recovery
- Backup strategy
- Restore test
- Point-in-time recovery
- RPO và RTO
- Disaster recovery
- Data integrity
- Backup không test restore thì chưa phải backup
---
Phần X. Testing Và Quality Trong Hệ Phân Tán
Chương 66. Test pyramid thực dụng
- Unit test
- Integration test
- Contract test
- End-to-end test
- Smoke test
- Regression test
- Test nào rẻ, test nào đắt
Chương 67. Integration testing
- Test database thật
- Test message broker thật
- Test external API bằng fake/mock
- Test containerized dependencies
- Test fixture
- Test data lifecycle
Chương 68. Contract testing
- Producer contract
- Consumer contract
- Consumer-driven contract
- Schema compatibility
- Backward compatibility
- Breaking change
- Contract test trong CI/CD
Chương 69. Testing async và event-driven systems
- Test queue consumer
- Test retry
- Test idempotency
- Test out-of-order event
- Test duplicate event
- Test missing event
- Test eventual consistency
Chương 70. Production verification
- Smoke test sau deploy
- Canary analysis
- Shadow traffic
- Feature flag
- Rollback verification
- Synthetic monitoring
- Testing in production một cách có kiểm soát
---
Phần XI. Kiến Trúc Theo Bài Toán Thực Tế
Chương 71. CRUD/SaaS application
- User, organization, role
- Billing
- Admin
- Audit log
- Background jobs
- Multi-tenancy
- Reporting
- Những phần thường bị đánh giá thấp
Chương 72. Marketplace
- Listing
- Booking/order
- Payment
- Payout
- Review
- Dispute
- Search
- Notification
- Trust and safety
Chương 73. Realtime application
- Chat
- Presence
- WebSocket scaling
- Pub/Sub backend
- Message persistence
- Delivery receipt
- Offline sync
- Push notification
Chương 74. Media processing system
- Upload
- Transcoding
- Thumbnail
- Metadata extraction
- Queue-based processing
- CDN delivery
- Retry failed jobs
- Cost control
Chương 75. AI application
- Model provider
- Prompt service
- Tool calling
- RAG
- Vector database
- Embedding pipeline
- Evaluation
- Prompt/model versioning
- Cost tracking
- Safety filtering
Chương 76. Job-heavy system
- Long-running jobs
- Worker scaling
- Progress update
- Job cancellation
- Queue visibility
- Result storage
- Partial failure
- Workflow orchestration
Chương 77. Analytics pipeline
- Event collection
- Stream processing
- Batch processing
- Warehouse
- Dashboard
- Data quality
- Backfill
- Replay
- Late-arriving events
---
Phần XII. Công Nghệ Hiện Đại Và Cách Chọn
Chương 78. Backend frameworks
- Django/DRF
- FastAPI
- Spring Boot
- ASP.NET Core
- NestJS
- Express/Fastify
- Go HTTP frameworks
- Rails/Laravel
- Chọn framework theo team, domain và workload
Chương 79. Message brokers
- Redis Queue/Streams
- RabbitMQ
- Kafka
- NATS
- SQS
- SNS
- EventBridge
- Chọn broker theo durability, throughput, replay và độ phức tạp
Chương 80. Databases
- PostgreSQL
- MySQL
- MongoDB
- Redis
- Elasticsearch/OpenSearch
- ClickHouse
- Cassandra
- Neo4j
- Chọn database theo access pattern
Chương 81. Observability stack
- OpenTelemetry
- Prometheus
- Grafana
- Loki
- ELK/OpenSearch
- Sentry
- Datadog/New Relic
- Self-host vs managed
Chương 82. AI infrastructure
- Model API provider
- Model gateway
- Vector database
- Embedding service
- GPU serving
- vLLM
- Ray Serve
- BentoML
- LLM observability
- Cost và latency trong AI systems
---
Phần XIII. Thiết Kế Hệ Thống Từ Đầu Đến Production
Chương 83. Phân tích yêu cầu kỹ thuật
- Workload
- Traffic pattern
- Latency target
- Consistency requirement
- Availability requirement
- Data size
- Growth assumption
- Failure mode
Chương 84. Back-of-the-envelope estimation
- Request per second
- Storage growth
- Bandwidth
- Worker concurrency
- Database connection
- Cache size
- Queue capacity
- Cost estimate
Chương 85. Chọn kiến trúc theo giai đoạn
- Prototype
- MVP
- Product-market fit
- Scale-up
- Enterprise
- Khi nào refactor
- Khi nào tách service
- Khi nào giữ nguyên cho khỏe
Chương 86. Migration và evolution
- Incremental refactor
- Schema migration
- Data backfill
- Dual write
- Parallel run
- Cutover
- Rollback
- Observability trước migration
Chương 87. Những lỗi kiến trúc phổ biến
- Microservices quá sớm
- Shared database giữa services
- Không có timeout
- Retry storm
- Queue không có dead letter
- Không có idempotency
- Không đo p95/p99
- Không có rollback plan
- Dùng công nghệ vì trend
Chương 88. Checklist production
- API
- Database
- Cache
- Queue
- Worker
- Security
- Deployment
- Observability
- Backup
- Scaling
- Cost
- Failure handling
---
Phần XIV. Bài Tập Thiết Kế Hệ Thống
Chương 89. URL shortener
- Redirect path
- Write path
- ID generation
- Cache
- Analytics
- Abuse prevention
Chương 90. Notification system
- Email, SMS, push
- Template
- Queue
- Retry
- Provider failover
- User preference
- Delivery tracking
Chương 91. Booking system
- Availability
- Calendar
- Timezone
- Reservation lock
- Payment hold
- Cancellation
- Conflict handling
Chương 92. Payment workflow
- Order
- Payment intent
- Webhook
- Idempotency
- Refund
- Payout
- Reconciliation
Chương 93. Video processing system
- Upload
- Transcode
- Queue
- Worker scaling
- CDN
- Progress update
- Failed job recovery
Chương 94. AI grading system
- Submission
- Job queue
- Worker concurrency
- Model provider
- Prompt versioning
- Evaluation
- Result callback
- Cost tracking
Chương 95. Realtime chat system
- WebSocket
- Presence
- Message persistence
- Delivery receipt
- Fan-out
- Offline message
- Scaling
Chương 96. Analytics pipeline
- Event schema
- Ingestion
- Stream processing
- Batch processing
- Warehouse
- Dashboard
- Backfill
- Replay
---
Phụ lục
Phụ lục A. Bảng chọn nhanh công nghệ
- Khi nào dùng REST
- Khi nào dùng gRPC
- Khi nào dùng queue
- Khi nào dùng Pub/Sub
- Khi nào dùng Kafka
- Khi nào dùng Redis
- Khi nào dùng PostgreSQL
- Khi nào dùng Kubernetes
Phụ lục B. Công thức tính nhanh
- Latency, throughput, concurrency
- Queue capacity
- Worker count
- Storage growth
- Bandwidth
- Availability
- Cost estimate
Phụ lục C. Thuật ngữ cần nắm
- Runtime
- Broker
- Worker
- Backpressure
- Idempotency
- Consistency
- Partition
- Replication
- SLO
- Trace
- Contract
Phụ lục D. Lộ trình học 12 tuần
- Tuần 1-2: Runtime, concurrency, HTTP, database
- Tuần 3-4: monolith, modular monolith, DDD vừa đủ
- Tuần 5-6: queue, worker, event-driven
- Tuần 7-8: microservices, distributed transactions, API gateway
- Tuần 9-10: observability, testing, reliability
- Tuần 11-12: system design case studies và production checklist