Home > Blog > tech

Serverless คืออะไร? สอน AWS Lambda, Cloud Functions และ Function as a Service (FaaS) 2026

serverless faas guide
Serverless FaaS Guide 2026
2026-04-08 | tech | 3500 words

Serverless Computing เป็นหนึ่งในเทรนด์ที่เปลี่ยนแปลงวงการพัฒนาซอฟต์แวร์มากที่สุดในช่วงหลายปีที่ผ่านมา แนวคิดที่ว่า "ไม่ต้องจัดการ Server เอง" ทำให้นักพัฒนาสามารถมุ่งเน้นไปที่การเขียน Business Logic โดยไม่ต้องกังวลเรื่อง Infrastructure ในปี 2026 Serverless ได้กลายเป็นทางเลือกหลักสำหรับหลายประเภทของ Workload ตั้งแต่ Web API ไปจนถึง Data Processing และ IoT

บทความนี้จะพาคุณเข้าใจ Serverless อย่างครบถ้วน ตั้งแต่แนวคิดพื้นฐาน ไปจนถึงการใช้งานจริงกับ AWS Lambda, Google Cloud Functions, Azure Functions และ Cloudflare Workers พร้อม Patterns, Best Practices และข้อควรระวัง

Serverless คืออะไร?

Serverless คือ Cloud Computing Model ที่ Cloud Provider จัดการ Infrastructure ทั้งหมดให้ รวมถึงการ Provision Server, Scaling, Patching และ Maintenance นักพัฒนาแค่เขียน Code แล้ว Deploy ขึ้นไป ไม่ต้องคิดเรื่อง Server เลย

คำว่า "Serverless" ไม่ได้แปลว่า "ไม่มี Server" แต่แปลว่า "คุณไม่ต้องจัดการ Server" Server ยังคงมีอยู่ แต่ Cloud Provider เป็นคนดูแลทั้งหมด คุณจ่ายเงินเฉพาะตอนที่ Code ทำงานจริง (Pay-per-execution) ไม่ต้องจ่ายค่า Server ที่ว่าง

Serverless แบ่งออกเป็น 2 ประเภทหลัก คือ Function as a Service (FaaS) เช่น AWS Lambda, Cloud Functions ที่รัน Code เป็นฟังก์ชันเดี่ยวๆ และ Backend as a Service (BaaS) เช่น Firebase, Auth0, Algolia ที่ให้บริการ Backend สำเร็จรูปผ่าน API

Serverless vs Containers vs VMs

ด้านVirtual MachinesContainersServerless
AbstractionHardware LevelOS LevelFunction Level
Startup Timeนาทีวินาทีมิลลิวินาที (Warm) / วินาที (Cold)
ScalingManual / Auto (ช้า)Orchestrator (K8s)Automatic (ทันที)
Cost Modelจ่ายตาม Instance (ตลอดเวลา)จ่ายตาม Instanceจ่ายตาม Execution (ใช้จริง)
ManagementOS + Runtime + AppRuntime + AppApp เท่านั้น
StateStatefulStateless/StatefulStateless
Max Runtimeไม่จำกัดไม่จำกัดจำกัด (15 นาที AWS Lambda)
Vendor Lock-inต่ำต่ำสูง
เลือกใช้อะไรดี? ใช้ Serverless สำหรับ Event-driven workload, API ที่มี Traffic ไม่สม่ำเสมอ, Background jobs. ใช้ Containers สำหรับ Long-running services, Microservices ที่ต้องการ Control. ใช้ VMs สำหรับ Legacy apps, Workload ที่ต้องการ Full control.

Function as a Service (FaaS) คืออะไร?

FaaS คือ Serverless Computing Model ที่ให้คุณรัน Code เป็น Function เดี่ยวๆ โดยแต่ละ Function จะถูก Trigger จาก Event ต่างๆ เช่น HTTP Request, Message Queue, File Upload, Timer, Database Change เป็นต้น

หลักการทำงานของ FaaS คือ เมื่อมี Event เข้ามา Cloud Provider จะจัดสรร Computing Resource ให้อัตโนมัติ รัน Function ของคุณ ส่ง Response กลับ แล้วคืน Resource ไม่ว่าจะมี 1 Request หรือ 1 ล้าน Request ระบบจะ Scale ให้อัตโนมัติ คุณไม่ต้องทำอะไรเลย

