DEV Community

Cover image for วิธีใช้ AWS Lambda API สำหรับ Serverless ปี 2026
Thanawat Wongchai
Thanawat Wongchai

Posted on • Originally published at apidog.com

วิธีใช้ AWS Lambda API สำหรับ Serverless ปี 2026

TL;DR

AWS Lambda API ช่วยให้นักพัฒนาสามารถปรับใช้ จัดการ และเรียกใช้ฟังก์ชันไร้เซิร์ฟเวอร์ได้แบบโปรแกรม ใช้ IAM รับรองความถูกต้อง, RESTful endpoint สำหรับจัดการฟังก์ชัน, รองรับการเรียกใช้ซิงค์และอะซิงค์ มีระบบจัดการ Concurrency ระดับบัญชี คู่มือนี้จะลงรายละเอียดการตั้งค่าการรับรองความถูกต้อง, การปรับใช้ฟังก์ชัน, รูปแบบการเรียกใช้, การเชื่อม Event Source และกลยุทธ์สถาปัตยกรรมไร้เซิร์ฟเวอร์สำหรับงาน production

ทดลองใช้ Apidog วันนี้

บทนำ

AWS Lambda ประมวลผลคำขอได้นับล้านล้านครั้งต่อเดือน รองรับผู้ใช้มากกว่า 1 ล้านราย นักพัฒนาที่ต้องสร้างแอปไร้เซิร์ฟเวอร์ ระบบอัตโนมัติ หรือ event-driven architecture จำเป็นต้องผสาน Lambda API เข้ากับโครงสร้างพื้นฐานแบบ Infrastructure as Code และ pipeline CI/CD

ทีมที่ดูแล Lambda หลายสิบฟังก์ชันด้วยมือจะเสียเวลาไปกับการ deploy, อัปเดต config และตรวจสอบกว่า 10-15 ชั่วโมง/สัปดาห์ การอินทิเกรท Lambda API อย่างถูกวิธีช่วยลดเวลา deploy, รองรับ blue-green deployment, และ autoscaling บนความต้องการจริง

คู่มือนี้จะพาคุณลงมือผสาน AWS Lambda API ตั้งแต่ IAM authentication, สร้าง/ปรับใช้ฟังก์ชัน, invoke แบบ sync/async, เชื่อม event source, layer architecture และแนวทาง deployment production-grade

AWS Lambda API คืออะไร?

AWS Lambda มี RESTful API สำหรับจัดการฟังก์ชัน serverless ครอบคลุมฟีเจอร์หลัก:

  • สร้าง อัปเดต ลบฟังก์ชัน
  • Deploy โค้ดและเวอร์ชัน
  • Invoke ฟังก์ชัน (sync/async)
  • เชื่อม Event Source (SQS, Kinesis, DynamoDB, S3 ฯลฯ)
  • จัดการ Layer, Alias, Routing
  • กำหนด Concurrency และ Reserved Capacity
  • บันทึก/มอนิเตอร์

คุณสมบัติหลัก

คุณสมบัติ คำอธิบาย
RESTful API HTTPS endpoint มาตรฐาน
IAM Authentication AWS Signature Version 4
Async Invocation Fire-and-forget event processing
Sync Invocation Request-response invocation
Event Sources Integrate >200 AWS services
Layers Shared code/components
Version/Alias Traffic routing & rollback
Provisioned Concurrency ลด cold start latency

การรองรับ Runtime ของ Lambda

Runtime เวอร์ชัน กรณีใช้งาน
Node.js 18.x, 20.x Backend API, Event processing
Python 3.9, 3.10, 3.11 Data processing, ML
Java 11, 17, 21 Enterprise apps
Go 1.x High-perf API
Rust 1.x Low-latency
.NET 6, 8 Windows workload
Ruby 3.x Web apps
Custom Any Container-based runtimes

ภาพรวมสถาปัตยกรรม API

