จากซีรีส์ที่ผ่านมา เราเรียน Docker, Kubernetes, IaC, GitOps — แต่ทั้งหมดรันอยู่บน infrastructure ไม่ว่าจะเป็นเครื่องตัวเอง, VPS หรือ Cloud
วันนี้มาเรียนรู้ Cloud Architecture — วิธีออกแบบระบบบน Cloud ให้ แข็งแกร่ง, scale ได้, ปลอดภัย และคุ้มค่า ☁️🐕
☁️ Cloud Computing คืออะไร?
Cloud Computing คือการใช้ computing resources (servers, storage, databases, networking) ผ่าน internet แทนที่จะซื้อเครื่องเอง:
Cloud Service Models — IaaS / PaaS / SaaS
Cloud services แบ่งเป็น 3 ระดับตามว่า provider จัดการให้มากน้อยแค่ไหน — IaaS (Infrastructure as a Service) ให้ VM/storage มาเปล่าๆ คุณจัดการ OS ขึ้นไปเอง เหมือนเช่าห้องเปล่า, PaaS (Platform as a Service) จัดการ server ให้ คุณแค่ deploy code เหมือน co-working space, SaaS (Software as a Service) ใช้งานได้เลย เหมือนโรงแรม ยิ่ง managed เยอะ ยิ่งสะดวก แต่ flexibility น้อยลง:
| Model | คุณจัดการ | Cloud จัดการ | ตัวอย่าง |
|---|---|---|---|
| IaaS | OS, Runtime, App, Data | Server, Storage, Network | EC2, GCE, Azure VM |
| PaaS | App, Data | OS, Runtime, Server | Heroku, App Engine, Elastic Beanstalk |
| SaaS | แค่ใช้งาน | ทุกอย่าง | Gmail, Slack, Salesforce |
| FaaS | แค่ code (functions) | ทุกอย่าง + scaling | Lambda, Cloud Functions |
💡 จำง่ายๆ: IaaS = เช่าเครื่อง | PaaS = เช่า platform | SaaS = เช่า app | FaaS = เช่า function
🏢 3 Cloud Providers หลัก
ตลาด Cloud ถูกครอง 3 เจ้าใหญ่ — AWS (Amazon) มี market share มากที่สุด (~32%) มี services มากกว่า 200 ตัว, Azure (Microsoft) แข็งแกร่งด้าน enterprise และ hybrid cloud, GCP (Google) เด่นด้าน data/AI และ Kubernetes (Google สร้าง K8s) การเลือก provider ขึ้นอยู่กับ workload, ทีม, และ existing ecosystem มากกว่า "ใครดีกว่า":
- Compute: EC2, Lambda, ECS, EKS
- Storage: S3, EBS, EFS
- Database: RDS, DynamoDB, ElastiCache
- Network: VPC, ALB, CloudFront, Route53
- Monitor: CloudWatch, X-Ray
- Market share: ~31%
- Compute: VMs, Functions, AKS
- Storage: Blob, Disk, Files
- Database: SQL DB, Cosmos DB, Redis
- Network: VNet, App Gateway, Front Door
- Monitor: Monitor, App Insights
- Market share: ~25%
- Compute: GCE, Cloud Run, GKE
- Storage: Cloud Storage, Persistent Disk
- Database: Cloud SQL, Firestore, Bigtable
- Network: VPC, Cloud Load Balancing, CDN
- Monitor: Cloud Monitoring, Trace
- Market share: ~11%
Service Mapping — เปรียบเทียบ 3 Providers
แต่ละ provider เรียกชื่อ services ต่างกันแต่ทำหน้าที่เหมือนกัน — ตารางด้านล่างช่วยให้เปรียบเทียบได้เร็ว เช่น AWS EC2 = Azure VM = GCP Compute Engine, AWS S3 = Azure Blob = GCP Cloud Storage:
| Category | AWS | Azure | GCP |
|---|---|---|---|
| VM | EC2 | Virtual Machines | Compute Engine |
| Serverless | Lambda | Functions | Cloud Functions / Cloud Run |
| Kubernetes | EKS | AKS | GKE |
| Object Storage | S3 | Blob Storage | Cloud Storage |
| SQL Database | RDS / Aurora | SQL Database | Cloud SQL / Spanner |
| NoSQL | DynamoDB | Cosmos DB | Firestore / Bigtable |
| Cache | ElastiCache | Azure Redis | Memorystore |
| CDN | CloudFront | Front Door | Cloud CDN |
| DNS | Route 53 | Azure DNS | Cloud DNS |
| Message Queue | SQS / SNS | Service Bus | Pub/Sub |
| IaC | CloudFormation | ARM / Bicep | Deployment Manager |
🏗️ Well-Architected Framework
AWS, Azure และ GCP ต่างมี Well-Architected Framework — แนวทางออกแบบระบบบน cloud ที่ดี ประกอบด้วย 6 pillars:
🌐 VPC & Networking — เครือข่ายบน Cloud
VPC (Virtual Private Cloud) คือ "เครือข่ายส่วนตัว" ของคุณบน Cloud — เหมือนกั้นรั้วล้อมรอบ resources ทั้งหมดของคุณ ไม่ให้ใครเข้าถึงได้นอกจากที่อนุญาต การออกแบบ VPC ที่ดีคือรากฐานของ cloud security — แบ่ง subnets เป็น public (รับ traffic จาก internet) และ private (เข้าถึงได้เฉพาะภายใน) ใช้ Security Groups เป็น firewall ควบคุม traffic:
# Terraform — สร้าง VPC + Subnets
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = { Name = "production-vpc" }
}
# Public Subnet — internet access
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-southeast-1a"
map_public_ip_on_launch = true
tags = { Name = "public-subnet-1a" }
}
# Private Subnet — no direct internet
resource "aws_subnet" "private" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.10.0/24"
availability_zone = "ap-southeast-1a"
tags = { Name = "private-subnet-1a" }
}
# Internet Gateway (public subnet access)
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
}
# NAT Gateway (private subnet → internet)
resource "aws_nat_gateway" "nat" {
subnet_id = aws_subnet.public.id
allocation_id = aws_eip.nat.id
}
# Security Group
resource "aws_security_group" "web" {
vpc_id = aws_vpc.main.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # HTTPS from anywhere
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # HTTP → redirect to HTTPS
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"] # Allow all outbound
}
}
💡 กฎทอง: Web/App servers → Public Subnet | Database/Cache → Private Subnet (ไม่เปิด internet ตรง!)
⚡ High Availability — ระบบล่มไม่ได้!
High Availability (HA) คือการออกแบบให้ระบบทำงานได้ต่อเนื่องแม้ส่วนใดส่วนหนึ่งล่ม — หลักการสำคัญคือ "ไม่พึ่ง single point of failure" ทุก component ต้องมีอย่างน้อย 2 ตัว กระจายอยู่คนละ Availability Zone (AZ) หรือคนละ Region ถ้า AZ หนึ่งล่ม อีก AZ รับ traffic แทนได้ทันที Cloud providers ออกแบบ AZ ให้แยก power, cooling, networking จากกัน:
| Availability | Downtime/year | วิธีทำ |
|---|---|---|
| 99% | 3.65 วัน | Single server |
| 99.9% | 8.76 ชม. | Load balancer + multiple servers |
| 99.99% | 52.6 นาที | Multi-AZ + auto-failover |
| 99.999% | 5.26 นาที | Multi-region + active-active |
# Terraform — Auto Scaling Group
resource "aws_autoscaling_group" "app" {
name = "app-asg"
min_size = 2
max_size = 10
desired_capacity = 4
vpc_zone_identifier = [
aws_subnet.private_1a.id,
aws_subnet.private_1b.id,
aws_subnet.private_1c.id, # กระจาย 3 AZs
]
launch_template {
id = aws_launch_template.app.id
version = "$Latest"
}
target_group_arns = [aws_lb_target_group.app.arn]
health_check_type = "ELB"
health_check_grace_period = 300
}
# Auto Scaling Policy — CPU > 70% → scale up
resource "aws_autoscaling_policy" "scale_up" {
name = "scale-up"
autoscaling_group_name = aws_autoscaling_group.app.name
policy_type = "TargetTrackingScaling"
target_tracking_configuration {
predefined_metric_specification {
predefined_metric_type = "ASGAverageCPUUtilization"
}
target_value = 70.0
}
}
🚀 Serverless Architecture
Serverless = ไม่ต้องจัดการ server เลย แค่เขียน code แล้ว deploy — cloud จัดการ scaling, patching, HA ให้หมด:
# AWS Lambda + API Gateway (Serverless Framework)
# serverless.yml
service: my-api
provider:
name: aws
runtime: nodejs20.x
region: ap-southeast-1
memorySize: 256
timeout: 30
environment:
TABLE_NAME: ${self:service}-${sls:stage}
functions:
getUser:
handler: src/handlers/getUser.handler
events:
- http:
path: /users/{id}
method: get
cors: true
createUser:
handler: src/handlers/createUser.handler
events:
- http:
path: /users
method: post
cors: true
processOrder:
handler: src/handlers/processOrder.handler
events:
- sqs: # Trigger จาก SQS queue
arn: !GetAtt OrderQueue.Arn
batchSize: 10
resources:
Resources:
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: ${self:service}-${sls:stage}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
# Deploy
serverless deploy --stage production
# ได้ endpoint เช่น:
# https://abc123.execute-api.ap-southeast-1.amazonaws.com/production/users
Serverless: ข้อดี vs ข้อเสีย
Serverless ไม่ใช่ "silver bullet" — เหมาะกับ event-driven workloads ที่ traffic ไม่สม่ำเสมอ (APIs ที่ request มาเป็นช่วงๆ, image processing, scheduled jobs) แต่ไม่เหมาะกับ long-running tasks หรือ workloads ที่ต้องการ persistent connections ข้อดีคือ scale เป็น 0 ได้ (ไม่ใช้ไม่จ่าย) ข้อเสียคือ cold start delay และ vendor lock-in:
| ✅ ข้อดี | ⚠️ ข้อเสีย |
|---|---|
| ไม่ต้องจัดการ server | Cold start (ช้าตอน function ตื่น) |
| Scale อัตโนมัติ (0 → ∞) | Timeout limit (Lambda max 15 min) |
| จ่ายตามใช้งาน (pay-per-request) | Vendor lock-in |
| HA built-in | Debug ยากกว่า |
| เร็วในการ deploy | ไม่เหมาะกับ long-running tasks |
💰 Cost Optimization — ลดค่า Cloud
Cloud แพงได้ถ้าไม่ระวัง! นี่คือวิธีลดค่าใช้จ่าย:
1. Right-sizing — เลือก instance ให้เหมาะ
ข้อผิดพลาดที่พบบ่อยที่สุดคือเลือก instance ใหญ่เกินไป "เผื่อไว้" — ซึ่งเปลืองเงินมาก! ใช้ CloudWatch/Monitoring ดู CPU/Memory utilization จริง ถ้าใช้ไม่ถึง 40% ลดขนาดลงได้:
# ตรวจ CPU/Memory utilization
# ถ้า avg CPU < 20% → downsize!
# AWS Cost Explorer recommendation
aws ce get-rightsizing-recommendation \
--service EC2 \
--configuration '{"RecommendationTarget":"SAME_INSTANCE_FAMILY"}'
2. Reserved / Savings Plans
ถ้ารู้ว่าจะใช้ workload อะไรไปอีก 1-3 ปี Reserved Instances หรือ Savings Plans ประหยัดได้ 30-72% เทียบกับ on-demand — ยิ่งจ่ายล่วงหน้ามาก ยิ่งประหยัดมาก:
| Pricing Model | ส่วนลด | เหมาะกับ |
|---|---|---|
| On-Demand | 0% (ราคาเต็ม) | ทดสอบ, traffic ไม่แน่นอน |
| Reserved (1yr) | ~30-40% | Workload คงที่ |
| Reserved (3yr) | ~50-60% | Workload คงที่ระยะยาว |
| Spot Instances | ~60-90%! | Batch jobs, CI/CD, stateless |
| Savings Plans | ~30-50% | ยืดหยุ่นกว่า Reserved |
3. Auto-shutdown Dev/Staging
Dev/Staging environments ไม่จำเป็นต้องรัน 24/7 — ถ้าทีมทำงาน 9:00-18:00 ปิด instances นอกเวลาทำงานประหยัดได้ ~70%! ใช้ Lambda function + CloudWatch Events schedule ให้ start/stop อัตโนมัติ:
# Lambda function — ปิด dev instances ตอนกลางคืน
import boto3
def handler(event, context):
ec2 = boto3.client('ec2')
# หา instances ที่มี tag Environment=dev
instances = ec2.describe_instances(
Filters=[
{'Name': 'tag:Environment', 'Values': ['dev', 'staging']},
{'Name': 'instance-state-name', 'Values': ['running']}
]
)
ids = []
for r in instances['Reservations']:
for i in r['Instances']:
ids.append(i['InstanceId'])
if ids:
ec2.stop_instances(InstanceIds=ids)
print(f"Stopped {len(ids)} instances: {ids}")
# Schedule: ปิดทุก 20:00 เปิดทุก 08:00
# → ประหยัด ~50% ค่า dev/staging!
4. Storage Lifecycle
ข้อมูลที่เก่าแล้วไม่จำเป็นต้องอยู่ใน storage ราคาแพง — ใช้ Lifecycle Policies ย้ายข้อมูลอัตโนมัติจาก S3 Standard → S3 IA (Infrequent Access) → Glacier ตามอายุ ประหยัดได้ 60-90%:
# S3 Lifecycle — ย้ายข้อมูลเก่าไป storage ถูกกว่า
resource "aws_s3_bucket_lifecycle_configuration" "logs" {
bucket = aws_s3_bucket.logs.id
rule {
id = "archive-old-logs"
status = "Enabled"
transition {
days = 30
storage_class = "STANDARD_IA" # 30 วัน → Infrequent Access (-40%)
}
transition {
days = 90
storage_class = "GLACIER" # 90 วัน → Glacier (-80%)
}
expiration {
days = 365 # 1 ปี → ลบทิ้ง
}
}
}
🐕 สำคัญ! ตั้ง billing alerts เสมอ! ไม่งั้นตื่นมาเจอบิล $10,000 จะร้องไห้
# AWS Budget Alert — แจ้งเตือนเมื่อค่าใช้จ่ายเกิน
resource "aws_budgets_budget" "monthly" {
name = "monthly-budget"
budget_type = "COST"
limit_amount = "500"
limit_unit = "USD"
time_unit = "MONTHLY"
notification {
comparison_operator = "GREATER_THAN"
threshold = 80 # แจ้งเมื่อถึง 80%
threshold_type = "PERCENTAGE"
notification_type = "ACTUAL"
subscriber_email_addresses = ["[email protected]"]
}
}
🔒 Cloud Security — ปกป้องระบบ
Cloud security ต่างจาก on-premise ตรงที่ใช้ Shared Responsibility Model — provider ดูแล security "ของ" cloud (physical, hypervisor, network) ส่วนคุณดูแล security "บน" cloud (data, access, config, OS patching) ข้อผิดพลาดที่พบบ่อยที่สุดคือ misconfiguration — S3 bucket เปิด public, IAM policy ให้สิทธิ์มากเกิน, Security Group เปิด port 0.0.0.0/0
IAM — Identity & Access Management
IAM คือระบบจัดการ "ใครมีสิทธิ์ทำอะไร" — หลักการสำคัญที่สุดคือ Least Privilege (ให้สิทธิ์เท่าที่จำเป็น) อย่าใช้ root account สำหรับงานประจำวัน สร้าง IAM users/roles ที่มี permissions เฉพาะงาน:
# Principle of Least Privilege — ให้สิทธิ์น้อยที่สุด
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/uploads/*"
}
]
}
# ❌ อย่าทำ!
# "Action": "*"
# "Resource": "*"
# → Full admin access ทุก service = อันตราย!
Security Checklist
Checklist ด้านล่างครอบคลุม security best practices ที่ทุก cloud deployment ต้องทำ — ตั้งแต่ MFA, encryption at rest/in transit, logging, ไปจนถึง vulnerability scanning:
- MFA — เปิด Multi-Factor Auth ทุก account โดยเฉพาะ root
- Least Privilege — ให้สิทธิ์น้อยที่สุดเท่าที่ต้องใช้
- Encrypt — encrypt data at rest (KMS) และ in transit (TLS)
- Private Subnets — DB/cache อยู่ใน private subnet เท่านั้น
- Security Groups — เปิด port เฉพาะที่ต้องใช้ (ไม่ 0.0.0.0/0 ทุก port!)
- Secrets Manager — อย่า hardcode credentials ใน code!
- CloudTrail — เปิด audit log ทุก API call
- GuardDuty — threat detection อัตโนมัติ
📊 Cloud Architecture Patterns
มาถึง patterns ที่ใช้จริงในการออกแบบระบบบน Cloud — แต่ละ pattern เหมาะกับ workload ต่างกัน ไม่มี "pattern ที่ดีที่สุด" มีแต่ "pattern ที่เหมาะสมที่สุด" กับ requirements ของคุณ เริ่มจาก simple แล้วค่อย evolve ตามความต้องการ:
1. Three-Tier Architecture (คลาสสิค)
Three-Tier แบ่งระบบเป็น 3 ชั้น — Presentation (frontend), Application (backend logic), Data (database) เป็น pattern คลาสสิคที่เข้าใจง่ายและเหมาะกับ web apps ส่วนใหญ่ เริ่มต้นด้วย pattern นี้ก่อน แล้วค่อยแยกเป็น microservices เมื่อ scale จนจำเป็น:
2. Event-Driven Architecture
Event-Driven Architecture คือการออกแบบให้ components สื่อสารกันผ่าน "events" แทนการเรียกตรง — เมื่อสิ่งหนึ่งเกิดขึ้น (เช่น user สั่งซื้อ) จะสร้าง event ส่งไปยัง message queue แล้ว services อื่นๆ รับไปทำงานต่อ ข้อดีคือ loose coupling — แต่ละ service ไม่ต้องรู้จักกัน:
Event-Driven pattern ทำให้ระบบมี resilience สูงเพราะหาก component หนึ่งล่ม events จะถูก queue ไว้และ process เมื่อ component กลับมา online ได้ การใช้ managed message queues อย่าง SQS, SNS หรือ EventBridge จะช่วยให้ระบบ scale ได้ดีและลด operational overhead
ข้อจำกัดของ pattern นี้คือการ debug และ monitoring ยากกว่าเพราะ flow ของข้อมูลไม่เป็นเส้นตรง และการ ensure eventual consistency ระหว่าง services ต้องใช้เทคนิคพิเศษ เช่น saga pattern หรือ event sourcing แต่สำหรับ use cases ที่เหมาะสม benefits ที่ได้จะมากกว่า complexity ที่เพิ่มขึ้น
3. Microservices on Kubernetes
Microservices บน Kubernetes เป็น pattern ที่ซับซ้อนที่สุดแต่ให้ benefits มากที่สุดสำหรับ large-scale applications การแยกแต่ละ business capability เป็น independent service ที่มี database ของตัวเองทำให้ทีมสามารถ develop, test และ deploy แยกกันได้ เหมาะกับองค์กรขนาดใหญ่ที่มีหลายทีม development
# แต่ละ service เป็น independent deployment
services:
├── user-service (EKS pod, own DynamoDB table)
├── order-service (EKS pod, own RDS database)
├── payment-service (EKS pod, connects Stripe)
├── notification-svc (Lambda, triggered by SQS)
└── api-gateway (Kong / AWS API Gateway)
# Communication:
sync → REST / gRPC (service-to-service)
async → SQS / SNS / EventBridge (event-driven)
Microservices architecture ตัวอย่างด้านบนแสดงการแยก services ตาม domain boundaries แทนที่จะแยกตาม technical layers แต่ละ service มี database ของตัวเองและสื่อสารกันผ่าน well-defined APIs การใช้ Kubernetes จะช่วยในการ orchestrate containers และ manage networking ระหว่าง services
ข้อดีของ pattern นี้คือ scalability และ development velocity ที่สูงมากสำหรับทีมขนาดใหญ่ แต่ cost และ complexity ก็สูงตามไปด้วย ไม่เหมาะกับ small teams หรือ simple applications การเลือกใช้ microservices ควรพิจารณาจาก organizational readiness มากกว่า technical requirements เพียงอย่างเดียว
สรุป
Cloud Architecture เป็นศาสตร์และศิลป์ที่ผสมผสานระหว่างความรู้ทางเทคนิคและความเข้าใจทางธุรกิจ การออกแบบระบบที่ดีไม่ใช่แค่การเลือก services ที่ล่าสุดหรือแพงที่สุด แต่เป็นการหาสมดุลระหว่าง technical requirements และ business constraints ให้เหมาะสมกับบริบทเฉพาะของแต่ละองค์กร
สิ่งสำคัญที่สุดคือการเริ่มต้นแบบ simple แล้วค่อย ๆ เพิ่ม complexity เมื่อจำเป็น การ over-engineer ตั้งแต่เริ่มต้นมักจะสร้างปัญหามากกว่าแก้ปัญหา การ monitor, measure และ iterate อย่างต่อเนื่องจะช่วยให้ระบบพัฒนาไปในทิศทางที่ถูกต้องและ sustainable ในระยะยาว
- Cloud Computing = เช่าใช้ resources จ่ายตามใช้งาน (IaaS / PaaS / SaaS / FaaS)
- 3 Providers = AWS (~31%), Azure (~25%), GCP (~11%) — services คล้ายกัน ชื่อต่าง
- Well-Architected = 6 pillars: Security, Reliability, Performance, Cost, Operations, Sustainability
- VPC = แยก public/private subnet, Security Groups จำกัด port
- High Availability = Multi-AZ, Auto Scaling, Load Balancer → 99.99% uptime
- Serverless = Lambda/Cloud Functions ไม่ต้องจัดการ server, scale อัตโนมัติ
- Cost = Right-size, Reserved/Spot instances, auto-shutdown dev, storage lifecycle
- Security = IAM least privilege, MFA, encrypt everything, private subnets ☁️🐕