ข้อดีของ FaaS ได้แก่ ไม่ต้องจัดการ Server, Auto-scaling ทันที, จ่ายเฉพาะตอนใช้งาน (ถ้าไม่มี Request ไม่ต้องจ่าย), Deploy ง่ายและเร็ว, Built-in High Availability และ Focus ที่ Business Logic ได้เต็มที่

AWS Lambda: FaaS ที่ได้รับความนิยมมากที่สุด

AWS Lambda เป็น FaaS Service ของ Amazon Web Services ที่เปิดตัวตั้งแต่ปี 2014 เป็นผู้บุกเบิกตลาด Serverless และยังคงเป็น FaaS ที่ได้รับความนิยมมากที่สุดในปี 2026 รองรับหลายภาษา เช่น Python, Node.js, Java, Go, .NET, Ruby และ Custom Runtime

สร้าง Lambda Function แรก

# handler.py - Lambda Function แรกของคุณ
import json

def lambda_handler(event, context):
    """
    event: ข้อมูลที่ส่งเข้ามา (JSON)
    context: ข้อมูลเกี่ยวกับ Runtime Environment
    """
    name = event.get('queryStringParameters', {}).get('name', 'World')

    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps({
            'message': f'Hello, {name}!',
            'request_id': context.aws_request_id,
            'remaining_time_ms': context.get_remaining_time_in_millis()
        })
    }

# ตัวอย่าง Lambda ที่ Process S3 Event
def s3_handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        size = record['s3']['object']['size']

        print(f"New file: s3://{bucket}/{key} ({size} bytes)")

        # Process file...
        # เช่น Resize image, Parse CSV, etc.

    return {'statusCode': 200, 'body': 'Processed'}

Deploy Lambda ด้วย AWS CLI

# 1. สร้าง ZIP Package
zip function.zip handler.py

# 2. สร้าง Lambda Function
aws lambda create-function \
  --function-name my-function \
  --runtime python3.12 \
  --handler handler.lambda_handler \
  --role arn:aws:iam::123456789:role/lambda-role \
  --zip-file fileb://function.zip \
  --timeout 30 \
  --memory-size 256

# 3. ทดสอบ
aws lambda invoke \
  --function-name my-function \
  --payload '{"queryStringParameters":{"name":"SiamCafe"}}' \
  response.json

# 4. อัปเดต Code
zip function.zip handler.py
aws lambda update-function-code \
  --function-name my-function \
  --zip-file fileb://function.zip

# 5. ดู Logs
aws logs tail /aws/lambda/my-function --follow

Lambda Triggers (Event Sources)

Lambda สามารถถูก Trigger ได้จาก Event Sources หลากหลาย ดังนี้

Event SourceUse Case
API GatewayREST API, WebSocket API
S3File upload processing, Image resizing
DynamoDB StreamsDatabase change events
SQSMessage queue processing
SNSPush notifications, Fan-out
EventBridgeScheduled tasks, Event routing
KinesisReal-time data streaming
CloudWatch EventsCron jobs, Monitoring alerts
CognitoUser authentication triggers
IoT CoreIoT device events

Lambda Layers

Lambda Layers ช่วยให้คุณแชร์ Code และ Dependencies ระหว่าง Lambda Functions หลายตัวได้ แทนที่จะ Bundle Dependencies ไปกับทุก Function แยกเป็น Layer แล้วแชร์ใช้ ช่วยลดขนาด Deployment Package และง่ายต่อการ Update Dependencies

# สร้าง Layer สำหรับ Python Dependencies
mkdir -p python/lib/python3.12/site-packages
pip install requests boto3 -t python/lib/python3.12/site-packages/
zip -r layer.zip python/

# Deploy Layer
aws lambda publish-layer-version \
  --layer-name my-dependencies \
  --zip-file fileb://layer.zip \
  --compatible-runtimes python3.12

# ใช้ Layer กับ Function
aws lambda update-function-configuration \
  --function-name my-function \
  --layers arn:aws:lambda:ap-southeast-1:123456789:layer:my-dependencies:1

Cold Start คืออะไร?