Lambda ใช้ endpoint:

https://lambda.{region}.amazonaws.com/2015-03-31/
Enter fullscreen mode Exit fullscreen mode

เวอร์ชัน API

เวอร์ชัน สถานะ กรณีใช้งาน
2015-03-31 ปัจจุบัน ฟีเจอร์ Lambda ครบถ้วน
2018-01-31 Runtime สำหรับ custom runtime interface

เริ่มต้นใช้งาน: การตั้งค่าการรับรองความถูกต้อง

ขั้นตอนที่ 1: สร้างบัญชี AWS และผู้ใช้ IAM

  1. เข้า AWS Console
  2. สมัครบัญชี AWS
  3. ไปที่ IAM Console > ผู้ใช้ > สร้างผู้ใช้
  4. แนบนโยบาย Lambda execution

ขั้นตอนที่ 2: สร้างข้อมูลประจำตัว IAM

สร้าง Access Key สำหรับใช้งาน API:

# AWS CLI method
aws iam create-access-key --user-name lambda-deployer

# Output: Store these securely
{
  "AccessKey": {
    "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
  }
}
Enter fullscreen mode Exit fullscreen mode

ความปลอดภัย: จัดเก็บ credentials ในไฟล์หรือ environment variable:

# ~/.aws/credentials
[lambda-deployer]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

# หรือใช้ env variables
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_DEFAULT_REGION="us-east-1"
Enter fullscreen mode Exit fullscreen mode

ขั้นตอนที่ 3: ทำความเข้าใจ AWS Signature Version 4

Lambda API ทุกคำขอต้อง sign ด้วย SigV4 ตัวอย่างการ sign (Node.js):

const crypto = require('crypto');

class AWSSigner {
  constructor(accessKeyId, secretAccessKey, region, service = 'lambda') {
    this.accessKeyId = accessKeyId;
    this.secretAccessKey = secretAccessKey;
    this.region = region;
    this.service = service;
  }

  sign(request, body = null) {
    const now = new Date();
    const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
    const dateStamp = amzDate.slice(0, 8);

    // 1. canonical request
    const hashedPayload = body ? crypto.createHash('sha256').update(body).digest('hex') : 'UNSIGNED-PAYLOAD';
    const canonicalUri = request.path;
    const canonicalQuerystring = request.query || '';
    const canonicalHeaders = `host:${request.host}\nx-amz-date:${amzDate}\n`;
    const signedHeaders = 'host;x-amz-date';
    const canonicalRequest = `${request.method}\n${canonicalUri}\n${canonicalQuerystring}\n${canonicalHeaders}\n${signedHeaders}\n${hashedPayload}`;

    // 2. string to sign
    const algorithm = 'AWS4-HMAC-SHA256';
    const credentialScope = `${dateStamp}/${this.region}/${this.service}/aws4_request`;
    const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex');
    const stringToSign = `${algorithm}\n${amzDate}\n${credentialScope}\n${hash}`;

    // 3. calculate signature
    const kDate = this.hmac(`AWS4${this.secretAccessKey}`, dateStamp);
    const kRegion = this.hmac(kDate, this.region);
    const kService = this.hmac(kRegion, this.service);
    const kSigning = this.hmac(kService, 'aws4_request');
    const signature = this.hmac(kSigning, stringToSign, 'hex');

    // 4. auth header
    const authorizationHeader = `${algorithm} Credential=${this.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;

    return {
      'Authorization': authorizationHeader,
      'X-Amz-Date': amzDate,
      'X-Amz-Content-Sha256': hashedPayload
    };
  }

  hmac(key, string, encoding = 'buffer') {
    return crypto.createHmac('sha256', key).update(string).digest(encoding);
  }
}

// Usage
const signer = new AWSSigner(
  process.env.AWS_ACCESS_KEY_ID,
  process.env.AWS_SECRET_ACCESS_KEY,
  'us-east-1'
);
Enter fullscreen mode Exit fullscreen mode

ขั้นตอนที่ 4: สร้าง Lambda API Client

const LAMBDA_BASE_URL = 'https://lambda.us-east-1.amazonaws.com/2015-03-31';

const lambdaRequest = async (path, options = {}) => {
  const url = new URL(`${LAMBDA_BASE_URL}${path}`);
  const method = options.method || 'GET';
  const body = options.body ? JSON.stringify(options.body) : null;

  const signer = new AWSSigner(
    process.env.AWS_ACCESS_KEY_ID,
    process.env.AWS_SECRET_ACCESS_KEY,
    'us-east-1'
  );

  const headers = signer.sign({ method, host: 'lambda.us-east-1.amazonaws.com', path }, body);

  const response = await fetch(url.toString(), {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...headers,
      ...options.headers
    },
    body
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Lambda API Error: ${error.Message}`);
  }

  return response.json();
};

