ข้ามไปที่เนื้อหา

The 12-Factor App: คู่มือฉบับเต็ม

Cloud-native application พังด้วยเรื่องเดิมๆ แทบทุกตัว config ไปฝังอยู่ในโค้ด state เก็บไว้ใน memory พอ restart ก็หาย local dev environment ทำงานไม่เหมือน production สักนิด หรือไม่ก็ scale แนวนอนไม่ได้เพราะ app เขียนไฟล์ลง disk

The 12-Factor App คือหลักการ 12 ข้อที่กันปัญหาพวกนี้ได้ทั้งหมด วิศวกรของ Heroku เขียนไว้ตั้งแต่ปี 2011 แต่ทุกวันนี้ก็ยังเป็นคู่มือสร้าง software-as-a-service application ที่ใช้ได้จริงและใช้ได้กว้างที่สุด บทความนี้จะไล่ทีละ factor พร้อมโค้ดจริงและ anti-pattern ที่เจอกันจริง แล้วดูว่าแต่ละข้อเอามาใช้กับ cloud-native deployment ยุคนี้ยังไง


12-Factor App คืออะไร

12-Factor App เป็น methodology สำหรับสร้าง software application ยุคใหม่ ที่มีคุณสมบัติแบบนี้:

  • ทำ setup automation ด้วย format แบบ declarative
  • มี contract ที่ชัดเจน กับ operating system ที่รันอยู่ข้างใต้
  • deploy บน cloud platform ได้สบาย
  • development กับ production ต่างกันน้อยที่สุด
  • Scale up ได้โดยไม่ต้องรื้อ tooling, architecture หรือวิธีทำงานของทีม

แนวคิดนี้มาจากการสังเกต pattern ของ app หลายพันตัวที่ deploy อยู่บน Heroku ไม่ใช่ framework ไม่ใช่ library แต่เป็นหลักการที่ใช้ได้กับทุกภาษาและทุก stack

  12-Factor Goal:
  ┌──────────────────────────────────────────────────────────┐
  │  Write code once → Deploy anywhere → Scale without pain  │
  └──────────────────────────────────────────────────────────┘

  The Three Failure Modes it prevents:
  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
  │   Code/Config   │  │  State/Coupling  │  │  Dev/Prod Gap   │
  │   Entanglement  │  │                 │  │                 │
  │                 │  │ "It works on my │  │ "But staging    │
  │ "I have to      │  │  machine. The   │  │  is fine."      │
  │  change code to │  │  server has a   │  │                 │
  │  deploy to prod"│  │  different IP"  │  │                 │
  └─────────────────┘  └─────────────────┘  └─────────────────┘

12 Factor ในตารางเดียว

# Factor สรุปสั้นๆ
1 Codebase Repo เดียว แต่ deploy ได้หลายที่
2 Dependencies ประกาศให้ครบ อย่าเดาว่ามีอยู่แล้ว
3 Config ค่าที่ต่างกันในแต่ละที่ เก็บไว้ใน environment ไม่ใช่ใน app
4 Backing Services ของภายนอกทุกอย่างคือ resource ที่เสียบเข้าถอดออกได้
5 Build, Release, Run แยก stage ให้ขาด artifact แก้ไม่ได้
6 Processes Stateless ไว้ก่อน ไม่แชร์อะไรกัน
7 Port Binding App มีทุกอย่างในตัว และเปิด port เอง
8 Concurrency Scale out ด้วยการเพิ่ม process ไม่ใช่เพิ่ม thread
9 Disposability Start ไว ปิดตัวเรียบร้อย
10 Dev/Prod Parity ทำให้แต่ละ environment ต่างกันน้อยที่สุด
11 Logs ส่งออกเป็น stream ไม่เขียนลงไฟล์
12 Admin Processes งาน one-off รันใน environment เดียวกับ app

Factor 1: Codebase — Repo เดียว Deploy ได้หลายที่

"One codebase tracked in revision control, many deploys."

กฎ

Codebase หนึ่งตัวคู่กับ app หนึ่งตัวเท่านั้น หลาย app จะใช้ codebase ร่วมกันไม่ได้ ถ้าเจอแบบนั้น ให้แยกโค้ดส่วนที่ใช้ร่วมกันออกมาเป็น library แล้วดึงเข้าไปเป็น dependency

Deploy คือ instance ของ app ที่รันอยู่จริง codebase เดียวมีได้หลาย deploy เช่น production, staging หรือเครื่อง local ของ developer ทุกตัวรันจากโค้ดชุดเดียวกัน ต่างกันแค่ version หรือ config

  ONE CODEBASE → MANY DEPLOYS

  git repo
  ─────────
  main branch  ──────→  Production  (v1.4.2)
  staging tag  ──────→  Staging     (v1.4.3-rc1)
  local clone  ──────→  Developer A (current HEAD)
  local clone  ──────→  Developer B (feature branch)

Anti-Pattern: Config ฝังอยู่ในโค้ด

# BAD: different branches for different environments
git checkout prod-branch     # has prod DB url hardcoded
git checkout staging-branch  # has staging DB url hardcoded
git checkout dev-branch      # has local DB url hardcoded

ทำแบบนี้ คุณจะไม่มีทาง deploy artifact ตัวเดียวกันไปหลาย environment ได้เลย build แต่ละรอบได้ binary คนละตัวตาม environment ดูแลทีปวดหัวแน่นอน

Anti-Pattern: หลาย App ใช้ Codebase ร่วมกัน

# BAD: two apps living in one repo and sharing source code
my-monolith/
├── web_app/
│   └── main.py  # imports from shared/
├── worker_app/
│   └── main.py  # also imports from shared/
└── shared/
    └── models.py  # shared business logic

ถ้า shared/ เป็น dependency จริง ก็แยกออกมาเป็น library ที่มี version ของตัวเอง แล้วให้แต่ละ app ประกาศ dependency ไปที่ library ตัวนั้นให้ชัด

ทำแบบ 12-Factor

# GOOD: separate repos, shared code is a library
github.com/mycompany/order-service        # one app
github.com/mycompany/notification-service # another app
github.com/mycompany/shared-models        # shared library (versioned)
# order-service/requirements.txt
shared-models==1.3.0   # explicit version, not a local path import

Codebase ในโลก Microservices

ใน microservices architecture แต่ละ service คือ app หนึ่งตัวที่มี codebase ของตัวเอง ส่วน monorepo (git repo เดียวที่รวมหลาย service) ไม่ได้ ผิด Factor 1 ขอแค่แต่ละ service มี deployment pipeline แยกกัน และ build artifact ของตัวเองออกมา