Cold Start คือเวลาที่ Cloud Provider ต้องใช้ในการเตรียม Execution Environment ให้กับ Lambda Function ที่ไม่ได้ถูกเรียกใช้มาสักพัก ประกอบด้วยการดาวน์โหลด Code, สร้าง Container, โหลด Runtime และ Initialize Application

Cold Start เกิดขึ้นเมื่อ Function ถูกเรียกครั้งแรก, Function ไม่ได้ถูกเรียกนานจนถูก Recycle (ประมาณ 5-15 นาที), มี Request มากจนต้องสร้าง Instance ใหม่ (Scale out) หรือมีการ Deploy Code ใหม่

เวลา Cold Start ขึ้นอยู่กับหลายปัจจัย ภาษาที่ใช้ (Python/Node.js เร็วกว่า Java/.NET มาก), ขนาดของ Deployment Package, จำนวน Dependencies, VPC Configuration (ถ้าอยู่ใน VPC จะช้ากว่า) และ Memory ที่กำหนดให้ (Memory มากขึ้น CPU มากขึ้น เร็วขึ้น)

Cold Start Optimization

# 1. Provisioned Concurrency (จอง Instance ไว้ล่วงหน้า)
aws lambda put-provisioned-concurrency-config \
  --function-name my-function \
  --qualifier prod \
  --provisioned-concurrent-executions 10

# 2. ลด Package Size
# ใช้ Lambda Layers แยก Dependencies
# ลบไฟล์ที่ไม่จำเป็น (.pyc, tests, docs)

# 3. Initialize นอก Handler (Global Scope)
import boto3

# สร้าง Client นอก Handler → reuse ได้เมื่อ Warm
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('my-table')

def lambda_handler(event, context):
    # ใช้ table ที่สร้างไว้แล้ว (ไม่ต้องสร้างใหม่)
    response = table.get_item(Key={'id': event['id']})
    return response['Item']

# 4. ใช้ Python/Node.js แทน Java (Cold Start เร็วกว่า 10x)

# 5. SnapStart (Java เท่านั้น)
# Lambda จะ Snapshot หลัง Initialization แล้ว Restore จาก Snapshot
aws lambda update-function-configuration \
  --function-name my-java-function \
  --snap-start ApplyOn=PublishedVersions

# 6. เพิ่ม Memory (ได้ CPU มากขึ้นด้วย)
aws lambda update-function-configuration \
  --function-name my-function \
  --memory-size 1024  # Default 128 MB
Cold Start ในปี 2026: AWS Lambda SnapStart ลด Cold Start ของ Java ลงได้ 90 เปอร์เซ็นต์ Cloudflare Workers มี Cold Start ต่ำกว่า 1ms เนื่องจากใช้ V8 Isolates แทน Container ถ้า Cold Start เป็นปัญหาจริงๆ ให้พิจารณา Provisioned Concurrency หรือ Cloudflare Workers

Google Cloud Functions

Google Cloud Functions เป็น FaaS ของ Google Cloud Platform รองรับ Node.js, Python, Go, Java, .NET, Ruby และ PHP มี 2 Generation คือ 1st gen (เดิม) และ 2nd gen (ใหม่ สร้างบน Cloud Run)

# main.py - Cloud Function (HTTP Trigger)
import functions_framework

@functions_framework.http
def hello(request):
    """HTTP Cloud Function"""
    name = request.args.get('name', 'World')
    return f'Hello, {name}!'

# Cloud Function (Pub/Sub Trigger)
import base64
import functions_framework

@functions_framework.cloud_event
def process_message(cloud_event):
    """Pub/Sub Cloud Function"""
    data = base64.b64decode(cloud_event.data["message"]["data"]).decode()
    print(f"Received message: {data}")

# Cloud Function (Cloud Storage Trigger)
@functions_framework.cloud_event
def process_file(cloud_event):
    """Storage Cloud Function"""
    data = cloud_event.data
    bucket = data["bucket"]
    name = data["name"]
    print(f"File uploaded: gs://{bucket}/{name}")

# Deploy
# gcloud functions deploy hello \
#   --gen2 \
#   --runtime=python312 \
#   --region=asia-southeast1 \
#   --source=. \
#   --entry-point=hello \
#   --trigger-http \
#   --allow-unauthenticated \
#   --memory=256MB \
#   --timeout=60s