// เรียกใช้งาน
const functions = await lambdaRequest('/functions');
console.log(`Found ${functions.Functions.length} functions`);
Enter fullscreen mode Exit fullscreen mode

ทางเลือก: ใช้ AWS SDK

ใช้ AWS SDK จะจัดการ signing อัตโนมัติ

const { LambdaClient, ListFunctionsCommand, CreateFunctionCommand, InvokeCommand } = require('@aws-sdk/client-lambda');

const lambda = new LambdaClient({ region: 'us-east-1' });

// List functions
const listCommand = new ListFunctionsCommand({});
const result = await lambda.send(listCommand);

// Create function
const createCommand = new CreateFunctionCommand({
  FunctionName: 'my-function',
  Runtime: 'nodejs20.x',
  Role: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  Handler: 'index.handler',
  Code: {
    S3Bucket: 'my-bucket',
    S3Key: 'function.zip'
  }
});

const fn = await lambda.send(createCommand);
Enter fullscreen mode Exit fullscreen mode

การจัดการฟังก์ชัน

การสร้างฟังก์ชัน

const createFunction = async (functionConfig) => {
  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionConfig.name,
      Runtime: functionConfig.runtime || 'nodejs20.x',
      Role: functionConfig.roleArn,
      Handler: functionConfig.handler || 'index.handler',
      Code: {
        S3Bucket: functionConfig.s3Bucket,
        S3Key: functionConfig.s3Key
      },
      Description: functionConfig.description || '',
      Timeout: functionConfig.timeout || 3,
      MemorySize: functionConfig.memorySize || 128,
      Environment: {
        Variables: functionConfig.environment || {}
      },
      Tags: functionConfig.tags || {}
    }
  });

  return response;
};

// ตัวอย่างใช้งาน
const fn = await createFunction({
  name: 'order-processor',
  roleArn: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  handler: 'index.handler',
  runtime: 'nodejs20.x',
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'order-processor/v1.0.0.zip',
  description: 'Process orders from SQS queue',
  timeout: 30,
  memorySize: 512,
  environment: {
    DB_HOST: 'db.example.com',
    LOG_LEVEL: 'info'
  }
});

console.log(`Function created: ${fn.FunctionArn}`);
Enter fullscreen mode Exit fullscreen mode

การอัปโหลดโค้ดโดยตรง (zip < 50MB)

const fs = require('fs');

const createFunctionWithZip = async (functionName, zipPath) => {
  const zipBuffer = fs.readFileSync(zipPath);
  const base64Code = zipBuffer.toString('base64');

  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionName,
      Runtime: 'nodejs20.x',
      Role: 'arn:aws:iam::123456789012:role/lambda-execution-role',
      Handler: 'index.handler',
      Code: {
        ZipFile: base64Code
      }
    }
  });

  return response;
};

// Zip file: zip -r function.zip index.js node_modules/
await createFunctionWithZip('my-function', './function.zip');
Enter fullscreen mode Exit fullscreen mode