monorepo/
├── services/
│   ├── orders/       → builds to orders-service:v1.2.0 image
│   ├── payments/     → builds to payments-service:v2.0.1 image
│   └── catalog/      → builds to catalog-service:v1.0.5 image
└── libs/
    └── shared/       → versioned internal library

Factor 2: Dependencies — ประกาศให้ครบ อย่าเดาเอาเอง

"Explicitly declare and isolate dependencies."

กฎ

12-factor app ไม่เคยหวังว่า package ระดับ system จะมีติดเครื่องอยู่แล้ว dependency ทุกตัวต้องประกาศไว้ใน dependency manifest ให้ครบและชัด แล้วใช้ dependency isolation tool กันไม่ให้ dependency จาก system รอบข้างหลุดเข้ามา

Dependency ที่แอบซ่อนอยู่

# BAD: code assumes ImageMagick is installed on the server
import subprocess

def resize_image(path: str, width: int) -> None:
    # This will silently fail if ImageMagick isn't installed
    subprocess.run(["convert", path, "-resize", str(width), path])

App ตัวนี้แอบพึ่ง ImageMagick ที่ต้องติดตั้งไว้ในระดับ system บน laptop คุณรันผ่าน (เพราะคุณติดตั้งไว้เอง) พอขึ้น server ใหม่ก็พัง (เพราะไม่มีใครติดตั้ง) จะพังเงียบหรือพังเสียงดังก็แล้วแต่ OS

ทำแบบ 12-Factor: ประกาศให้ชัด

# pyproject.toml — every dependency explicit and versioned
[project]
name = "order-service"
version = "1.0.0"
dependencies = [
    "fastapi==0.111.0",
    "sqlalchemy==2.0.30",
    "pydantic==2.7.0",
    "Pillow==10.3.0",    # image processing — no system ImageMagick needed
    "httpx==0.27.0",
]

[tool.uv]
dev-dependencies = [
    "pytest==8.2.0",
    "pytest-asyncio==0.23.7",
]
# Dockerfile — isolated environment, no system dependencies leak in
FROM python:3.12-slim

WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN pip install uv && uv sync --frozen --no-dev

COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
// package.json
{
  "name": "order-service",
  "version": "1.0.0",
  "dependencies": {
    "express": "4.19.2",
    "pg": "8.11.5",
    "sharp": "0.33.4"
  },
  "devDependencies": {
    "jest": "29.7.0",
    "typescript": "5.4.5"
  },
  "engines": {
    "node": ">=20.0.0"
  }
}
FROM node:20-alpine

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production

COPY . .
CMD ["node", "src/index.js"]
// go.mod — all dependencies declared, pinned by go.sum
module github.com/mycompany/order-service

go 1.22

require (
    github.com/gin-gonic/gin v1.10.0
    github.com/jackc/pgx/v5 v5.6.0
    github.com/redis/go-redis/v9 v9.5.3
)

Lock file ต้อง commit เสมอ ไม่มีข้อยกเว้น

Commit lock file ทุกครั้ง (package-lock.json, poetry.lock, go.sum, uv.lock) lock file จะ pin transitive dependency ทุกตัวไว้ที่ version ตายตัว build บนเครื่องไหน เมื่อไหร่ ก็ได้ผลเหมือนเดิม

"Isolation" แปลว่าอะไร

Isolation คือ package ใน system ต้องปนเข้ามาใน dependency environment ของ app ไม่ได้ tool ที่ช่วยเรื่องนี้มีตามนี้:

ภาษา Isolation Tool
Python venv, uv, conda
Node.js node_modules (อยู่ใน project ของตัวเอง)
Go Module cache (go.mod แยกให้)
Java Maven/Gradle local repository
ทุกภาษา Docker (ใช้ได้กับทุกกรณี)

Factor 3: Config — แยก Config ออกจาก App ด้วย Environment

"Store config in the environment."

กฎ

Config คือทุกอย่างที่ต่างกันในแต่ละ deploy (staging, production, environment ของ developer) ส่วนโค้ดเหมือนกันทุก deploy วิธีเช็คง่ายๆ คือถามตัวเองว่า ถ้า open-source codebase ตอนนี้เลย credential จะหลุดไหม ถ้าหลุด แปลว่า config รั่วเข้าไปอยู่ในโค้ดแล้ว

อะไรนับเป็น Config

  • Database connection string และ credential
  • API key ของ service ภายนอก (Stripe, SendGrid, Twilio)
  • Resource handle (Redis URL, ชื่อ S3 bucket)
  • Feature flag
  • URL ของ service ตัวอื่นที่ app ต้องเรียก

อะไรไม่นับเป็น Config

  • ค่าคงที่ในระบบที่ไม่ต่างกันในแต่ละ environment (อัตราภาษีที่กฎหมายกำหนด, ค่าคงที่ทางคณิตศาสตร์)
  • Configuration ระดับ application ที่ใช้เหมือนกันทุกที่ (routing rule, การ setup middleware)

Anti-Pattern: Config ฝังอยู่ในโค้ด

# BAD: config hardcoded in source code
DATABASE_URL = "postgresql://admin:SuperSecret123@prod-db.internal:5432/orders"
STRIPE_KEY = "sk_live_abc123xyz..."
REDIS_URL = "redis://redis.internal:6379/0"

# BAD: config in a committed config file
# config/production.py (in git!)
DEBUG = False
DATABASE_HOST = "prod-db.internal"
DATABASE_PASSWORD = "SuperSecret123"

Config ในโค้ด คือ security incident ที่รอวันระเบิด

ใครก็ตามที่เคย clone repo ไป ตอนนี้มี password ของ production database ติดมือไปแล้ว password นี้อยู่ใน git history ตลอดไป ต่อให้ "ลบ" ทีหลังก็ไม่หาย credential หลุดกันแบบนี้แหละ

ทำแบบ 12-Factor: ใช้ Environment Variable

# GOOD: all config from environment variables
import os
from functools import lru_cache
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    stripe_secret_key: str
    redis_url: str
    debug: bool = False
    log_level: str = "INFO"
    max_connections: int = 10

    class Config:
        env_file = ".env"          # loaded in dev, ignored in prod
        env_file_encoding = "utf-8"

@lru_cache
def get_settings() -> Settings:
    return Settings()
# .env (local development — NEVER commit this)
DATABASE_URL=postgresql://postgres:password@localhost:5432/orders_dev
STRIPE_SECRET_KEY=sk_test_abc123
REDIS_URL=redis://localhost:6379/0
DEBUG=true
LOG_LEVEL=DEBUG
# .gitignore
.env
.env.*
!.env.example  # commit an example with no real values
# .env.example (commit this — shows what vars are needed, no real values)
DATABASE_URL=postgresql://user:password@host:5432/dbname
STRIPE_SECRET_KEY=sk_test_...
REDIS_URL=redis://localhost:6379/0
DEBUG=false
LOG_LEVEL=INFO

