Lesson 4Serverless

Lambda and API Gateway

Serverless ช่วยให้ทีม deploy code โดยไม่ต้องจัดการ servers แต่ยังต้องออกแบบ timeout, memory, concurrency, permissions, retries และ observability ให้ถูกต้อง

AWS Lambda

AWS Lambda รัน code ตาม events โดย AWS จัดการ compute infrastructure, scaling และ runtime environment ให้ ทีมรับผิดชอบ application code, configuration, IAM execution role, dependencies, logs และ failure handling

Execution role และ permissions

Lambda execution role คือ IAM Role ที่ function ใช้เรียก AWS services เช่น S3, DynamoDB, SQS หรือ Secrets Manager ควรให้ permission เท่าที่จำเป็นและแยก role ตาม function หรือ bounded context

exports.handler = async (event) => {
  console.log(JSON.stringify({ eventType: "request", records: event.Records?.length || 0 }));
  return {
    statusCode: 200,
    body: JSON.stringify({ ok: true })
  };
};

Timeout, memory และ concurrency

  • Timeout: เวลาสูงสุดที่ function รันได้ ถ้าสั้นเกินไปจะ fail ถ้ายาวเกินไปอาจซ่อน dependency ที่ช้า
  • Memory: มีผลต่อ CPU ที่ได้รับด้วย ต้อง benchmark ไม่ใช่เดาจาก RAM อย่างเดียว
  • Concurrency: จำนวน invocations ที่รันพร้อมกัน ต้องควบคุมเพื่อป้องกัน downstream overload

API Gateway

API Gateway เป็น front door สำหรับ APIs รองรับ HTTP, REST และ WebSocket APIs พร้อม features เช่น authorization, throttling, logging, custom domain, canary release และ integration กับ Lambda หรือ backend อื่น

ClientHTTP request
API GatewayAuth, throttling, logs
LambdaBusiness logic
AWS servicesDynamoDB/S3/SQS

Step Functions

Step Functions ใช้สร้าง workflows หรือ state machines สำหรับ orchestrate หลาย steps เช่น retry, catch, choice, human approval หรือ long-running process เหมาะกว่าเขียน orchestration logic ทั้งหมดไว้ใน Lambda function เดียว

Common mistakes

  • ให้ Lambda execution role กว้างเกินไป เช่น * ทุก resource
  • ไม่ตั้ง reserved concurrency ทำให้ traffic spike ยิง database หรือ third-party API จนล่ม
  • ใช้ Lambda ทำ long-running workflow ซับซ้อนแทน Step Functions

Review questions

  1. Lambda execution role ใช้ทำอะไร?
  2. Memory ของ Lambda มีผลต่อ performance อย่างไร?
  3. API Gateway เป็น front door ให้ backend แบบใดได้บ้าง?