Chuyển đến nội dung chính

Bài 1: Cloud Native là gì? — Nguyên lý và Twelve-Factor App

Định nghĩa Cloud Native theo CNCF, so sánh Traditional vs Cloud Native, phương pháp luận Twelve-Factor App, và tại sao Cloud Native là xu hướng tất yếu cho ứng dụng hiện đại.

🏗️ Kiến trúc — Bài 1 Bài 1: Cloud Native là gì? — Nguyên lý và Twelve-Factor App

Cloud Native Microservices Architecture

Phần 1: Cloud Native Foundations

xdev.asia

Bài 1: Cloud Native là gì? — Nguyên lý và Twelve-Factor App

Giới thiệu

Cloud computing đã thay đổi hoàn toàn cách chúng ta xây dựng và vận hành phần mềm. Nhưng việc đơn thuần chạy ứng dụng trên cloud không đồng nghĩa với "Cloud Native". Bài học này giúp bạn hiểu rõ Cloud Native thực sự nghĩa là gì, tại sao nó quan trọng, và các nguyên lý nền tảng mà mọi kỹ sư cần nắm vững.


1. Cloud Native là gì?

1.1 Định nghĩa theo CNCF

Theo Cloud Native Computing Foundation (CNCF) — tổ chức quản lý các dự án như Kubernetes, Prometheus, Envoy:

Cloud native technologies empower organizations to build and run scalable applications in modern, dynamic environments such as public, private, and hybrid clouds. Containers, service meshes, microservices, immutable infrastructure, and declarative APIs exemplify this approach.

Nói đơn giản: Cloud Native là phương pháp tiếp cận xây dựng ứng dụng tận dụng tối đa lợi thế của cloud computing.

1.2 Các đặc trưng cốt lõi

Cloud Native Application
├── Containerized          → Đóng gói nhất quán, portable
├── Dynamically Orchestrated → Kubernetes tự động quản lý
├── Microservices-oriented  → Chia nhỏ, độc lập, dễ scale
├── Loosely Coupled         → Ít phụ thuộc lẫn nhau
├── Resilient              → Tự phục hồi khi có lỗi
├── Observable             → Giám sát toàn diện (metrics, logs, traces)
└── Automated              → CI/CD, IaC, GitOps

1.3 Cloud Native ≠ "Chạy trên Cloud"

Một ứng dụng chạy trên AWS EC2 nhưng vẫn là monolith, deploy thủ công, không có auto-scaling — không phải Cloud Native.

Ngược lại, một ứng dụng chạy trên on-premise Kubernetes cluster với đầy đủ container, CI/CD, observability — đó là Cloud Native.

Cloud Native là về cách bạn xây dựng và vận hành, không phải nơi bạn chạy.


2. So sánh Traditional vs Cloud Native

Đặc điểmTraditionalCloud Native
Kiến trúcMonolithicMicroservices
Triển khaiVM / Bare metalContainer / Kubernetes
ScalingVertical (scale up)Horizontal (scale out)
Release cycleHàng tháng / quýHàng ngày / hàng giờ
Failure handlingTránh failure bằng mọi giáChấp nhận failure, tự phục hồi
InfrastructureMutable (cập nhật tại chỗ)Immutable (thay thế hoàn toàn)
StateStateful serversStateless services + External state
ConfigurationFile config trên serverEnvironment variables / ConfigMap
NetworkingIP cố địnhDynamic DNS, Service Discovery
MonitoringReactive (xảy ra mới biết)Proactive (metrics, alerts, traces)

Ví dụ thực tế

Traditional approach:

Developer → Build WAR → Gửi cho Ops → Ops deploy lên Tomcat trên VM
→ Cần scale? Mua thêm server, cài đặt thủ công
→ Server die? Downtime cho đến khi fix xong

Cloud Native approach:

Developer → Git push → CI/CD tự động build container image
→ ArgoCD sync → Kubernetes deploy 3 replicas
→ Cần scale? HPA tự thêm pod
→ Pod die? Kubernetes tự restart trong giây

3. Tại sao Cloud Native?

3.1 Business drivers

  • Time-to-market: Deploy tính năng mới trong giờ thay vì tuần
  • Scalability: Xử lý traffic spike (Black Friday, flash sale) tự động
  • Cost efficiency: Scale down khi không cần, chỉ trả tiền cho những gì sử dụng
  • Innovation speed: Các team phát triển độc lập, song song

3.2 Technical drivers

  • Fault isolation: Lỗi ở service A không kéo sập toàn bộ hệ thống
  • Technology diversity: Mỗi service có thể dùng ngôn ngữ/framework phù hợp nhất
  • Independent deployment: Cập nhật service A mà không cần redeploy service B
  • Resource optimization: CPU/Memory được allocate chính xác cho từng workload

4. The Twelve-Factor App

Phương pháp luận Twelve-Factor App (12factor.net) được Heroku đề xuất năm 2011, là nền tảng lý thuyết cho Cloud Native application design.

4.1 Tổng quan 12 factors

Factor 1: Codebase

Một codebase duy nhất được quản lý bởi version control, triển khai nhiều môi trường.

Git Repository (1 codebase)
├── Deploy → Development
├── Deploy → Staging
└── Deploy → Production

Quy tắc: Một app = một repo. Nếu có shared code, tách thành library.

Factor 2: Dependencies

Khai báo và cô lập dependencies rõ ràng.

