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

レッスン 19: サーバーレスおよびクラウドネイティブのアーキテクチャ

クラウドネイティブの原則 (12-Factor App)。サーバーレス コンピューティング: FaaS (Lambda、Cloud Functions)。コンテナオーケストレーションの概要。サーバーレス パターン: API ゲートウェイ + Lambda、イベント駆動型。コールド スタート、ベンダー ロックイン、およびサーバーレスを使用するタイミング。

🏗️ アーキテクチャ — レッスン 19 レッスン 19: サーバーレスとクラウドネイティブ 建築

システムアーキテクチャ: ゼロからヒーローへ

パート 5: アーキテクチャ パターン

xdev.asia

はじめに

クラウドはシステムの設計方法を変えました。物理サーバーを購入すると、インフラストラクチャを管理することなくコードを実行できるようになります。この記事では、クラウドネイティブの原則とサーバーレス アーキテクチャについて説明します。


1. 12-Factor アプリ

12 nguyên tắc thiết kế ứng dụng Cloud-Native:

 1. Codebase:    1 repo, nhiều deploys (staging, prod)
 2. Dependencies: Khai báo rõ ràng (package.json, requirements.txt)
 3. Config:      Lưu trong environment variables (không hardcode)
 4. Backing:     Database, cache, queue là attached resources
 5. Build/Release/Run: Tách biệt 3 stages
 6. Processes:   Stateless processes (không lưu state in-memory)
 7. Port binding: Self-contained, export via port
 8. Concurrency: Scale out bằng processes
 9. Disposability: Fast startup, graceful shutdown
10. Dev/Prod parity: Giữ dev, staging, prod giống nhau
11. Logs:        Treat logs as event streams (stdout)
12. Admin:       One-off admin tasks cũng là code

2. サーバーレス コンピューティング

2.1 FaaS (サービスとしての機能)

Traditional Server:
  ┌──────────────────────────┐
  │ Server (24/7 running)    │
  │ OS, Runtime, App         │
  │ Bạn quản lý TẤT CẢ      │
  │ Trả tiền 24/7            │
  └──────────────────────────┘

Container (CaaS):
  ┌──────────────────────────┐
  │ Container (on demand)    │
  │ Runtime, App             │
  │ Cloud quản lý OS, Infra  │
  │ Trả tiền khi container chạy │
  └──────────────────────────┘

Serverless (FaaS):
  ┌──────────────────────────┐
  │ Function (on invocation) │
  │ Chỉ viết code            │
  │ Cloud quản lý EVERYTHING │
  │ Trả tiền per invocation  │
  │ Auto scale 0 → ∞         │
  └──────────────────────────┘

2.2 実行モデル

Request 1: → Cold Start (init container) → Execute → Return
Request 2: → Warm (reuse container)       → Execute → Return
Request 3: → Warm (reuse container)       → Execute → Return
... (idle 15 min) ...
Request 4: → Cold Start (new container)   → Execute → Return

Cold Start Timeline:
  ├── Download code (100-500ms)
  ├── Init runtime (50-200ms)
  ├── Init dependencies (100-2000ms)
  ├── Execute function (varies)
  └── Total cold start: 500ms - 5s

Mitigation:
  - Provisioned concurrency (keep warm)
  - Smaller packages (fewer dependencies)
  - Choose fast runtimes (Go, Rust > Java, .NET)

3. サーバーレス パターン

3.1 API ゲートウェイ + Lambda

Client ──► API Gateway ──► Lambda ──► DynamoDB
                │
                ├──► /users  → UserFunction
                ├──► /orders → OrderFunction
                └──► /search → SearchFunction

Ưu điểm: Auto-scale, pay per request
Nhược điểm: Cold start, 15m timeout limit

3.2 イベント駆動型サーバーレス

┌──────────┐     ┌────────┐     ┌──────────┐
│ S3       │────►│ Lambda │────►│ DynamoDB │
│ Upload   │     │ Process│     │ Metadata │
└──────────┘     │ image  │     └──────────┘
                 └────┬───┘
                      │
                 ┌────▼───┐
                 │ S3     │
                 │ Thumb  │
                 └────────┘

Events trigger functions:
  - S3: File uploaded → Lambda resize
  - SQS: Message → Lambda process
  - DynamoDB Streams: Record change → Lambda sync
  - CloudWatch: Schedule → Lambda cron job
  - API Gateway: HTTP request → Lambda handler

3.3 サーバーレス Web アプリ