Config ใน Kubernetes

ใน Kubernetes, environment variable มาจาก ConfigMap (ค่าที่ไม่ sensitive) กับ Secret (ค่าที่ sensitive):

# configmap.yaml — non-sensitive config
apiVersion: v1
kind: ConfigMap
metadata:
  name: order-service-config
data:
  LOG_LEVEL: "INFO"
  MAX_CONNECTIONS: "20"
  FEATURE_NEW_CHECKOUT: "true"

---
# secret.yaml — sensitive values (base64 encoded, ideally from a secret manager)
apiVersion: v1
kind: Secret
metadata:
  name: order-service-secrets
type: Opaque
stringData:          # stringData lets you write plain text, k8s encodes it
  DATABASE_URL: "postgresql://user:pass@db-service:5432/orders"
  STRIPE_SECRET_KEY: "sk_live_..."
# deployment.yaml — inject config into the container
spec:
  containers:
  - name: order-service
    image: mycompany/order-service:v1.2.0
    envFrom:
    - configMapRef:
        name: order-service-config
    - secretRef:
        name: order-service-secrets
    env:
    - name: POD_NAME          # expose Kubernetes metadata as env vars
      valueFrom:
        fieldRef:
          fieldPath: metadata.name

ไปไกลกว่า env var: ใช้ secrets manager

ใน production, Kubernetes Secret ธรรมดาเก็บค่าแบบ base64-encoded เฉยๆ ไม่ได้ encrypt ถ้าอยากปลอดภัยจริงตอนระบบใหญ่ขึ้น ให้ใช้ secrets manager:

  • HashiCorp Vault คู่กับ Vault Agent Injector
  • AWS Secrets Manager คู่กับ AWS Secrets Store CSI Driver
  • ฝั่ง GCP ใช้ GCP Secret Manager ฝั่ง Azure ใช้ Azure Key Vault

ระบบพวกนี้ inject secret ให้ตอน runtime, rotate ให้อัตโนมัติ และเก็บ audit log ไว้ให้ด้วย


Factor 4: Backing Services — Resource ที่เสียบเข้าถอดออกได้

"Treat backing services as attached resources."

กฎ

Backing service คือ service อะไรก็ได้ที่ app เรียกใช้ผ่าน network ตามปกติ เช่น database, message queue, cache, email service, payment API ฝั่ง 12-factor app มอง service ที่รันเองกับ service ของ third-party เหมือนกันหมด ทั้งสองแบบเข้าถึงผ่าน URL หรือ credential ที่อยู่ใน config

  BACKING SERVICES — all treated the same way:

  ┌─────────────────┐
  │   Your App      │
  └────────┬────────┘
           │ accessed via URL/credentials in environment config
     ┌─────┴──────────────────────────────────┐
     │                                         │
     ▼         ▼          ▼          ▼         ▼
  ┌──────┐  ┌──────┐  ┌──────┐  ┌──────┐  ┌──────┐
  │  DB  │  │Redis │  │Kafka │  │SMTP  │  │Stripe│
  │(your │  │(your │  │(your │  │(Send │  │(3rd  │
  │ own) │  │ own) │  │ own) │  │ Grid)│  │party)│
  └──────┘  └──────┘  └──────┘  └──────┘  └──────┘

App มองทุกตัวเหมือนกันหมด มีแค่ URL กับ credential ใน environment variable จะรัน database บน localhost หรือบน AWS RDS app ก็ไม่สน

ข้อดีของการ "Attach/Detach"

ข้อดีตัวจริงคือ สลับ backing service ได้โดยไม่ต้องแก้โค้ดสักบรรทัด แก้แค่ config

# GOOD: database is just a URL — the app doesn't know where it lives
class OrderRepository:
    def __init__(self, database_url: str):
        self._engine = create_engine(database_url)

    def save(self, order: Order) -> None:
        with self._engine.connect() as conn:
            conn.execute(...)
# Swap from local Postgres to RDS — zero code changes
# Before
DATABASE_URL=postgresql://postgres:pass@localhost:5432/orders

# After (just change the env var)
DATABASE_URL=postgresql://orders_user:prod_pass@orders.abc123.us-east-1.rds.amazonaws.com:5432/orders

Anti-Pattern: Hardcode ที่อยู่ของ Service

# BAD: app knows exactly where the database lives
class OrderRepository:
    def __init__(self):
        # hardcoded — can't swap without code change
        self._conn = psycopg2.connect(
            host="10.0.1.42",
            port=5432,
            database="orders",
            user="admin",
            password="secret"
        )

Backing Service ที่ใช้กันจริง

ประเภท Local Dev Production
Relational DB PostgreSQL (Docker) AWS RDS, Cloud SQL, Neon
Cache Redis (Docker) Elasticache, Upstash
Message Queue RabbitMQ (Docker) AWS SQS, Google Pub/Sub, Kafka
Object Storage MinIO (Docker) AWS S3, GCS, Azure Blob
Search Elasticsearch (Docker) Elastic Cloud, OpenSearch
Email Mailhog (Docker) SendGrid, AWS SES
SMS Mock server Twilio

รัน backing service บน local ด้วย Docker Compose

รัน backing service ทุกตัวบน local ผ่าน Docker Compose พฤติกรรมจะได้ตรงกับ production:

# docker-compose.yml
services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: orders_dev
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  kafka:
    image: confluentinc/cp-kafka:7.6.1
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
    ports:
      - "9092:9092"

Factor 5: Build, Release, Run — แยก Stage ให้ขาด

"Strictly separate build and run stages."

กฎ

กว่า codebase จะกลายเป็น deploy ได้ ต้องผ่านสาม stage:

  1. Build: เปลี่ยน code repo ให้เป็น bundle ที่รันได้ (compile, bundle asset, ดึง dependency) ขั้นนี้ไม่รู้เลยว่าจะเอาไป deploy ที่ environment ไหน
  2. Release: เอา build artifact มารวมกับ config ของ deploy นั้น ทุก release มี ID ไม่ซ้ำกัน และแก้ไม่ได้ (immutable)
  3. Run: เลือก release มาหนึ่งตัว แล้ว launch process ของ app จาก release ตัวนั้นใน execution environment
  BUILD → RELEASE → RUN

  Source Code  ──→  Build Process  ──→  Build Artifact
                         │
                    (add config)
                         │
                         ▼
               Release (artifact + config)  ──→  Run (processes)

  Build Artifact: Docker image, compiled binary, zip bundle
  Release ID:     v1.4.2, git SHA, timestamp — never mutable

