
Mục Tiêu Series
- Học cách xây 1 REST API service production-ready bằng Rust + axum theo phong cách Zero-To-Production: workspace nhiều crate, sqlx compile-time check, JWT + OAuth2, tower middleware (CORS / rate limit / cache / security), tracing + OpenTelemetry + Prometheus, test pyramid (unit / integration / e2e / load), Docker multi-stage + CI/CD. Đầu ra: tự build và deploy 1 service Rust thật, hiểu mọi quyết định kiến trúc, sẵn sàng phỏng vấn Rust backend hoặc đảm nhận microservice hot path ở team production.
Prerequisites
- ✅ Hoàn thành series Rust Cơ Bản (hoặc tương đương)
- ✅ Nắm vững ownership / borrow / lifetime / trait / generic
- ✅ Đã viết được async/await + tokio basic (spawn, channel, select)
- ✅ Hiểu Result / Option / ? / anyhow / thiserror
- ✅ Quen cargo workspace + features + dev-deps
- 📝 Kinh nghiệm HTTP/REST ở ngôn ngữ khác (Node / Go / Python) — helpful
- 📝 SQL cơ bản (SELECT / JOIN / INDEX) — sẽ ôn nhanh
- 📝 Docker cơ bản (build / run / compose) — sẽ giới thiệu lại
Ai Nên Học Series Này?
- Backend Engineer Node / Python / Go / Java muốn chuyển sang Rust cho hot path low latency
- Rust developer đã xong cơ bản, cần lộ trình build service production thật thay vì hello-world
- SRE / DevOps muốn viết internal API, control plane, operator bằng Rust
- Founder / Tech lead startup chọn Rust làm core stack, cần blueprint workspace + deploy
- Sinh viên / fresher muốn portfolio Rust backend đủ độ thực tế để apply job
- Người đã đọc "Zero To Production In Rust" của Luca Palmieri, muốn version tiếng Việt + cập nhật 2026
Ứng Dụng Sau Khi Học
- Tự build 1 REST API production-ready: auth + DB + cache + queue + observability + deploy
- Đánh giá / refactor codebase axum hiện có theo chuẩn workspace nhiều crate
- Thiết kế middleware stack production (CORS, rate limit, security header, request-id, trace)
- Triển khai JWT + OAuth2 (Google / GitHub) + RBAC / ABAC đúng chuẩn RFC
- Vận hành observability: structured log + Prometheus metric + OpenTelemetry tracing
- Setup test pyramid Rust: unit + integration (testcontainers) + e2e + load (k6) + chaos
- Đóng gói + deploy: Docker multi-stage + cargo-chef + fly.io / Railway / Kubernetes
Thời Gian Học
- Ước tính: 10-12 tuần
- Tổng số bài: ~316 bài học
- Thời lượng mỗi bài: 9-12 phút (capstone 12-15 phút)
- Thực hành: 2-3 giờ/ngày
- Pace khuyến nghị: ~30 bài/tuần
- 5 Capstone projects cuối series: 1-2 tuần
Tools & Công Nghệ
- Rust 1.85+ edition 2024 (stable)
- axum 0.8+ (tower-based web framework)
- tokio 1.40+ multi-thread runtime
- sqlx 0.8+ compile-time SQL check
- PostgreSQL 16+ và Redis 7+ (Docker)
- tracing + OpenTelemetry + Prometheus + Grafana + Loki
- Docker multi-stage + cargo-chef + GitHub Actions CI
- JWT (jsonwebtoken), oauth2, argon2, validator, utoipa, apalis
Tài Nguyên Tham Khảo
Cấu Trúc Mỗi Bài
- 📖 Mục Tiêu Bài Học: 4-6 thứ sẽ nắm được
- 📚 Khái niệm / Lý thuyết: RFC, pattern, lý do design
- 🧭 State Hiện Tại: recap code shop project đến bài trước
- 💻 Thực Hành Trên Shop: code + file path (
crates/shop-xxx/src/...) - 🧪 Test / Run:
cargo run -p shop-api+ curl + expected output - 🐛 Pitfall / Best Practice: gotcha production
- 🎯 Bài Tập Củng Cố: 5-6 câu + đáp án giấu
Capstone Projects (5)
- Multi-Tenant SaaS API (org_id, Postgres RLS, Stripe billing)
- Real-time chat với WebSocket + Redis pub/sub + presence
- GraphQL server với async-graphql + DataLoader + subscription
- gRPC service với tonic + streaming RPC + interceptor
- Scheduled job runner với distributed lock + dashboard + audit log
Series Trước
- Rust Cơ Bản - 316 bài, prereq bắt buộc. Cover ownership, borrow, lifetime, trait, generic, error handling, async/await, tokio basic. Nếu chưa xong, học series này trước rồi mới quay lại.
- (Coming) Rust Thực Chiến - Kafka consumer, advanced gRPC, WebSocket nâng cao, plugin system, FFI với C, build cho WASM target.
Dự Án Xuyên Suốt: Shop API (E-commerce)
Toàn series xây dựng một dự án duy nhất: shop — REST API e-commerce production-ready với khoảng 60 endpoints và 17 bảng PostgreSQL. Mỗi bài thêm / sửa code incremental trên cùng codebase, mô phỏng đúng quy trình build real-world product. Không có "tutorial code" — mọi thứ bạn viết đều là code sẽ dùng được trong service production thật.
Domain model: Users (customer + admin), Categories (hierarchical), Products (SKU, variants, inventory), Cart, Orders (state machine), Payments (Stripe-like webhook), Inventory (reservation + restock), Reviews, Notifications (email + WebSocket), Audit log, Idempotency keys, Sessions.
Workspace 7 crate:
shop-api- binary axum HTTP server (port 3000, routes / handlers / middleware / extractors)shop-core- library domain logic, entity, service, repository trait (pure, no infra)shop-db- library PostgreSQL adapter sqlx, impl repository traitshop-cache- library Redis adapter (fred / redis-rs): session, cache, distributed lockshop-worker- binary apalis background worker (email, inventory, analytics)shop-cli- binary admin CLI (seed, user-create, ...)shop-common- library shared utility (config, error, telemetry, pagination)
Danh Sách Bài Học (32 Nhóm - 316 Bài)
1. REST & HTTP Foundation
- B1 - REST là gì? Khái niệm và lịch sử
- B2 - HTTP Methods: GET / POST / PUT / PATCH / DELETE
- B3 - HTTP Status Codes: 2xx / 3xx / 4xx / 5xx
- B4 - HTTP Headers cần biết
- B5 - Content Negotiation: Accept / Content-Type / Vary
- +5 bài: JSON format, REST vs RPC vs GraphQL, OpenAPI/Swagger, curl/HTTPie/Postman, setup project Rust API
2. Axum Overview
- B11 - axum là gì? Sinh ra từ đâu
- B12 - Hello World với axum
- B13 - Route handler — function signature
- B14 - Response types: String / Html / Json / StatusCode
- B15 - JSON serialization với serde + axum::Json
- +5 bài: error response pattern, project structure, async + tokio, axum-extra, hệ sinh thái tower/hyper
3. Routing Cơ Bản
- B21 - Route methods: GET / POST / PUT / DELETE / PATCH
- B22 - Path parameters với Path<T>
- B23 - Query parameters với Query<T>
- B24 - Nested routes — Router::nest
- B25 - Route merge & fallback handler
- +5 bài: route ordering, redirect / static, route với State, route_layer vs layer, API versioning
4. Extractors Và Response Sâu
- B31 - Extractor trait — bản chất
- B32 - Custom extractor (CurrentUser)
- B33 - Header extractor typed (TypedHeader)
- B34 - Cookie extractor: plain / signed / private
- B35 - Form extractor cho HTML form
- +5 bài: multipart upload, raw body/bytes, streaming body, Extension extractor, response builder pattern
5. JSON, Body, Streaming
- B41 - JSON extract + validation (validator crate)
- B42 - Field optional, default, skip null
- B43 - Enum serialization: tagged / untagged / adjacent
- B44 - DateTime / UUID / Decimal trong JSON
- B45 - Custom serializer / deserializer
- +5 bài: rename/alias, body size limit, gzip/brotli, chunked encoding, SSE
6. PostgreSQL & sqlx Setup
- B51 - PostgreSQL overview cho Rust dev
- B52 - Cài PostgreSQL bằng Docker
- B53 - sqlx là gì? Compile-time check
- B54 - sqlx-cli — migration & schema tool
- B55 - Cargo.toml: sqlx features
- +5 bài: connection pool, query! macro, query_as!, FromRow derive, config DATABASE_URL
7. CRUD Cơ Bản
- B61 - CRUD mapping REST ↔ SQL
- B62 - Create resource: POST + INSERT
- B63 - Read by ID: GET /users/:id
- B64 - List resources với pagination
- B65 - Update PUT — replace resource
- +5 bài: PATCH partial, hard vs soft delete, UUID vs sequence, RETURNING clause, integration test testcontainers
8. sqlx Nâng Cao
- B71 - Transaction cơ bản với sqlx
- B72 - Nested transaction với savepoint
- B73 - Isolation level (Read Committed → Serializable)
- B74 - Type mapping: PG ↔ Rust
- B75 - JSONB column với typed struct
- +5 bài: array column, bulk insert, optimistic lock, LISTEN/NOTIFY, custom Postgres type
9. Migration & Schema
- B81 - Migration strategy cho production
- B82 - sqlx migrate add / run / revert
- B83 - Idempotent migration — safe re-run
- B84 - Foreign key constraint
- B85 - Index: B-tree / Hash / GIN / GiST
- +5 bài: partial index, view & materialized, schema versioning, breaking change, rollback plan
10. Query Builder & ORM
- B91 - sqlx QueryBuilder cho dynamic SQL
- B92 - sea-query — standalone query builder
- B93 - sea-orm — async ORM
- B94 - diesel — sync ORM truyền thống
- B95 - sqlx vs ORM — decision matrix
- +5 bài: pagination offset vs cursor, full-text search tsvector, dynamic filter, sort multi-field, query log & slow query
11. Authentication Basic
- B101 - Authentication trong REST API
- B102 - Password hashing với bcrypt
- B103 - Password hashing với argon2 (modern)
- B104 - Register flow: validate / hash / save
- B105 - Login flow với session cookie
- +5 bài: signed/encrypted cookie, CSRF protection, email verification, password reset, account lockout
12. JWT Authentication
- B111 - JWT là gì? RFC 7519
- B112 - jsonwebtoken crate cho Rust
- B113 - JWT HS256 — symmetric signing
- B114 - JWT RS256 — asymmetric signing
- B115 - Standard claims: iss / sub / aud / exp / iat / nbf / jti
- +5 bài: custom claims/role, refresh token, blacklist & revoke, key rotation, security pitfall
13. OAuth2 & OIDC
- B121 - OAuth 2.0 overview — RFC 6749
- B122 - Authorization Code flow detail
- B123 - PKCE extension cho mobile/SPA
- B124 - oauth2 crate cho Rust
- B125 - Google Login integration
- +5 bài: GitHub login, refresh OAuth, OpenID Connect, scope handling, custom OAuth provider preview
14. Authorization & RBAC
- B131 - AuthN vs AuthZ — phân biệt
- B132 - RBAC: Role-Based Access Control
- B133 - Permission-based: granular
- B134 - ABAC: Attribute-Based Access
- B135 - Casbin cho Rust authorization
- +5 bài: route-level guard, resource-level check, policy testing, audit log auth, JWT scope extractor
15. Tower Middleware Cơ Bản
- B141 - tower::Service trait — bản chất
- B142 - tower::Layer trait
- B143 - axum::middleware::from_fn
- B144 - from_fn_with_state
- B145 - Layer ordering — onion model
- +5 bài: error handling middleware, request modify, response transform, conditional middleware, composition
16. Production Middleware
- B151 - CORS với tower-http
- B152 - TraceLayer — request logging
- B153 - CompressionLayer — gzip / brotli
- B154 - Body limit layer
- B155 - Timeout layer
- +5 bài: sensitive header strip, request-id, X-Forwarded-*, security headers (HSTS/CSP), full middleware chain example
17. Rate Limit & Throttling
- B161 - Rate limit — algorithms overview
- B162 - tower-governor crate
- B163 - Per-IP rate limit
- B164 - Per-user rate limit (authenticated)
- B165 - Distributed rate limit với Redis
- +5 bài: Retry-After header, burst strategy, exempt list, monitoring rate limit, DDoS protection basics
18. Caching
- B171 - Cache overview — tradeoff
- B172 - moka — in-memory cache
- B173 - Cache-aside (lazy loading)
- B174 - Write-through vs write-back
- B175 - Cache key design — naming convention
- +5 bài: TTL strategy, invalidation, ETag conditional GET, cache stampede, monitoring hit rate
19. Redis Basics
- B181 - Redis overview cho Rust dev
- B182 - Cài Redis bằng Docker
- B183 - redis-rs crate cho Rust
- B184 - Redis connection pool (bb8 / deadpool)
- B185 - Redis string commands
- +5 bài: hash, list/queue, set/sorted set, pub/sub, streams
20. Session & Cache Patterns Với Redis
- B191 - Session store trong Redis
- B192 - tower-sessions với Redis store
- B193 - Cache-aside implementation
- B194 - Write-through implementation
- B195 - Single flight — stampede mitigation
- +5 bài: distributed lock (Redlock), idempotency key, idempotency impl, leaderboard ZSet, rate limit cluster
21. Background Jobs
- B201 - Background jobs — tại sao cần
- B202 - Apalis — job queue cho Rust
- B203 - Enqueue job từ axum handler
- B204 - Retry policy: exponential backoff
- B205 - Dead letter queue pattern
- +5 bài: worker process binary, cron schedule, idempotent job, monitoring job, alternative queue (RabbitMQ/NATS/Kafka)
22. Logging
- B211 - tracing recap cho web service
- B212 - tracing-subscriber formatter (pretty / json / compact)
- B213 - Structured log fields
- B214 - Log level strategy
- B215 - Sensitive data masking trong log
- +5 bài: log aggregation (Loki/ELK), rotation stdout, error stack trace anyhow, request/response logging, log correlation request-id
23. Metrics
- B221 - Metrics overview: RED / USE
- B222 - metrics crate + Prometheus exporter
- B223 - Counter / Gauge / Histogram
- B224 - Label cardinality — pitfall
- B225 - request_duration_seconds histogram
- +5 bài: error rate, business metrics, Prometheus + Grafana setup, alert rule, SLO/SLI tracking
24. Distributed Tracing
- B231 - OpenTelemetry overview
- B232 - Trace context propagation — W3C
- B233 - Jaeger / Tempo backend setup
- B234 - Instrument axum handler với #[instrument]
- B235 - Custom span attribute
- +5 bài: sampling strategy, cross-service trace, trace-log correlation, baggage, tracing best practices
25. Health & Profile
- B241 - Health endpoint pattern (/health, /healthz)
- B242 - Readiness vs liveness probe
- B243 - Dependency check: DB / Redis / external
- B244 - Public status page endpoint
- B245 - Smoke test endpoint sau deploy
- +5 bài: debug endpoint security, flamegraph, memory profile jemalloc, tokio-metrics, production readiness checklist
26. Unit + Integration Test
- B251 - Test strategy cho axum app
- B252 - Unit test pure handler
- B253 - axum-test crate — test server
- B254 - Integration test real HTTP (reqwest)
- B255 - testcontainers: Postgres + Redis
- +5 bài: mock State trait object, factory pattern, golden file (insta), parameterized (rstest), tx rollback test
27. E2E & Contract Test
- B261 - E2E test với Docker Compose
- B262 - OpenAPI generation với utoipa
- B263 - Contract test với Pact
- B264 - Schema validation test
- B265 - Regression test suite
- +5 bài: performance test criterion, load test k6, chaos test toxiproxy, fuzz test cargo-fuzz, test data cleanup
28. Test Best Practices
- B271 - Test pyramid revisited cho API
- B272 - Test isolation — independent test
- B273 - Parallel test execution
- B274 - Test DB strategy: template database
- B275 - AAA pattern: Arrange / Act / Assert
- +5 bài: fixture vs builder, mock vs real, test data hygiene, CI parallelization, flaky test debug
29. Configuration & Secrets
- B281 - Config overview — 12-Factor App
- B282 - config crate — multi-source
- B283 - dotenvy load .env cho dev
- B284 - Secret management: Vault, AWS SecretsManager
- B285 - Feature flag — toggle runtime
- +5 bài: env-specific config, hot reload, runtime override env, secret rotation, anti-pattern hardcode
30. Docker & Deployment
- B291 - Dockerfile multi-stage cho Rust
- B292 - Distroless image — security & size
- B293 - cargo-chef — cache dependency layer
- B294 - docker-compose dev stack
- B295 - HEALTHCHECK Docker & K8s
- +5 bài: signal handling SIGTERM, graceful shutdown axum, fly.io/Railway/Render, Kubernetes preview, blue-green & canary
31. CI/CD & Monitoring
- B301 - GitHub Actions workflow cho Rust API
- B302 - Cache cargo build trong CI
- B303 - Test parallel CI: matrix strategy
- B304 - Docker build & push to registry
- B305 - Deploy via SSH / rsync (bare metal)
- +5 bài: semantic release & versioning, rollback strategy, monitoring stack (Prom + Grafana + Loki), Alertmanager routing, SLO error budget tracking
32. Capstone Projects
- B311 - Capstone 1: Multi-tenant SaaS API (Postgres RLS)
- B312 - Capstone 2: Real-time chat WebSocket + Redis pub/sub
- B313 - Capstone 3: GraphQL server với async-graphql
- B314 - Capstone 4: gRPC service với tonic
- B315 - Capstone 5: Scheduled job runner service
- B316 - Tổng kết series — checklist + career path Rust backend
Tips Học Hiệu Quả
- Code song song theo Shop project: Không học chay. Mỗi bài clone repo Shop, gõ tay theo bài, chạy
cargo run -p shop-api+ curl endpoint thật. Đầu hàng = bỏ lỡ trải nghiệm Zero-To-Production. - Commit theo từng bài: Series gợi ý commit message kiểu
B62: thêm endpoint POST /products. Git log của bạn sẽ là portfolio sống động cho phỏng vấn. - Đừng skip nhóm 11-14 (auth): Auth là phần nhiều ứng viên Rust backend làm sai. JWT pitfall, OAuth PKCE, RBAC schema phải nắm trước khi nhảy production.
- Setup Postgres + Redis bằng Docker từ ngày đầu: Đừng cài local.
docker-compose up1 lệnh, isolate môi trường, tái lập được cho team. - Bật
cargo sqlx preparetrước CI: sqlx compile-time check yêu cầu DATABASE_URL hoặc offline cache. Bỏ qua = CI fail build. - Observability là first-class: Đừng để cuối series mới làm log/metric/trace. Bật từ B1 (cấu hình tracing), dần thêm layer khi học sâu hơn.
- Test pyramid nghiêm túc: 70% unit + 20% integration + 10% e2e. Đừng dồn vào e2e — chậm + flaky. Mock state qua trait object là kỹ năng phải có.
- Đọc PR thực tế của tokio-rs/axum: Issue + PR open giúp bạn hiểu trade-off design framework. Cách học sâu nhất sau official docs.
Lộ Trình Học Tập (10-12 Tuần)
Tuần 1: REST & HTTP foundation + Axum overview (Bài 1 - 20)
├── REST 6 constraint, HTTP method / status / header
├── JSON, OpenAPI, content negotiation
└── Hello-world axum, handler, response type, project structure
Tuần 2: Routing + Extractor + Response (Bài 21 - 50)
├── Path / Query / nested / merge / fallback / versioning
├── Custom extractor, cookie, multipart, streaming
└── JSON validate, body limit, compression, SSE
Tuần 3: PostgreSQL + sqlx + CRUD cơ bản (Bài 51 - 70)
├── Docker Postgres, sqlx-cli, connection pool
├── query! / query_as! / FromRow
└── CRUD Shop entity: User, Product, Category — testcontainers
Tuần 4: sqlx nâng cao + Migration + Query builder (Bài 71 - 100)
├── Transaction, isolation, JSONB, array, bulk insert
├── Migration strategy, idempotent, index, view
└── Pagination, full-text search, dynamic filter, slow query
Tuần 5: Authentication + JWT + OAuth2 + RBAC (Bài 101 - 140)
├── argon2 hashing, session cookie, CSRF
├── JWT HS256/RS256, refresh token, blacklist
└── OAuth2 (Google, GitHub), RBAC + ABAC, Casbin
⚠️ Tuần quan trọng — sai auth = security incident
Tuần 6: Tower Middleware + Rate Limit + Caching + Redis (Bài 141 - 200)
├── tower Service / Layer / from_fn, layer ordering
├── CORS, compression, timeout, security headers
├── tower-governor, distributed rate limit Redis
└── moka, cache-aside, Redis session, idempotency key
Tuần 7: Background Jobs + Logging + Metrics (Bài 201 - 230)
├── Apalis worker, retry policy, DLQ, cron
├── tracing structured log, Loki aggregation
└── Prometheus metric, RED/USE, alert rule, SLO
Tuần 8: Distributed Tracing + Health + Testing (Bài 231 - 280)
├── OpenTelemetry, Jaeger, span attribute, sampling
├── Health / readiness / liveness, flamegraph, jemalloc
├── Unit + integration + axum-test + testcontainers
└── E2E + contract (Pact) + criterion + k6 + chaos
Tuần 9: Configuration + Secrets + Docker + Deployment (Bài 281 - 300)
├── 12-factor config, config crate, dotenvy, Vault
├── Dockerfile multi-stage, distroless, cargo-chef
└── docker-compose, graceful shutdown, fly.io / K8s, canary
Tuần 10: CI/CD + Monitoring stack (Bài 301 - 310)
├── GitHub Actions, cache cargo, parallel test matrix
├── Docker build push GHCR/ECR, semantic release
└── Prometheus + Grafana + Loki + Alertmanager + SLO
Tuần 11-12: Capstone Projects (Bài 311 - 316)
├── Multi-tenant SaaS (RLS) + WebSocket chat + GraphQL
├── gRPC tonic + Scheduled job runner
└── Tổng kết — 50-item production checklist + career path
Yêu Cầu Trước Khi Bắt Đầu
- Đã hoàn thành series Rust Cơ Bản hoặc tương đương — nắm chắc ownership / borrow / lifetime / trait / generic / async / tokio basic. Series này KHÔNG dạy lại Rust syntax cơ bản.
- Cài sẵn: Rust toolchain stable (1.85+), Docker Desktop / Engine, VS Code + rust-analyzer (hoặc RustRover),
cargo install sqlx-cli. - Biết SQL cơ bản (SELECT, JOIN, INDEX, transaction) — nếu chưa, đọc nhanh PostgreSQL Tutorial trước khi tới nhóm 6.
- Biết Docker cơ bản: build image, docker-compose up, network giữa container. Series có refresh ở nhóm 30 nhưng không từ zero.
- GitHub repo riêng để commit Shop project — embed commit hash vào quá trình học giúp ôn lại sau.
Sau Khi Xong Series
- Bạn sẽ có 1 codebase Shop API thật (~60 endpoint, 17 bảng, 7 crate workspace) trên GitHub — portfolio tốt cho phỏng vấn Rust backend.
- Hiểu mọi layer của 1 web service production: HTTP / routing / extract / validate / DB / cache / queue / auth / middleware / observability / test / deploy / CI-CD.
- 5 Capstone projects mở rộng: Multi-tenant SaaS (Postgres RLS + Stripe), WebSocket chat (Redis pub/sub), GraphQL (async-graphql + DataLoader), gRPC (tonic + streaming), Scheduled job runner (distributed lock).
- Sẵn sàng đảm nhận microservice Rust ở team production, hoặc tự khởi tạo backend cho startup riêng.
- Tiếp theo có thể đi sâu: event sourcing + CQRS, Kafka consumer, microservice mesh (Linkerd / Istio), hoặc tham gia open-source axum / sqlx / tokio.