การอัปเดตโค้ดฟังก์ชัน

const updateFunctionCode = async (functionName, updateConfig) => {
  const response = await lambdaRequest(`/functions/${functionName}/code`, {
    method: 'PUT',
    body: {
      S3Bucket: updateConfig.s3Bucket,
      S3Key: updateConfig.s3Key,
      Publish: updateConfig.publish || false
    }
  });

  return response;
};

// ตัวอย่าง
const updated = await updateFunctionCode('order-processor', {
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'order-processor/v1.1.0.zip',
  publish: true
});

console.log(`Updated to version: ${updated.Version}`);
Enter fullscreen mode Exit fullscreen mode

การอัปเดตการกำหนดค่าฟังก์ชัน

const updateFunctionConfig = async (functionName, config) => {
  const response = await lambdaRequest(`/functions/${functionName}/configuration`, {
    method: 'PUT',
    body: {
      Runtime: config.runtime,
      Handler: config.handler,
      Description: config.description,
      Timeout: config.timeout,
      MemorySize: config.memorySize,
      Environment: {
        Variables: config.environment
      }
    }
  });

  return response;
};

// ตัวอย่าง
const updated = await updateFunctionConfig('order-processor', {
  timeout: 60,
  memorySize: 1024,
  environment: {
    DB_HOST: 'new-db.example.com',
    LOG_LEVEL: 'debug'
  }
});
Enter fullscreen mode Exit fullscreen mode

การลบฟังก์ชัน

const deleteFunction = async (functionName, qualifier = null) => {
  const path = qualifier
    ? `/functions/${functionName}?Qualifier=${qualifier}`
    : `/functions/${functionName}`;

  await lambdaRequest(path, { method: 'DELETE' });
  console.log(`Function ${functionName} deleted`);
};
Enter fullscreen mode Exit fullscreen mode

การเรียกใช้ฟังก์ชัน

การเรียกใช้แบบซิงโครนัส (Request-Response)

const invokeFunction = async (functionName, payload, qualifier = null) => {
  const path = qualifier
    ? `/functions/${functionName}/invocations?Qualifier=${qualifier}`
    : `/functions/${functionName}/invocations`;

  const response = await lambdaRequest(path, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'RequestResponse',
      'X-Amz-Log-Type': 'Tail'
    },
    body: payload
  });

  const result = JSON.parse(Buffer.from(response.Payload).toString());
  const logs = Buffer.from(response.LogResult, 'base64').toString();

  return { result, logs };
};

// ตัวอย่าง
const { result, logs } = await invokeFunction('order-processor', {
  orderId: 'ORD-12345',
  customerId: 'CUST-67890',
  items: [
    { sku: 'PROD-001', quantity: 2 },
    { sku: 'PROD-002', quantity: 1 }
  ]
});

console.log(`Result: ${JSON.stringify(result)}`);
console.log(`Logs:\n${logs}`);
Enter fullscreen mode Exit fullscreen mode

การเรียกใช้แบบอะซิงโครนัส (Fire-and-Forget)

const invokeAsync = async (functionName, payload) => {
  const response = await lambdaRequest(`/functions/${functionName}/invocations`, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'Event',
      'X-Amz-Log-Type': 'None'
    },
    body: payload
  });

  return {
    statusCode: response.StatusCode,
    executionId: response['X-Amz-Execution-Id']
  };
};

// ตัวอย่าง
const result = await invokeAsync('email-sender', {
  to: 'customer@example.com',
  template: 'order-confirmation',
  data: { orderId: 'ORD-12345' }
});

console.log(`Async invocation ID: ${result.executionId}`);
Enter fullscreen mode Exit fullscreen mode

การเรียกใช้แบบ Dry Run

const dryRunInvocation = async (functionName) => {
  const response = await lambdaRequest(`/functions/${functionName}/invocations`, {
    method: 'POST',
    headers: {
      'X-Amz-Invocation-Type': 'DryRun'
    }
  });

  return response;
};