┌──────────────────────────────────────────────────┐
│                                                    │
│  CloudFront (CDN)                                 │
│       │                                            │
│  ┌────▼────┐                                      │
│  │ S3      │ ← Static files (React/Vue SPA)       │
│  │ Bucket  │                                       │
│  └─────────┘                                       │
│                                                    │
│  API Gateway → Lambda Functions                    │
│       │           │                                │
│       │      ┌────▼─────┐  ┌──────────┐           │
│       │      │ DynamoDB │  │ Cognito  │           │
│       │      │ (data)   │  │ (auth)   │           │
│       │      └──────────┘  └──────────┘           │
│       │                                            │
│  ┌────▼─────┐                                     │
│  │ SQS      │ → Lambda (background)               │
│  └──────────┘                                       │
└──────────────────────────────────────────────────┘

Chi phí (100K requests/tháng):
  Lambda: ~$0.20
  API Gateway: ~$3.50
  DynamoDB: ~$1.00
  S3 + CloudFront: ~$1.00
  Total: ~$6/tháng (vs EC2 ~$20+/tháng)

4. コンテナオーケストレーション

4.1 Kubernetes の概要

┌─────────────────────────────────────────────────┐
│ Kubernetes Cluster                               │
│                                                   │
│ Control Plane:                                    │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│ │API Server│ │Scheduler │ │Controller│          │
│ │          │ │          │ │Manager   │          │
│ └──────────┘ └──────────┘ └──────────┘          │
│                                                   │
│ Worker Nodes:                                     │
│ ┌────────────────────────────────────────┐        │
│ │ Node 1                                 │        │
│ │ ┌──────────┐ ┌──────────┐ ┌────────┐ │        │
│ │ │Pod: App-1│ │Pod: App-2│ │Pod: DB │ │        │
│ │ └──────────┘ └──────────┘ └────────┘ │        │
│ └────────────────────────────────────────┘        │
│ ┌────────────────────────────────────────┐        │
│ │ Node 2                                 │        │
│ │ ┌──────────┐ ┌──────────┐             │        │
│ │ │Pod: App-3│ │Pod: Cache│             │        │
│ │ └──────────┘ └──────────┘             │        │
│ └────────────────────────────────────────┘        │
└─────────────────────────────────────────────────┘

K8s quản lý: Scheduling, Scaling, Self-healing,
Rolling updates, Service discovery, Load balancing

4.2 サーバーレス vs コンテナ vs VM

特長VMコンテナサーバーレス
スタートアップ分秒ミリ秒*
スケーリングマニュアル/オート自動 (K8s)インスタント
管理フル (OS+アプリ)アプリ + ランタイムコードのみ
コストモデル1時間あたり1時間あたり呼び出しごと
最大実行時間無制限無制限15分
状態ステートフルステートフル無国籍
ベンダーロック低い低い高

5. サーバーレスをいつ使用するか?

✅ Dùng khi:
  - Event-driven workloads (file processing, webhooks)
  - Sporadic traffic (low/unpredictable)
  - Rapid prototyping
  - Scheduled tasks (cron jobs)
  - Chatbots, IoT backends
  - APIs with low-medium traffic

❌ KHÔNG dùng khi:
  - Consistent high traffic (vì cost cao hơn containers)
  - Long-running processes (> 15 minutes)
  - Need WebSocket/persistent connections
  - Heavy computation (ML training)
  - Latency-sensitive (cold start vấn đề)
  - Complex stateful workflows

6. ベンダーロックインの軽減

Vấn đề: AWS Lambda code khó chạy trên GCP/Azure

Mitigation:
  1. Serverless Framework / SAM / CDK:
     Abstract cloud-specific config

  2. Hexagonal Architecture:
     Business logic tách biệt handlers

     // Handler (cloud-specific)
     export const handler = async (event) => {
       return await orderService.createOrder(
         parseRequest(event)  // adapter
       );
     };

     // Business logic (portable)
     class OrderService {
       async createOrder(data) { ... }
     }

  3. Multi-cloud tools:
     Knative (serverless on K8s)
     OpenFaaS (self-hosted FaaS)

概要

アプローチ最適な用途トレードオフ
クラウド VMレガシー、ステートフルフルコントロール、高度な操作
コンテナ + K8マイクロサービス柔軟で複雑な運用
サーバーレス FaaSイベント駆動型の可変負荷シンプルなベンダーロック
サーバーレスコンテナ混合ワークロードバランス制御/シンプル

演習

  1. アーキテクチャの選択: スタートアップ SaaS: チーム 3、API + Web ダッシュボード、初期ユーザー 1,000 人、成長は不確実。比較: サーバーレス (Lambda + DynamoDB) とコンテナー (ECS/K8s + PostgreSQL)。どれを選びますか?

  2. 12 要素監査: 現在の (または想像上の) アプリケーションを確認します。 12 個の要素をチェックし、違反している要素とその修正方法をリストします。

  3. 移行計画: Monolith Spring Boot アプリ (10 エンドポイント、PostgreSQL、Redis、cron ジョブ)。サーバーレスへの移行計画を作成します。 Lambda に適したエンドポイントはどれですか?どちらがコンテナを保持すべきでしょうか?