Azure Functions

Azure Functions เป็น FaaS ของ Microsoft Azure รองรับ C#, JavaScript, TypeScript, Python, Java, PowerShell และ Custom Handlers มีจุดเด่นคือ Durable Functions ที่ช่วยจัดการ Stateful Workflows ใน Serverless

# function_app.py - Azure Function (Python v2 Model)
import azure.functions as func
import json

app = func.FunctionApp()

@app.route(route="hello", auth_level=func.AuthLevel.ANONYMOUS)
def hello(req: func.HttpRequest) -> func.HttpResponse:
    name = req.params.get('name', 'World')
    return func.HttpResponse(
        json.dumps({"message": f"Hello, {name}!"}),
        mimetype="application/json"
    )

# Timer Trigger (Cron Job)
@app.timer_trigger(schedule="0 */5 * * * *", arg_name="timer")
def scheduled_task(timer: func.TimerRequest) -> None:
    if timer.past_due:
        print("Timer is past due!")
    print("Running scheduled task...")

# Blob Storage Trigger
@app.blob_trigger(arg_name="blob",
                  path="uploads/{name}",
                  connection="AzureWebJobsStorage")
def process_blob(blob: func.InputStream):
    print(f"Blob trigger: {blob.name}, Size: {blob.length} bytes")

# Durable Functions (Orchestration)
import azure.durable_functions as df

@app.orchestration_trigger(context_name="context")
def order_processing(context: df.DurableOrchestrationContext):
    # Step 1: Validate Order
    order = context.get_input()
    validation = yield context.call_activity("validate_order", order)

    # Step 2: Process Payment
    payment = yield context.call_activity("process_payment", order)

    # Step 3: Ship Order
    shipping = yield context.call_activity("ship_order", order)

    return {"validation": validation, "payment": payment, "shipping": shipping}

Cloudflare Workers

Cloudflare Workers เป็น FaaS ที่รันบน Edge Network ของ Cloudflare กระจายอยู่ทั่วโลกมากกว่า 300 จุด ใช้ V8 Isolates แทน Container ทำให้ Cold Start ต่ำมาก (ต่ำกว่า 1ms) เหมาะสำหรับ Workload ที่ต้องการ Low Latency

// worker.js - Cloudflare Worker
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const name = url.searchParams.get('name') || 'World';

    return new Response(
      JSON.stringify({ message: `Hello, ${name}!` }),
      {
        headers: { 'Content-Type': 'application/json' }
      }
    );
  },

  // Scheduled Event (Cron Trigger)
  async scheduled(event, env, ctx) {
    console.log('Cron trigger fired at:', event.cron);
    // ทำ Scheduled Task...
  }
};

// ใช้ KV Storage (Key-Value)
export default {
  async fetch(request, env) {
    // อ่าน
    const value = await env.MY_KV.get('key');

    // เขียน
    await env.MY_KV.put('key', 'value', { expirationTtl: 3600 });

    // ใช้ D1 Database (SQLite on Edge)
    const results = await env.DB.prepare(
      'SELECT * FROM users WHERE id = ?'
    ).bind(1).all();

    return Response.json(results);
  }
};

// wrangler.toml - Configuration
// name = "my-worker"
// main = "worker.js"
// compatibility_date = "2026-01-01"
//
// [[kv_namespaces]]
// binding = "MY_KV"
// id = "abc123"
//
// [[d1_databases]]
// binding = "DB"
// database_name = "my-db"
// database_id = "def456"

// Deploy: npx wrangler deploy

Serverless Frameworks

Serverless Framework

Serverless Framework เป็น Framework ที่ได้รับความนิยมมากที่สุดสำหรับการพัฒนา Serverless Application รองรับ AWS, Azure, Google Cloud และอื่นๆ ช่วย Abstract ความซับซ้อนของ Cloud Provider ให้ใช้ Configuration File เดียว

# serverless.yml
service: my-api
frameworkVersion: '4'

provider:
  name: aws
  runtime: python3.12
  region: ap-southeast-1
  stage: ${opt:stage, 'dev'}
  environment:
    TABLE_NAME: ${self:service}-${self:provider.stage}
  iam:
    role:
      statements:
        - Effect: Allow
          Action:
            - dynamodb:GetItem
            - dynamodb:PutItem
            - dynamodb:Query
          Resource: !GetAtt UsersTable.Arn