// ตรวจสอบ permission
try {
  await dryRunInvocation('order-processor');
  console.log('Invocation permissions OK');
} catch (error) {
  console.error('Permission denied:', error.message);
}
Enter fullscreen mode Exit fullscreen mode

ประเภทการตอบกลับการเรียกใช้

ประเภท พฤติกรรม กรณีใช้งาน
RequestResponse sync, รอผลลัพธ์ API, CLI command
Event async, ไม่รอผล Event processing, notification
DryRun test permission ตรวจสอบ, debug

การจัดการเวอร์ชันและ Alias

การเผยแพร่เวอร์ชัน

const publishVersion = async (functionName, description = null) => {
  const response = await lambdaRequest(`/functions/${functionName}/versions`, {
    method: 'POST',
    body: description ? { Description: description } : {}
  });

  return response;
};

// ตัวอย่าง
const version = await publishVersion('order-processor', 'v1.2.0 - Add tax calculation');
console.log(`Published version: ${version.Version}`);
Enter fullscreen mode Exit fullscreen mode

การสร้าง Alias

const createAlias = async (functionName, aliasName, version, description = null) => {
  const response = await lambdaRequest(`/functions/${functionName}/aliases`, {
    method: 'POST',
    body: {
      Name: aliasName,
      FunctionVersion: version,
      Description: description
    }
  });

  return response;
};

// ตัวอย่าง
const prodAlias = await createAlias('order-processor', 'prod', '5', 'Production version');
console.log(`Alias ARN: ${prodAlias.AliasArn}`);
Enter fullscreen mode Exit fullscreen mode

การเปลี่ยนเส้นทางการรับส่งข้อมูลด้วย Routing Config

const updateAliasWithRouting = async (functionName, aliasName, routingConfig) => {
  const response = await lambdaRequest(`/functions/${functionName}/aliases/${aliasName}`, {
    method: 'PUT',
    body: {
      RoutingConfig: {
        AdditionalVersionWeights: routingConfig
      }
    }
  });

  return response;
};

// 10% traffic to version 6, 90% to version 5
await updateAliasWithRouting('order-processor', 'prod', {
  '6': 0.1
});

// หลังทดสอบ, ปรับเป็น 100%
await updateAliasWithRouting('order-processor', 'prod', {});
Enter fullscreen mode Exit fullscreen mode

กรณีการใช้งาน Alias

Alias เวอร์ชัน วัตถุประสงค์
dev $LATEST ทดสอบ dev
staging test ล่าสุด ตรวจสอบ QA
prod stable งาน production traffic
blue prod ปัจจุบัน Blue-green deployment
green เวอร์ชันใหม่ Blue-green deployment

การจับคู่แหล่งที่มาของเหตุการณ์

การสร้าง SQS Trigger

const createSQSEventSource = async (functionName, queueArn, batchSize = 10) => {
  const response = await lambdaRequest('/event-source-mappings', {
    method: 'POST',
    body: {
      EventSourceArn: queueArn,
      FunctionName: functionName,
      BatchSize: batchSize,
      Enabled: true
    }
  });

  return response;
};

// ตัวอย่าง
const mapping = await createSQSEventSource(
  'order-processor',
  'arn:aws:sqs:us-east-1:123456789012:orders-queue',
  10
);

console.log(`Event source created: ${mapping.UUID}`);
Enter fullscreen mode Exit fullscreen mode

การสร้าง DynamoDB Stream Trigger

const createDynamoDBEventSource = async (functionName, streamArn, startingPosition = 'LATEST') => {
  const response = await lambdaRequest('/event-source-mappings', {
    method: 'POST',
    body: {
      EventSourceArn: streamArn,
      FunctionName: functionName,
      StartingPosition: startingPosition,
      BatchSize: 100,
      BisectBatchOnFunctionError: true,
      MaximumRetryAttempts: 3
    }
  });

  return response;
};