ทำไม Release ต้อง Immutable

Release ที่สร้างแล้ว แก้ไม่ได้เด็ดขาด อยากเปลี่ยนอะไรก็สร้าง release ใหม่ ได้ประโยชน์ตามนี้:

  • Rollback ได้ทันที: แค่ activate release ก่อนหน้า
  • Audit trail: ย้อนดูได้เป๊ะๆ ว่าช่วงไหนรันโค้ดอะไรอยู่
  • ไม่มีเซอร์ไพรส์: ของที่เทสใน staging คือตัวเดียวกับที่รันใน production

Anti-Pattern: SSH เข้า Production ไปแก้สดๆ

# BAD: "just a quick hotfix" in production
ssh prod-server-01
vim /app/orders/pricing.py   # edit code directly on the server
kill -HUP $(cat /var/run/app.pid)  # reload
# Now prod and your codebase are out of sync. Forever.

แบบนี้มีชื่อเรียกว่า "cowboy deployment" deploy รอบต่อๆ ไปจะพังหมด เพราะบน server มีของที่แก้ไว้ local โดยไม่มีใครจดไว้

ทำแบบ 12-Factor: CI/CD Pipeline

# .github/workflows/deploy.yml
name: Build → Release → Deploy

on:
  push:
    branches: [main]

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    outputs:
      image_tag: ${{ steps.meta.outputs.tags }}
    steps:
      - uses: actions/checkout@v4

      - name: Build Docker image
        id: build
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            mycompany/order-service:${{ github.sha }}
            mycompany/order-service:latest
          # The image IS the build artifact — immutable, content-addressed

  release-staging:
    name: Release → Staging
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to staging
        run: |
          # Combine build artifact (image) + staging config (env vars)
          kubectl set image deployment/order-service \
            order-service=mycompany/order-service:${{ github.sha }} \
            --namespace=staging
          kubectl rollout status deployment/order-service --namespace=staging

  release-production:
    name: Release → Production
    needs: release-staging
    runs-on: ubuntu-latest
    environment: production   # requires manual approval
    steps:
      - name: Deploy to production
        run: |
          kubectl set image deployment/order-service \
            order-service=mycompany/order-service:${{ github.sha }} \
            --namespace=production

Build stage ห้ามแตะ production config

Build ได้ artifact ตัวเดียวกันเสมอ ไม่ว่าจะเอาไป deploy ที่ไหน config ค่อยใส่เข้ามาตอน Release stage เท่านั้น การ bake secret ไว้ใน Docker image เลยเป็น anti-pattern


Factor 6: Processes — Stateless และไม่แชร์อะไรกัน

"Execute the app as one or more stateless processes."

กฎ

Process แบบ 12-factor ต้อง stateless และ share nothing ข้อมูลไหนต้องเก็บถาวร ให้ไปอยู่ใน stateful backing service (database, cache) ตัว process เองไม่เก็บ persistent state อะไรไว้เลย

ถ้าจะ scale บน cloud นี่คือ factor ที่สำคัญที่สุด