functions:
  getUser:
    handler: handlers/users.get
    events:
      - httpApi:
          path: /users/{id}
          method: get

  createUser:
    handler: handlers/users.create
    events:
      - httpApi:
          path: /users
          method: post

  processQueue:
    handler: handlers/queue.process
    events:
      - sqs:
          arn: !GetAtt ProcessingQueue.Arn
          batchSize: 10

  dailyReport:
    handler: handlers/reports.daily
    events:
      - schedule: cron(0 9 * * ? *)

resources:
  Resources:
    UsersTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:provider.environment.TABLE_NAME}
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH

    ProcessingQueue:
      Type: AWS::SQS::Queue
      Properties:
        QueueName: ${self:service}-queue-${self:provider.stage}

# Deploy
# serverless deploy --stage prod

AWS SAM (Serverless Application Model)

# template.yaml (SAM)
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My Serverless API

Globals:
  Function:
    Timeout: 30
    Runtime: python3.12
    MemorySize: 256
    Environment:
      Variables:
        TABLE_NAME: !Ref UsersTable

Resources:
  GetUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.get_user
      CodeUri: src/
      Events:
        GetUser:
          Type: HttpApi
          Properties:
            Path: /users/{id}
            Method: get

  CreateUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.create_user
      CodeUri: src/
      Events:
        CreateUser:
          Type: HttpApi
          Properties:
            Path: /users
            Method: post

  UsersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH

# Commands
# sam build
# sam local invoke GetUserFunction --event events/get.json
# sam local start-api  (ทดสอบ Local)
# sam deploy --guided

SST (Serverless Stack)

SST เป็น Framework สมัยใหม่ที่สร้างบน AWS CDK ให้ Developer Experience ที่ดีเยี่ยม มี Live Lambda Development ที่ช่วยให้ Debug Lambda Function แบบ Real-time บนเครื่อง Local ได้

// sst.config.ts
export default {
  config() {
    return { name: "my-app", region: "ap-southeast-1" };
  },
  stacks(app) {
    app.stack(function API({ stack }) {
      const table = new Table(stack, "Users", {
        fields: { id: "string" },
        primaryIndex: { partitionKey: "id" }
      });

      const api = new Api(stack, "Api", {
        routes: {
          "GET /users/{id}": "packages/functions/src/users.get",
          "POST /users": "packages/functions/src/users.create"
        }
      });

      api.bind([table]);

      stack.addOutputs({
        ApiUrl: api.url
      });
    });
  }
};

Event-Driven Architecture กับ Serverless

Event-Driven Architecture (EDA) เป็น Architecture Pattern ที่เหมาะกับ Serverless มากที่สุด เพราะ Lambda Function ถูกออกแบบมาให้ Trigger จาก Event อยู่แล้ว ทุกอย่างเริ่มจาก Event แล้ว Function จะทำงานตอบสนอง

# ตัวอย่าง Event-Driven E-Commerce
# 1. User สั่งซื้อ → API Gateway → Order Lambda
# 2. Order Lambda → สร้าง Order ใน DynamoDB
# 3. DynamoDB Stream → Payment Lambda
# 4. Payment Lambda → ตัดเงิน → SNS Topic
# 5. SNS Topic → Email Lambda (ส่งอีเมล)
# 6. SNS Topic → Inventory Lambda (ลด Stock)
# 7. SNS Topic → Analytics Lambda (บันทึกข้อมูล)

# order_handler.py
import boto3, json, uuid
from datetime import datetime

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('orders')

def create_order(event, context):
    body = json.loads(event['body'])
    order_id = str(uuid.uuid4())

    order = {
        'id': order_id,
        'customer_id': body['customer_id'],
        'items': body['items'],
        'total': body['total'],
        'status': 'PENDING',
        'created_at': datetime.utcnow().isoformat()
    }

    table.put_item(Item=order)

    return {
        'statusCode': 201,
        'body': json.dumps({'order_id': order_id, 'status': 'PENDING'})
    }