// ตัวอย่าง
await createDynamoDBEventSource(
  'user-analytics',
  'arn:aws:dynamodb:us-east-1:123456789012:table/Users/stream/2026-03-25T00:00:00.000'
);
Enter fullscreen mode Exit fullscreen mode

ประเภทแหล่งที่มาของเหตุการณ์

แหล่งที่มา กรณีใช้งาน Batch
SQS Queue message ใช่ (1-10)
Kinesis Real-time stream ใช่ (1-10,000)
DynamoDB DB change stream ใช่ (1-1,000)
S3 Object event ไม่ (1/event)
EventBridge Event routing ใช่
API Gateway HTTP API ไม่
Schedule Cron job ไม่

การจัดการเลเยอร์

การสร้างเลเยอร์

const createLayer = async (layerName, layerConfig) => {
  const response = await lambdaRequest('/layers', {
    method: 'POST',
    body: {
      LayerName: layerName,
      Description: layerConfig.description,
      CompatibleRuntimes: layerConfig.runtimes,
      Content: {
        S3Bucket: layerConfig.s3Bucket,
        S3Key: layerConfig.s3Key
      }
    }
  });

  return response;
};

// ตัวอย่าง
const layer = await createLayer('shared-utils', {
  description: 'Shared utilities and dependencies',
  runtimes: ['nodejs20.x', 'nodejs18.x'],
  s3Bucket: 'my-layers-bucket',
  s3Key: 'shared-utils/v1.zip'
});

console.log(`Layer ARN: ${layer.LayerArn}`);
Enter fullscreen mode Exit fullscreen mode

การใช้เลเยอร์ในฟังก์ชัน

const createFunctionWithLayers = async (functionConfig) => {
  const response = await lambdaRequest('/functions', {
    method: 'POST',
    body: {
      FunctionName: functionConfig.name,
      Runtime: functionConfig.runtime,
      Role: functionConfig.roleArn,
      Handler: functionConfig.handler,
      Code: {
        S3Bucket: functionConfig.s3Bucket,
        S3Key: functionConfig.s3Key
      },
      Layers: functionConfig.layers // Array of layer ARNs
    }
  });

  return response;
};

// ตัวอย่าง
await createFunctionWithLayers({
  name: 'api-handler',
  roleArn: 'arn:aws:iam::123456789012:role/lambda-execution-role',
  handler: 'index.handler',
  runtime: 'nodejs20.x',
  s3Bucket: 'my-deployments-bucket',
  s3Key: 'api-handler/v1.0.0.zip',
  layers: [
    'arn:aws:lambda:us-east-1:123456789012:layer:shared-utils:1',
    'arn:aws:lambda:us-east-1:123456789012:layer:aws-sdk:3'
  ]
});
Enter fullscreen mode Exit fullscreen mode

การทำงานพร้อมกันและการปรับขนาด

การตั้งค่า Reserved Concurrency

const putFunctionConcurrency = async (functionName, reservedConcurrentExecutions) => {
  const response = await lambdaRequest(`/functions/${functionName}/concurrency`, {
    method: 'PUT',
    body: {
      ReservedConcurrentExecutions: reservedConcurrentExecutions
    }
  });

  return response;
};

// ตัวอย่าง - Reserve 100 concurrent executions
await putFunctionConcurrency('order-processor', 100);
Enter fullscreen mode Exit fullscreen mode

ขีดจำกัดการทำงานพร้อมกันของบัญชี

ประเภทบัญชี ขีดจำกัดเริ่มต้น เพิ่มได้
Free Tier 1,000 ใช่
Pay-as-you-go 1,000 ใช่
Enterprise 1,000+ ปรับ custom