Stateless คือสิ่งที่ทำให้ Scale ได้

  STATEFUL (broken scaling):

  User → Load Balancer → Server A (has user's session in memory)
                       → Server B (user's session NOT here → broken!)

  STATELESS (correct scaling):

  User → Load Balancer → Server A (reads session from Redis) ✓
                       → Server B (also reads session from Redis) ✓

  Any server can handle any request. Add more servers freely.

Anti-Pattern: เก็บ State ไว้ใน Process

# BAD: storing state in the process
# This breaks the moment you run a second instance

class OrderService:
    _pending_orders: dict = {}      # in-memory state — lost on restart
    _user_sessions: dict = {}       # will be empty on the next server
    _uploaded_files: list = []      # different on every instance

    def save_draft_order(self, user_id: str, order: dict):
        self._pending_orders[user_id] = order  # only on THIS server

    def get_draft_order(self, user_id: str):
        return self._pending_orders.get(user_id)  # won't be here on server B

Anti-Pattern: Sticky Session

# BAD: nginx sticky sessions — routing users to the same server
upstream backend {
    ip_hash;   # forces same user to same server
    server 10.0.1.10;
    server 10.0.1.11;
}

Sticky session เป็นแค่พลาสเตอร์ที่ปิดปัญหา application แบบ stateful ไว้ แถม server ที่ user "ติด" อยู่ก็กลายเป็น single point of failure

ทำแบบ 12-Factor: ย้าย State ไปไว้ข้างนอก

# GOOD: all state in backing services
import redis
import json
from uuid import UUID

class OrderDraftService:
    def __init__(self, redis_client: redis.Redis, db: Database):
        self._redis = redis_client
        self._db = db

    def save_draft(self, user_id: UUID, order_data: dict) -> None:
        # Store draft in Redis (survives process restart)
        key = f"draft_order:{user_id}"
        self._redis.setex(key, 3600, json.dumps(order_data))  # 1 hour TTL

    def get_draft(self, user_id: UUID) -> dict | None:
        key = f"draft_order:{user_id}"
        data = self._redis.get(key)
        return json.loads(data) if data else None

    def confirm_order(self, user_id: UUID) -> UUID:
        draft = self.get_draft(user_id)
        if not draft:
            raise DraftNotFoundError(user_id)

        order = Order.from_draft(draft)
        self._db.save(order)  # persist to database

        self._redis.delete(f"draft_order:{user_id}")  # clean up
        return order.id
# Session storage in backing service (not in-process)
from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
import redis

app = FastAPI()

# Sessions stored in Redis — stateless from the app's perspective
app.add_middleware(
    SessionMiddleware,
    secret_key=os.getenv("SESSION_SECRET"),
    # configure Redis as session backend
)

ไฟล์ที่ User Upload: ห้ามลง Local Disk

# BAD: files written to local disk
def upload_receipt(file: UploadFile):
    with open(f"/tmp/receipts/{file.filename}", "wb") as f:
        f.write(await file.read())   # will be gone on pod restart
    return f"/tmp/receipts/{file.filename}"

# GOOD: files in object storage (S3, GCS, etc.)
import boto3

def upload_receipt(file: UploadFile) -> str:
    s3 = boto3.client("s3")
    key = f"receipts/{uuid4()}/{file.filename}"
    s3.upload_fileobj(file.file, "my-bucket", key)
    return f"s3://my-bucket/{key}"   # URL survives process death

Factor 7: Port Binding — App เปิด Port เอง

"Export services via port binding."

กฎ

12-factor app มีทุกอย่างครบในตัว ไม่ต้องรอให้ใคร inject web server มาให้ตอน runtime app เปิด HTTP (หรือ protocol อื่น) เองด้วยการ bind port แล้วรอรับ request ที่ port นั้น

ไม่ต้องติดตั้ง Apache หรือ Nginx ไว้ก่อน web server เป็นแค่ dependency อีกตัวที่ประกาศไว้ใน manifest

  TRADITIONAL (server installs the app):
  Apache/Nginx is installed → App is a plugin/module → Apache serves it

  12-FACTOR (app self-contains the server):
  App starts → Binds port 8000 → Anyone connecting to :8000 gets a response

ใช้งานจริง

# main.py — the web server is a library, not a system dependency
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
def health():
    return {"status": "ok"}

@app.get("/orders/{order_id}")
def get_order(order_id: str):
    ...
# The app binds its own port
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
// server.js — Express binds its own port
const express = require('express');
const app = express();
const PORT = process.env.PORT || 8000;

app.get('/health', (req, res) => res.json({ status: 'ok' }));

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Order service listening on port ${PORT}`);
});
// main.go
package main

import (
    "fmt"
    "net/http"
    "os"
)

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8000"
    }

    http.HandleFunc("/health", healthHandler)
    http.HandleFunc("/orders/", ordersHandler)

    fmt.Printf("Order service listening on :%s\n", port)
    http.ListenAndServe(":"+port, nil)
}

Port Binding ใน Kubernetes

ใน Kubernetes ให้ประกาศ port ไว้ใน container spec แล้ว expose ออกไปผ่าน Service:

# deployment.yaml
spec:
  containers:
  - name: order-service
    image: mycompany/order-service:v1.2.0
    ports:
    - containerPort: 8000   # the port the app binds to
    env:
    - name: PORT
      value: "8000"

---
# service.yaml — routes traffic to the container port
apiVersion: v1
kind: Service
metadata:
  name: order-service
spec:
  selector:
    app: order-service
  ports:
  - port: 80          # port clients connect to
    targetPort: 8000  # port the container listens on

หนึ่ง app → หนึ่ง port ไม่ใช่หนึ่ง app → หลาย port

12-factor app แต่ละตัว bind port เดียว ถ้าต้อง expose ทั้ง HTTP และ metrics endpoint ก็ใช้สอง port แยกกันบน app เดียว (8000 สำหรับ HTTP, 9090 สำหรับ Prometheus metrics) หรือไม่ก็รัน sidecar container


Factor 8: Concurrency — Scale Out ด้วย Process

"Scale out via the process model."

กฎ

ใน 12-factor app process คือหัวใจหลัก งานแต่ละแบบแยกไปให้ process type คนละตัวรับ แล้ว scale app ด้วยการเพิ่มจำนวน process ไม่ใช่ขยาย process เดียวให้อ้วนขึ้น

  PROCESS MODEL — one app, multiple process types:

  ┌─────────────────────────────────────────────┐
  │           ORDER SERVICE                      │
  ├─────────────────┬───────────────────────────┤
  │   web           │   worker                  │
  │  (HTTP handler) │  (background jobs)        │
  │                 │                           │
  │  3 processes    │   5 processes             │
  │  (light load)   │   (heavy load)            │
  └─────────────────┴───────────────────────────┘

HTTP traffic พุ่งก็ scale web process job queue ล้นก็ scale worker process แต่ละฝั่ง scale แยกกัน ไม่กระทบกัน

Vertical vs Horizontal Scaling

  VERTICAL SCALING (pre-12-factor):
  One fat process → add more CPU/RAM to the machine
  Limit: one machine, one process can only get so big

  HORIZONTAL SCALING (12-factor):
  Many small processes → add more instances
  Limit: practically unlimited (cloud elasticity)

Process Type

# Procfile (Heroku) or Kubernetes deployments — declares process types
web: uvicorn main:app --host 0.0.0.0 --port $PORT
worker: celery -A tasks worker --loglevel=info --concurrency=4
scheduler: celery -A tasks beat --loglevel=info
# Kubernetes: separate Deployments for separate process types
---
# web process
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service-web
spec:
  replicas: 3    # scale independently
  template:
    spec:
      containers:
      - name: order-service
        image: mycompany/order-service:v1.2.0
        command: ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

---
# worker process — same image, different command
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service-worker
spec:
  replicas: 5    # scale independently from web
  template:
    spec:
      containers:
      - name: order-service
        image: mycompany/order-service:v1.2.0   # same image!
        command: ["celery", "-A", "tasks", "worker"]

Auto-Scaling ใน Kubernetes

# Horizontal Pod Autoscaler — automatic process scaling
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: order-service-web-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service-web
  minReplicas: 2
  maxReplicas: 20
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

ใช้ thread แทน process ไม่ได้

ใช้ thread ใน process เพื่อทำ I/O concurrency ได้ แต่อย่าพึ่ง thread ในการ scale thread แชร์ memory กัน ต้องทำ synchronization บั๊กตามมาง่าย และ scale ได้แค่ในเครื่องเดียว ส่วน process แยกขาดจากกัน stateless และ deploy แยกได้ เรื่อง scale ให้ใช้ process


Factor 9: Disposability — Start ไว ปิดตัวเรียบร้อย

"Maximize robustness with fast startup and graceful shutdown."

กฎ

Process ของ app ต้อง start หรือ stop ได้ทุกเมื่อ หมายความว่า:

  • Start ไว: ตั้งแต่ process เริ่มจนพร้อมรับ request ต้องใช้เวลาน้อยที่สุด (เป้าคือ < 5 วินาที)
  • Graceful shutdown: พอได้ SIGTERM ให้หยุดรับ request ใหม่ ทำงานที่ค้างอยู่ให้เสร็จ แล้วค่อย exit แบบเรียบร้อย

Process ที่พร้อมทิ้งได้ (disposable) ช่วยให้ deploy ได้เร็ว scale ได้ยืดหยุ่น และระบบทนต่อ failure

ทำไมเรื่องนี้สำคัญ

ใน Kubernetes, pod เกิดและตายอยู่ตลอด ทั้งตอน deploy, ตอน scale, ตอน node ล่ม และตอน upgrade ถ้า app ใช้เวลา start 60 วินาที rolling deploy จะช้าจนทรมาน ถ้า app ไม่จัดการ SIGTERM ทุกครั้งที่ deploy request ที่กำลังทำอยู่จะหลุดหมด

Graceful Shutdown

import signal
import asyncio
from fastapi import FastAPI
import uvicorn

app = FastAPI()
is_shutting_down = False

@app.get("/health/live")
def liveness():
    return {"status": "alive"}

@app.get("/health/ready")
def readiness():
    # Stop serving traffic before we actually shut down
    if is_shutting_down:
        return {"status": "shutting_down"}, 503
    return {"status": "ready"}

@app.on_event("shutdown")
async def shutdown_event():
    global is_shutting_down
    is_shutting_down = True

    # Finish in-flight requests (uvicorn handles this)
    # Close database connections cleanly
    await database.disconnect()

    # Drain the message queue consumer
    await message_consumer.stop()

    print("Shutdown complete")
# Worker with graceful shutdown
import signal
import sys
from celery import Celery

app = Celery("tasks")

def graceful_shutdown(signum, frame):
    print("Received SIGTERM, finishing current task and shutting down...")
    # Celery's warm shutdown: finish current task, don't accept new ones
    app.control.broadcast("shutdown", destination=[f"celery@{socket.gethostname()}"])
    sys.exit(0)

signal.signal(signal.SIGTERM, graceful_shutdown)

Kubernetes Health Check

# deployment.yaml — health probes tell Kubernetes about app state
spec:
  containers:
  - name: order-service
    image: mycompany/order-service:v1.2.0

    # Startup probe: is the app done initializing?
    startupProbe:
      httpGet:
        path: /health/live
        port: 8000
      failureThreshold: 30      # allow up to 30 * 10s = 5 min to start
      periodSeconds: 10

    # Liveness probe: should Kubernetes restart this pod?
    livenessProbe:
      httpGet:
        path: /health/live
        port: 8000
      initialDelaySeconds: 0
      periodSeconds: 10
      failureThreshold: 3

    # Readiness probe: should this pod receive traffic?
    readinessProbe:
      httpGet:
        path: /health/ready
        port: 8000
      periodSeconds: 5
      failureThreshold: 2

    # Give the app time to finish in-flight requests
    lifecycle:
      preStop:
        exec:
          command: ["/bin/sh", "-c", "sleep 5"]

  terminationGracePeriodSeconds: 30   # total time before SIGKILL

ทำยังไงให้ Start ไว

  • Resource ที่หนัก (ML model, connection pool) ให้ lazy-load หรือไม่ก็ pre-warm ไว้ใน startup hook
  • ใช้ connection pooling จะได้ไม่ต้องเปิด DB connection 100 ตัวตอน startup
  • ทำ Docker image layer ให้เล็ก ใช้ Alpine base image และ multi-stage build
  • อย่ารัน database migration ตอน startup (ดูใน Factor 12)

Factor 10: Dev/Prod Parity — ปิดทุกช่องว่าง

"Keep development, staging, and production as similar as possible."

กฎ

แต่ก่อน development กับ production ห่างกันอยู่สามด้าน 12-factor app ออกแบบมาเพื่อลดทั้งสามด้านให้เหลือน้อยที่สุด

  THE THREE GAPS:

  ┌────────────────┬────────────────────────┬──────────────────────────┐
  │ Gap            │ Traditional            │ 12-Factor                │
  ├────────────────┼────────────────────────┼──────────────────────────┤
  │ Time Gap       │ Weeks or months between│ Deploy hours or minutes  │
  │                │ dev and production     │ after writing the code   │
  ├────────────────┼────────────────────────┼──────────────────────────┤
  │ Personnel Gap  │ Devs write code,       │ Devs who write code also │
  │                │ ops deploys it         │ own deployment           │
  ├────────────────┼────────────────────────┼──────────────────────────┤
  │ Tools Gap      │ Nginx in prod,         │ Same tools everywhere    │
  │                │ SQLite locally         │ (Docker makes this easy) │
  └────────────────┴────────────────────────┴──────────────────────────┘

ช่องว่างด้าน Tool อันตรายที่สุด

บั๊กแบบ "บนเครื่องผมก็รันได้นะ" ส่วนใหญ่มาจากช่องว่างด้าน tool นี่แหละ:

Service ทางลัดที่ชอบใช้บน local อันตรายตรงไหน
Database SQLite (local) vs PostgreSQL (prod) SQL dialect ไม่เหมือนกัน จัดการ NULL ไม่เหมือนกัน performance ก็ต่างกัน
Cache Dictionary cache (local) vs Redis (prod) Local cache ใช้ได้ปกติ แต่ Redis มี network latency และต้อง serialize ข้อมูล
Message Queue In-process queue vs Kafka (prod) Ordering guarantee ต่างกัน และพังคนละแบบ
Email Print ออก console vs SendGrid (prod) Email ใน console ไม่มีวัน bounce แต่ SendGrid bounce ได้
File Storage Local filesystem vs S3 (prod) ไฟล์ local อยู่รอดหลัง restart แต่ S3 ทำงานไม่เหมือนกัน

ทำแบบ 12-Factor: ใช้ Docker Compose ให้ Parity

# docker-compose.yml — production-equivalent services locally
services:
  app:
    build: .
    env_file: .env
    ports:
      - "8000:8000"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started

  postgres:
    image: postgres:16-alpine   # SAME major version as production
    environment:
      POSTGRES_DB: orders_dev
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine       # SAME major version as production

  kafka:
    image: confluentinc/cp-kafka:7.6.1   # SAME as production
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
    depends_on:
      - zookeeper

  zookeeper:
    image: confluentinc/cp-zookeeper:7.6.1

  mailhog:
    image: mailhog/mailhog     # catches emails in dev, shows them in a UI
    ports:
      - "1025:1025"   # SMTP
      - "8025:8025"   # Web UI

Mailhog: tool เด็ดสำหรับ dev/prod parity

Mailhog เป็น SMTP server สำหรับ development ที่ดัก email ขาออกทุกฉบับไว้ แล้วโชว์ใน web UI ที่ localhost:8025 บน local app คุยกับ smtp://mailhog:1025 ส่วนใน production คุยกับ smtp://sendgrid:587 SMTP protocol เดียวกัน โค้ดเดียวกัน ต่างกันแค่ env var SMTP_HOST


Factor 11: Logs — ส่งเป็น Stream ไม่เขียนลงไฟล์

"Treat logs as event streams."

กฎ

12-factor app ไม่สนเลยว่า output stream ของตัวเองจะไหลไปไหนหรือเก็บไว้ที่ไหน app แค่เขียน log ทุกบรรทัดออก stdout (จะใช้ stderr ด้วยก็ได้) เป็น event stream แบบไม่ buffer หนึ่ง event ต่อหนึ่งบรรทัด

หน้าที่ดักจับ route และเก็บ stream พวกนี้เป็นของ execution environment ไม่ใช่ของ app

ทำไมต้อง Stdout ไม่ใช่ไฟล์

  LOG FILES (anti-pattern):
  App writes → /var/log/app.log → need to rotate → need to ship → logstash polls the file

  Problems: log rotation complexity, disk fills up, hard to aggregate across 20 pods

  STDOUT (12-factor):
  App writes → stdout → container runtime captures → log aggregator collects

  Works the same regardless of how many pods you have. Zero configuration in the app.

Structured Logging

Log แบบ plain text query ยาก Structured log (JSON) ช่วยให้ filter, aggregate และตั้ง alert จาก field ที่ต้องการได้

# GOOD: structured JSON logging
import structlog
import logging
import sys

def configure_logging():
    structlog.configure(
        processors=[
            structlog.contextvars.merge_contextvars,
            structlog.processors.add_log_level,
            structlog.processors.TimeStamper(fmt="iso"),
            structlog.processors.JSONRenderer(),  # output as JSON
        ],
        wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
        logger_factory=structlog.PrintLoggerFactory(file=sys.stdout),
    )

log = structlog.get_logger()

# Each log line is a JSON object — queryable, parseable, monitorable
log.info("order_confirmed",
    order_id=str(order.id),
    customer_id=str(order.customer_id),
    total_amount=str(order.total.amount),
    currency=order.total.currency,
    item_count=len(order.line_items),
    duration_ms=elapsed_ms
)

ผลลัพธ์:

{"event": "order_confirmed", "level": "info", "timestamp": "2026-05-18T10:23:41Z",
 "order_id": "a1b2c3", "customer_id": "x9y8z7",
 "total_amount": "149.99", "currency": "USD", "item_count": 3, "duration_ms": 42}

Log Routing ใน Production

  App (writes to stdout)
       │
       ▼
  Container Runtime (Docker/containerd captures stdout)
       │
       ▼
  Log Collector (Fluentbit, Promtail, Fluent, CloudWatch Agent)
       │
       ▼
  Log Storage & Search (Loki, Elasticsearch, CloudWatch Logs, Splunk)
       │
       ▼
  Visualization & Alerting (Grafana, Kibana, CloudWatch Dashboards)
# Kubernetes: Fluentbit DaemonSet collects logs from all pods automatically
# No configuration needed in the app — it just writes to stdout
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluent-bit
  namespace: logging
spec:
  selector:
    matchLabels:
      name: fluent-bit
  template:
    spec:
      containers:
      - name: fluent-bit
        image: fluent/fluent-bit:3.1
        volumeMounts:
        - name: varlog
          mountPath: /var/log          # reads from node log directory
      volumes:
      - name: varlog
        hostPath:
          path: /var/log

Correlation ID: กุญแจของ distributed tracing

ในระบบ microservices request เดียวของ user อาจวิ่งผ่าน 5 service ใส่ correlation_id (หรือ trace_id) ไว้ในทุก log entry จะได้ตาม request ข้าม service ได้:

import uuid
from fastapi import Request
import structlog

async def correlation_id_middleware(request: Request, call_next):
    correlation_id = request.headers.get("X-Correlation-ID", str(uuid.uuid4()))
    structlog.contextvars.bind_contextvars(correlation_id=correlation_id)
    response = await call_next(request)
    response.headers["X-Correlation-ID"] = correlation_id
    return response

Factor 12: Admin Processes — งาน One-Off รันแบบเดียวกับ App

"Run admin/management tasks as one-off processes."

กฎ

งาน admin หรืองาน management ที่ทำครั้งเดียวจบ เช่น database migration, data backup หรือเปิด REPL session เข้าไปตรวจของ ต้องรันใน environment เดียวกันเป๊ะ กับ process ปกติของ app ใช้ codebase เดียวกัน config เดียวกัน dependency ชุดเดียวกัน แต่รันเป็น process แบบ one-off แยกออกมา ไม่ได้อยู่ใน process formation ปกติของ app

ตัวอย่าง Admin Process

  • Database schema migration
  • ล้าง session ที่หมดอายุออกจาก database
  • Seed ข้อมูลตั้งต้นให้ database ใหม่
  • รัน script แปลงข้อมูลแบบครั้งเดียวจบ
  • เปิด REPL เข้าไปดู state ของระบบที่รันอยู่

Anti-Pattern: รัน Migration ตอน App Startup

# BAD: running migrations on every pod startup
@app.on_event("startup")
async def startup():
    # This runs on EVERY pod startup:
    # - Pod 1 starts migration
    # - Pod 2 starts migration at the same time
    # - Race condition, table locks, broken state
    await run_migrations()  # DON'T DO THIS
    await database.connect()

ทำแบบ 12-Factor: Kubernetes Job

# Run migration as a separate one-off process before deploying the app
# Same image, same environment, different command

# Local / CI
docker run --rm \
  --env-file .env.production \
  mycompany/order-service:v1.2.0 \
  python manage.py migrate
# Kubernetes: run migration as a Job before rolling out the new Deployment
apiVersion: batch/v1
kind: Job
metadata:
  name: order-service-migrate-v1-2-0
spec:
  template:
    spec:
      restartPolicy: OnFailure
      containers:
      - name: migrate
        image: mycompany/order-service:v1.2.0   # same image as app
        command: ["python", "manage.py", "migrate"]
        envFrom:
        - configMapRef:
            name: order-service-config
        - secretRef:
            name: order-service-secrets
# Helm hook: run migration before upgrade
# templates/migration-job.yaml
metadata:
  annotations:
    "helm.sh/hook": pre-upgrade,pre-install
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded

Migration workflow ที่ใช้ได้จริง

  1. Build Docker image ใหม่ที่มีไฟล์ migration ชุดล่าสุด
  2. รัน migration Job กับ production database
  3. Migration ผ่าน ค่อย roll out Deployment ใหม่
  4. Migration พัง Deployment เก่าก็ยังรันอยู่ ไม่มี downtime

ไปไกลกว่า 12 Factor

12-Factor App เขียนไว้ตั้งแต่ปี 2011 เทคโนโลยี cloud-native ไปไกลมากแล้วตั้งแต่นั้น เลยมีคนเสนอ factor เพิ่มอีกหลายข้อสำหรับ application ยุคนี้

Factor 13: API First

ออกแบบ service contract (API) ให้เสร็จก่อนเขียน implementation สักบรรทัด ทุก service คือ platform service ภายในก็ต้องออกแบบอย่างพิถีพิถันไม่ต่างจาก public API

  • เขียน API ด้วย OpenAPI/Swagger, Protobuf หรือ AsyncAPI
  • Generate server stub และ client library จาก spec
  • ใส่ version ให้ API ตั้งแต่วันแรก
# openapi.yaml — define the contract first
openapi: "3.1.0"
info:
  title: Order Service API
  version: "1.0.0"
paths:
  /orders:
    post:
      summary: Place an order
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaceOrderRequest'
      responses:
        '201':
          description: Order created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'

Factor 14: Telemetry

แค่ log ไม่พอ cloud-native app ใน production ต้องมี observability ครบสามเสาหลัก:

  THE THREE PILLARS OF OBSERVABILITY

  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐
  │    LOGS      │  │   METRICS    │  │    TRACES    │
  │              │  │              │  │              │
  │ What happened│  │ How is it    │  │ Why is it    │
  │ (events)     │  │ performing?  │  │ slow?        │
  │              │  │ (numbers)    │  │ (causality)  │
  │ ELK, Loki    │  │ Prometheus   │  │ Jaeger,      │
  │ CloudWatch   │  │ Grafana      │  │ Zipkin, OTEL │
  └──────────────┘  └──────────────┘  └──────────────┘

ใช้ OpenTelemetry มาตรฐานกลางสำหรับทำ instrumentation ที่ไม่ผูกกับ vendor เจ้าไหน:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

tracer = trace.get_tracer("order-service")

def confirm_order(order_id: str):
    with tracer.start_as_current_span("confirm_order") as span:
        span.set_attribute("order.id", order_id)

        order = order_repo.find_by_id(order_id)
        span.set_attribute("order.customer_id", str(order.customer_id))

        order.confirm()
        order_repo.save(order)

        span.set_attribute("order.total", str(order.total.amount))
        return order

Factor 15: Authentication และ Authorization

ทุก call ระหว่าง service และทุก request จาก client ต้องผ่านการ authenticate ในโลก cloud-native แปลว่า:

  • mTLS (mutual TLS) ระหว่าง service ใช้ service mesh อย่าง Istio จัดการให้อัตโนมัติ
  • JWT (JSON Web Token) สำหรับ authenticate client แล้ว validate ที่ API Gateway
  • RBAC (Role-Based Access Control) สำหรับ authorization
  • Zero-trust networking อย่าเชื่อ request ไหนแค่เพราะมาจากใน cluster

12-Factor Compliance Checklist

ใช้ตารางนี้เป็น checklist เช็คทุก service ก่อน deploy:

Factor เช็คอะไร พลาดกันบ่อยตรงไหน
1 Codebase ☐ หนึ่ง service หนึ่ง repo ทุก deploy มาจากโค้ดชุดเดียว แยก git branch ตาม environment
2 Dependencies ☐ Commit lock file แล้ว ไม่เดาว่า system มี package อะไร ไม่มี package-lock.json, pip install แบบไม่ pin version
3 Config ☐ ไม่มี secret หรือ URL ในโค้ดหรือในไฟล์ config ที่ commit Hardcode DB password ไว้ใน config.py
4 Backing Services ☐ เรียก service ภายนอกทุกตัวผ่าน URL ใน env var Hardcode DB host, ตอน dev ใช้ SQLite บน local
5 Build/Release/Run ☐ CI build artifact, release ใส่ config, run แยกออกมา git pull บน server, แก้ hotfix ผ่าน SSH
6 Processes ☐ ไม่เก็บ session state ใน memory ไม่เขียนลง local filesystem เก็บ session เป็น dict ใน process, เขียนไฟล์ลง /tmp
7 Port Binding ☐ App เปิด port เอง ไม่ต้องติดตั้ง server ไว้ก่อน ต้องติดตั้ง Apache/IIS ไว้ก่อน
8 Concurrency ☐ Scale แนวนอนได้ เพราะ stateless รัน 2+ instance ไม่ได้เพราะติด state
9 Disposability ☐ จัดการ SIGTERM แบบ graceful มี health endpoint Deploy ทีไร request ที่ค้างอยู่หลุด, startup ช้า
10 Dev/Prod Parity ☐ ใช้ DB engine เดียวกันทั้ง local และ prod SQLite บน local แต่ PostgreSQL บน prod
11 Logs ☐ Log ออก stdout เป็น structured JSON ไม่เขียนลงไฟล์ เขียนลง /var/log/app.log, ไม่มี correlation ID
12 Admin Processes ☐ Migration รันเป็น Job แบบ one-off ไม่ได้รันตอน startup app.on_event("startup") รัน migration

Summary

12-Factor App เป็นวินัย ไม่ใช่ framework ไม่มีอะไรให้ติดตั้ง ต้องเอาไปใช้ผ่านการตัดสินใจอย่างตั้งใจในทุก layer ของ stack

แบ่ง factor ทั้งหมดได้เป็นสามกลุ่ม:

  PORTABILITY (Factors 1-4)
  Your app should run anywhere without special environment setup.
  → One codebase, explicit dependencies, config in env, services as resources

  DEPLOYABILITY (Factors 5-9)
  Your app should be deployable, scalable, and reliable without drama.
  → Separate stages, stateless processes, self-contained ports, horizontal scale, disposability

  OPERABILITY (Factors 10-12)
  Your app should be observable and manageable in production.
  → Prod parity, log streams, isolated admin tasks

ถ้ากำลังเริ่ม service ใหม่ เริ่มตามนี้:

  1. สร้าง git repo แล้วประกาศ dependency ทุกตัวพร้อม lock file
  2. สร้าง .env.example ที่มี config variable ครบทุกตัวที่ต้องใช้
  3. เขียน docker-compose.yml ที่จำลอง service แบบเดียวกับ production ไว้บน local
  4. ตั้ง Dockerfile ให้ log ออก stdout และจัดการ SIGTERM ได้
  5. ทำ CI/CD pipeline ที่ build ครั้งเดียว แล้ว promote artifact ตัวเดิมไปทีละ environment
  6. ใส่ liveness และ readiness probe
  7. เขียน migration เป็น script แยก อย่าใส่ไว้ใน startup hook

ทำแบบนี้ให้สม่ำเสมอ แล้วคุณจะได้ service ที่ scale ถึงหลักล้าน user โดยไม่ต้องรื้อ architecture, server ล่มข้อมูลก็ไม่หาย, deploy เสร็จในไม่กี่วินาทีแบบไม่มี downtime และ debug ใน production ได้โดยไม่ต้อง SSH เข้าไป


มีคำถามหรืออยากคุยเรื่อง cloud-native pattern? ติดต่อผมได้ทาง LinkedIn, X หรือส่ง email มาได้เลย

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.