# payment_handler.py (Triggered by DynamoDB Stream)
def process_payment(event, context):
    for record in event['Records']:
        if record['eventName'] == 'INSERT':
            order = record['dynamodb']['NewImage']
            order_id = order['id']['S']
            total = float(order['total']['N'])

            # Process payment...
            print(f"Processing payment for order {order_id}: ${total}")

            # Publish to SNS
            sns = boto3.client('sns')
            sns.publish(
                TopicArn='arn:aws:sns:...:order-completed',
                Message=json.dumps({'order_id': order_id, 'status': 'PAID'})
            )

API Gateway + Lambda

การใช้ API Gateway ร่วมกับ Lambda เป็นรูปแบบที่นิยมมากที่สุดสำหรับการสร้าง REST API แบบ Serverless ในปี 2026 AWS มี HTTP API (แนะนำ ถูกกว่า เร็วกว่า) และ REST API (ฟีเจอร์มากกว่า)

# API Gateway + Lambda (SAM Template)
Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.12
      Events:
        RootGet:
          Type: HttpApi
          Properties:
            Path: /
            Method: get
        ProxyAll:
          Type: HttpApi
          Properties:
            Path: /{proxy+}
            Method: ANY

# app.py - ใช้ Mangum เพื่อรัน FastAPI บน Lambda
from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

@app.get("/")
def root():
    return {"message": "Hello from Lambda!"}

@app.get("/users/{user_id}")
def get_user(user_id: str):
    return {"user_id": user_id, "name": "John"}

@app.post("/users")
def create_user(user: dict):
    return {"created": True, "user": user}

# Lambda Handler
handler = Mangum(app)

Serverless Database: DynamoDB & Firestore

Serverless Application ต้องการ Database ที่ Serverless ด้วย คือไม่ต้องจัดการ Server, Auto-scaling และจ่ายตามการใช้งาน DynamoDB (AWS) และ Firestore (Google Cloud) เป็นตัวเลือกยอดนิยม

# DynamoDB with Lambda (Python)
import boto3
from boto3.dynamodb.conditions import Key

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')

def get_user(event, context):
    user_id = event['pathParameters']['id']
    response = table.get_item(Key={'id': user_id})
    return {
        'statusCode': 200,
        'body': json.dumps(response.get('Item', {}))
    }

def create_user(event, context):
    user = json.loads(event['body'])
    table.put_item(Item=user)
    return {'statusCode': 201, 'body': json.dumps(user)}

def list_users(event, context):
    response = table.scan(Limit=100)
    return {
        'statusCode': 200,
        'body': json.dumps(response['Items'])
    }

def query_by_email(event, context):
    email = event['queryStringParameters']['email']
    response = table.query(
        IndexName='email-index',
        KeyConditionExpression=Key('email').eq(email)
    )
    return {
        'statusCode': 200,
        'body': json.dumps(response['Items'])
    }

Serverless Pricing Model

หนึ่งในข้อดีหลักของ Serverless คือ Pricing Model แบบ Pay-per-use ที่คุณจ่ายเฉพาะตอนที่ Code ทำงานจริง มาดูรายละเอียดของแต่ละ Provider กัน

ProviderFree Tier (ต่อเดือน)ราคา (ต่อ 1M Requests)ราคา Compute
AWS Lambda1M requests + 400,000 GB-s$0.20$0.0000166667 / GB-s
Google Cloud Functions2M requests + 400,000 GB-s$0.40$0.0000025 / GHz-s
Azure Functions1M requests + 400,000 GB-s$0.20$0.000016 / GB-s
Cloudflare Workers100K requests/day$0.30 (Bundled)Included

ตัวอย่างการคำนวณค่าใช้จ่าย AWS Lambda สำหรับ API ที่มี 10 ล้าน Requests ต่อเดือน แต่ละ Request ใช้เวลา 200ms และ Memory 256MB จะคำนวณได้ดังนี้ Request Cost เท่ากับ 10M คูณ 0.20 ดอลลาร์ ต่อ 1M เท่ากับ 2 ดอลลาร์ Compute Cost เท่ากับ 10M คูณ 0.2s คูณ 0.25GB คูณ 0.0000166667 เท่ากับประมาณ 8.33 ดอลลาร์ รวมทั้งหมดประมาณ 10.33 ดอลลาร์ต่อเดือน ซึ่งถูกมากเมื่อเทียบกับการรัน EC2 Instance ตลอด 24 ชั่วโมง