รายการตรวจสอบการปรับใช้สำหรับการผลิต

  • [ ] ใช้ AWS SDK สำหรับ SigV4
  • [ ] กำหนดเวอร์ชันด้วย Alias
  • [ ] Reserved Concurrency สำหรับฟังก์ชันสำคัญ
  • [ ] ตั้งค่า DLQ สำหรับ async
  • [ ] เปิด X-Ray tracing
  • [ ] กำหนด VPC สำหรับฐานข้อมูล
  • [ ] Structured Logging (JSON)
  • [ ] CloudWatch Alarms
  • [ ] ใช้ Layer สำหรับ shared component
  • [ ] Blue-green deployment

กรณีการใช้งานในโลกจริง

แบ็คเอนด์ API

SaaS company สร้าง REST API แบบ serverless:

  • ปัญหา: traffic ขึ้นลงเร็ว, scale ไม่คาดเดา
  • โซลูชัน: Lambda + API Gateway autoscale
  • ผลลัพธ์: uptime 99.99%, ลดต้นทุน 60% เทียบ EC2

การใช้งานหลัก:

  • Lambda per resource
  • API Gateway = routing/auth
  • DynamoDB = storage
  • Provisioned Concurrency = latency ต่ำ

ไปป์ไลน์การประมวลผลเหตุการณ์

e-commerce ประมวลผลคำสั่งซื้อ:

  • ปัญหา: peak event traffic (flash sale)
  • โซลูชัน: SQS + Lambda batch
  • ผลลัพธ์: ไม่สูญ order, scale x10

การใช้งานหลัก:

  • SQS buffer order
  • Lambda batch 10 message/ครั้ง
  • DLQ สำหรับ message fail
  • CloudWatch alert queue depth

บทสรุป

AWS Lambda API ให้ฟังก์ชัน serverless แบบครบวงจร จุดสำคัญที่ควรรู้:

  • ใช้ IAM + SigV4 (AWS SDK ช่วยอัตโนมัติ)
  • รูปแบบการเรียกใช้ sync/async
  • Version/Alias สำหรับ deployment
  • Event source mapping สำหรับสถาปัตยกรรม serverless
  • Layer สำหรับโค้ด/ไลบรารี shared
  • Apidog ช่วยปรับปรุงการทดสอบ API และ teamwork

ส่วนคำถามที่พบบ่อย

ฉันจะรับรองความถูกต้องกับ Lambda API ได้อย่างไร?

ใช้ AWS IAM credential และ Signature Version 4 (แนะนำให้ใช้ AWS SDK เพื่อ sign อัตโนมัติ)

การเรียกใช้แบบซิงโครนัสและอะซิงโครนัสแตกต่างกันอย่างไร?

ซิงโครนัส (RequestResponse) รอผลลัพธ์, อะซิงโครนัส (Event) จัดคิวแล้ว return ทันที

เวอร์ชันของ Lambda ทำงานอย่างไร?

แต่ละเวอร์ชันที่ถูก publish คือ snapshot ที่เปลี่ยนไม่ได้ ใช้ Alias ชี้ไปเวอร์ชันนั้นและควบคุม traffic routing

Lambda Layers คืออะไร?

เลเยอร์คือการแยกโค้ด/ไลบรารีที่ใช้ร่วมกันออกจากฟังก์ชัน ให้หลายฟังก์ชันใช้ร่วมกันได้

ฉันจะลด Cold Start ได้อย่างไร?

ใช้ Provisioned Concurrency, ทำแพ็กเกจให้เล็ก, เลือกภาษาแบบ compiled (Go, Rust) สำหรับ latency ต่ำ

Reserved Concurrency คืออะไร?

Reserved Concurrency คือการจองจำนวน concurrent execution ให้ฟังก์ชัน ป้องกัน resource contention

ฉันสามารถทริกเกอร์ Lambda จาก S3 ได้หรือไม่?

ได้ ตั้งค่า S3 event notification ให้เรียก Lambda เมื่อมี object สร้าง/ลบ

Top comments (0)