// package.json — khai báo rõ ràng
{
  "dependencies": {
    "express": "4.18.2",
    "pg": "8.11.0"
  }
}

Không bao giờ dựa vào system-level packages đã cài sẵn trên server.

Factor 3: Config

Lưu cấu hình trong environment variables.

# ✅ Đúng: Config qua env vars
DATABASE_URL=postgresql://user:pass@host:5432/db
REDIS_URL=redis://cache:6379
API_KEY=sk-xxx

# ❌ Sai: Hardcode trong source code
const DB_HOST = "192.168.1.100";

Factor 4: Backing Services

Xử lý backing services như attached resources.

App ──attach──▶ PostgreSQL (có thể thay bằng RDS bất cứ lúc nào)
App ──attach──▶ Redis (có thể thay bằng ElastiCache)
App ──attach──▶ S3 (có thể thay bằng MinIO)

Thay đổi backing service = thay đổi config, không thay đổi code.

Factor 5: Build, Release, Run

Tách biệt hoàn toàn build, release và run stages.

Build Stage:   Source code → Executable (Docker image)
Release Stage: Image + Config → Versioned release (v1.2.3)
Run Stage:     Launch release trong execution environment

Factor 6: Processes

Chạy ứng dụng dưới dạng stateless processes.

# ✅ Stateless: Session lưu ở Redis
Request → App Instance 1 ──session──▶ Redis
Request → App Instance 2 ──session──▶ Redis

# ❌ Stateful: Session lưu trong memory
Request → App Instance 1 (session ở đây)
Request → App Instance 2 (không có session!) ← BUG

Factor 7: Port Binding

Export services qua port binding.

Application tự chứa HTTP server (không cần external Tomcat/Apache):

const app = express();
app.listen(process.env.PORT || 8080);

Factor 8: Concurrency

Scale out thông qua process model.

Thay vì 1 process lớn dùng 16 cores:
├── Web process × 4 (handle HTTP requests)
├── Worker process × 8 (background jobs)
└── Clock process × 1 (scheduled tasks)

Factor 9: Disposability

Khởi động nhanh, shutdown gracefully.

Startup:  < 5 giây (lý tưởng < 1 giây)
Shutdown: SIGTERM → hoàn thành request đang xử lý → close connections → exit

Factor 10: Dev/Prod Parity

Giữ development, staging và production giống nhau nhất có thể.

# ✅ Dev dùng PostgreSQL, Prod dùng PostgreSQL
# ❌ Dev dùng SQLite, Prod dùng PostgreSQL
# ❌ Dev dùng file system, Prod dùng S3

Docker Compose giúp đạt dev/prod parity.

Factor 11: Logs

Xử lý logs như event streams.

Application → stdout/stderr → Log collector (Fluent Bit) → Loki/Elasticsearch

Application không bao giờ quản lý log files. Chỉ viết ra stdout.

Factor 12: Admin Processes

Chạy admin/management tasks như one-off processes.

# Database migration
kubectl exec -it order-service-pod -- ./manage.py migrate

# Data cleanup
kubectl run --rm -it cleanup --image=myapp -- python cleanup_script.py

4.2 Beyond Twelve Factors

Kevin Hoffman trong cuốn "Beyond the Twelve-Factor App" bổ sung thêm 3 factors:

  • Factor 13: API First — Thiết kế API contract trước, implement sau
  • Factor 14: Telemetry — Metrics, logs, traces là yêu cầu bắt buộc
  • Factor 15: Authentication & Authorization — Security by design, không phải afterthought

5. Cloud Native Landscape

CNCF duy trì Cloud Native Landscape — bản đồ toàn bộ công nghệ Cloud Native:

┌─────────────────────────────────────────────────────────────┐
│                    Cloud Native Landscape                    │
├───────────────┬──────────────┬───────────────┬──────────────┤
│ App Definition│ Orchestration│  Runtime      │  Provisioning│
│ & Development │ & Management │               │              │
│               │              │               │              │
│ - Helm       │ - Kubernetes │ - containerd  │ - Terraform  │
│ - gRPC       │ - Istio      │ - CRI-O      │ - Ansible    │
│ - OpenAPI    │ - ArgoCD     │ - Envoy      │ - Crossplane │
│ - Dapr       │ - Keda       │ - CoreDNS    │ - Pulumi     │
├───────────────┼──────────────┼───────────────┼──────────────┤
│ Observability │ Serverless   │  Security     │  Database    │
│               │              │               │              │
│ - Prometheus │ - Knative    │ - Vault      │ - Vitess     │
│ - Grafana    │ - OpenFaaS   │ - Falco      │ - TiDB       │
│ - Jaeger     │ - Dapr       │ - OPA        │ - CockroachDB│
│ - Loki       │              │ - Trivy      │              │
└───────────────┴──────────────┴───────────────┴──────────────┘

6. Tổng kết

ConceptTakeaway
Cloud NativePhương pháp xây dựng ứng dụng tận dụng cloud, không chỉ là chạy trên cloud
Twelve-Factor12 nguyên lý thiết kế ứng dụng portable, scalable, production-ready
Immutable InfrastructureKhông sửa server, thay thế hoàn toàn
Stateless DesignState ở external service, app instance có thể thay thế bất kỳ lúc nào
Observable by DefaultMetrics, logs, traces là yêu cầu bắt buộc từ đầu

Bài tiếp theo: Container & Docker — Nền tảng đóng gói ứng dụng Cloud Native, từ Dockerfile best practices đến image security.