ข้อควรระวังเรื่องค่าใช้จ่าย: Serverless ถูกสำหรับ Workload ที่มี Traffic น้อยถึงปานกลาง แต่ถ้า Traffic สูงมากและคงที่ตลอดเวลา การใช้ Container หรือ EC2 Reserved Instance อาจถูกกว่า ต้องคำนวณเปรียบเทียบก่อนเสมอ

Serverless ใช้ทำอะไรได้บ้าง?

Web APIs

สร้าง REST API หรือ GraphQL API ด้วย API Gateway + Lambda เหมาะสำหรับ API ที่มี Traffic ไม่สม่ำเสมอ เช่น API สำหรับ Mobile App, Webhook, Internal Tools

Scheduled Tasks (Cron Jobs)

ใช้ EventBridge Schedule หรือ CloudWatch Events เรียก Lambda Function ตามเวลาที่กำหนด เช่น สร้าง Daily Report, Cleanup ข้อมูลเก่า, ส่ง Email Notification

Event Processing

ประมวลผล Event จาก S3 (เช่น Resize รูปภาพเมื่อ Upload), SQS/SNS (เช่น Process Order), DynamoDB Streams (เช่น Sync ข้อมูลไป Elasticsearch), Kinesis (เช่น Real-time Analytics)

Data Processing

ETL (Extract, Transform, Load) Pipeline, Log Processing, CSV/JSON Parsing, Machine Learning Inference

Chatbots & IoT

สร้าง Chatbot บน Slack/LINE/Discord, ประมวลผลข้อมูลจาก IoT Devices

ข้อจำกัดของ Serverless

แม้ Serverless จะมีข้อดีมากมาย แต่ก็มีข้อจำกัดที่ต้องรู้ก่อนเลือกใช้

ข้อจำกัดรายละเอียดวิธีแก้ไข
Execution TimeoutAWS Lambda สูงสุด 15 นาทีใช้ Step Functions สำหรับ Long-running tasks
Cold StartLatency สูงขึ้นเมื่อ Function ไม่ได้ถูกใช้Provisioned Concurrency, SnapStart
Statelessไม่สามารถเก็บ State ระหว่าง Invocationsใช้ DynamoDB, Redis, S3 เก็บ State
Vendor Lock-inย้าย Provider ยากใช้ Serverless Framework, Abstract Provider
Debugging ยากดู Logs ยากกว่า Traditional Appใช้ CloudWatch, X-Ray, Datadog
Package SizeAWS Lambda สูงสุด 250 MB (unzipped)ใช้ Layers, Container Image (10 GB)
Concurrency LimitAWS Lambda default 1,000 concurrentขอเพิ่ม Limit, ใช้ Reserved Concurrency

Serverless Patterns

Fan-out Pattern

ใช้ SNS หรือ EventBridge กระจาย Event ไปยังหลาย Lambda Functions พร้อมกัน เหมาะสำหรับ Use Case ที่ต้องทำหลายอย่างจาก Event เดียว เช่น เมื่อ Order สำเร็จ ต้อง (1) ส่งอีเมล (2) อัปเดต Inventory (3) บันทึก Analytics พร้อมกัน

Saga Pattern

ใช้ AWS Step Functions จัดการ Distributed Transaction ที่มีหลายขั้นตอน ถ้าขั้นตอนใดล้มเหลว จะทำ Compensating Transaction (Rollback) อัตโนมัติ เหมาะสำหรับ E-Commerce Order Processing, Payment Processing, Booking Systems

# Step Functions Definition (ASL)
{
  "Comment": "Order Processing Saga",
  "StartAt": "ValidateOrder",
  "States": {
    "ValidateOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:validate-order",
      "Next": "ProcessPayment",
      "Catch": [{
        "ErrorEquals": ["ValidationError"],
        "Next": "OrderFailed"
      }]
    },
    "ProcessPayment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:process-payment",
      "Next": "ShipOrder",
      "Catch": [{
        "ErrorEquals": ["PaymentError"],
        "Next": "RefundPayment"
      }]
    },
    "ShipOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:ship-order",
      "End": true,
      "Catch": [{
        "ErrorEquals": ["ShippingError"],
        "Next": "CancelShipment"
      }]
    },
    "RefundPayment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:refund",
      "Next": "OrderFailed"
    },
    "CancelShipment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:cancel-shipment",
      "Next": "RefundPayment"
    },
    "OrderFailed": {
      "Type": "Fail",
      "Error": "OrderProcessingFailed"
    }
  }
}

Monitoring Serverless: CloudWatch & Datadog

การ Monitor Serverless Application แตกต่างจาก Traditional Application เพราะไม่มี Server ให้ Monitor ต้องโฟกัสที่ Function-level Metrics แทน

# CloudWatch Metrics ที่ต้องดู:
# - Invocations: จำนวนครั้งที่ Function ถูกเรียก
# - Duration: เวลาที่ Function ใช้ทำงาน
# - Errors: จำนวน Errors
# - Throttles: จำนวนครั้งที่ถูก Throttle (เกิน Concurrency Limit)
# - ConcurrentExecutions: จำนวน Instance ที่รันพร้อมกัน
# - IteratorAge: สำหรับ Stream-based triggers (ยิ่งสูง ยิ่ง lag)

# CloudWatch Alarm
aws cloudwatch put-metric-alarm \
  --alarm-name "Lambda-Errors-High" \
  --metric-name Errors \
  --namespace AWS/Lambda \
  --statistic Sum \
  --period 300 \
  --threshold 10 \
  --comparison-operator GreaterThanThreshold \
  --evaluation-periods 1 \
  --dimensions Name=FunctionName,Value=my-function \
  --alarm-actions arn:aws:sns:...:alerts

# AWS X-Ray (Distributed Tracing)
# เพิ่มใน Lambda Configuration
aws lambda update-function-configuration \
  --function-name my-function \
  --tracing-config Mode=Active

# ใช้ X-Ray SDK ใน Code
from aws_xray_sdk.core import patch_all
patch_all()  # Automatically trace AWS SDK calls

# Structured Logging (Best Practice)
import json, logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def handler(event, context):
    logger.info(json.dumps({
        "event": "order_created",
        "order_id": "12345",
        "customer_id": "67890",
        "amount": 99.99,
        "request_id": context.aws_request_id
    }))

# Powertools for AWS Lambda (แนะนำ)
from aws_lambda_powertools import Logger, Tracer, Metrics
from aws_lambda_powertools.metrics import MetricUnit

logger = Logger(service="my-service")
tracer = Tracer(service="my-service")
metrics = Metrics(namespace="MyApp", service="my-service")

@logger.inject_lambda_context
@tracer.capture_lambda_handler
@metrics.log_metrics
def handler(event, context):
    metrics.add_metric(name="OrderCreated", unit=MetricUnit.Count, value=1)
    logger.info("Order created", extra={"order_id": "12345"})
    return {"statusCode": 200}

เมื่อไหร่ควรใช้ / ไม่ควรใช้ Serverless

ควรใช้ Serverless เมื่อ

ไม่ควรใช้ Serverless เมื่อ

สรุป

Serverless และ FaaS เป็นเทคโนโลยีที่เปลี่ยนวิธีการพัฒนาและ Deploy ซอฟต์แวร์อย่างมาก ในปี 2026 Serverless ไม่ใช่แค่เทรนด์อีกต่อไป แต่เป็นทางเลือกหลักสำหรับหลาย Use Case สิ่งสำคัญคือต้องเข้าใจว่า Serverless ไม่ใช่คำตอบสำหรับทุกปัญหา ต้องเลือกใช้ให้เหมาะกับ Workload ของคุณ

เริ่มต้นวันนี้ด้วยการลอง AWS Lambda Free Tier ที่ให้ 1 ล้าน Requests ฟรีต่อเดือน สร้าง API ง่ายๆ แล้วค่อยๆ เรียนรู้ Event-driven Architecture, Patterns ต่างๆ และ Best Practices ที่กล่าวถึงในบทความนี้ เมื่อเข้าใจ Serverless อย่างลึกซึ้งแล้ว คุณจะสามารถเลือกเครื่องมือที่เหมาะสมสำหรับแต่ละงาน และสร้าง Application ที่ Scale ได้ดี ค่าใช้จ่ายต่ำ และดูแลรักษาง่าย


Back to Blog | iCafe Forex | SiamLanCard | Siam2R