devHọc Dev
Bài học

Tuần 5 - Ngày 3: Lambda & Serverless

Tuần 5 – Ngày 3

Mục tiêu học tập

  • Hiểu Lambda architecture và limits
  • Nắm vững event-driven patterns
  • Biết cách optimize Lambda performance

1. Lambda Architecture

┌─────────────────────────────────────────────────────────┐│LAMBDAFUNCTION││││┌─────────────────────────────────────────────────┐│││EXECUTIONENVIRONMENT││││││││┌─────────────┐┌────────────────────────┐│││││Runtime││FunctionCode││││││(Python,││+Dependencies││││││Node.js)││(LambdaLayer)│││││└─────────────┘└────────────────────────┘││││││││/tmp(512MB-10GBephemeralstorage)│││└─────────────────────────────────────────────────┘││││Configuration:││-Memory:128MB-10,240MB││-Timeout:upto15minutes││-Concurrency:1000default(canincrease)│└─────────────────────────────────────────────────────────┘

2. Lambda Invocation

Invocation Types

1. SYNCHRONOUS (RequestResponse)
   - Wait for function to complete
   - Get result immediately
   - Examples: API Gateway, ALB

2. ASYNCHRONOUS (Event)
   - Fire and forget
   - Automatic retry (2 times)
   - Examples: S3, SNS, EventBridge

3. POLL-BASED (Event Source Mapping)
   - Lambda polls source
   - Batch processing
   - Examples: SQS, Kinesis, DynamoDB Streams

Event Source Mapping

┌─────────────────────────────────────────────────────────┐│EVENTSOURCEMAPPING││││┌─────────────┐Poll┌─────────────────┐│││SQS│◄────────────│LambdaService││││Queue│││││└─────────────┘Batch│Invokesyour│││(1-10k)│functionwith│││││batchof│││▼│records│││┌──────────────┴──────────────┐│││LambdaFunction│││└─────────────────────────────┘││││BatchSettings:││-BatchSize:1-10,000(SQS),1-10,000(Kinesis)││-BatchWindow:0-300seconds││-Parallelization:Pershard(Kinesis/DynamoDB)│└─────────────────────────────────────────────────────────┘

3. Lambda Performance

Cold Start vs Warm Start

COLDSTART(Firstinvocation):┌────────────────────────────────────────────────────────┐│Download│Initialize│Initialize│Execute││Code│Runtime│Handler│Handler││(50-100ms)│(100-300ms)│(varies)│(varies)│└────────────────────────────────────────────────────────┘Total:500ms-2sWARMSTART(Subsequentinvocations):┌─────────────────────────────────────────────────┐│ExecuteHandlerOnly││(varies)│└─────────────────────────────────────────────────┘Total:Executiontimeonly

Provisioned Concurrency

┌─────────────────────────────────────────────────────────┐│PROVISIONEDCONCURRENCY││││Pre-initializedexecutionenvironments:││││┌────────┐┌────────┐┌────────┐┌────────┐│││Warm││Warm││Warm││Warm││││Env││Env││Env││Env│││└────────┘└────────┘└────────┘└────────┘││││Benefits:││-Nocoldstart││-Predictablelatency││││Cost:││-Payforprovisionedcapacity+invocations│└─────────────────────────────────────────────────────────┘

Memory & CPU Optimization

Memory↑=CPU↑Testresults(example):┌─────────────────────────────────────────────────────────┐│Memory│Duration│Cost/Invocation│BestValue│├──────────┼──────────┼─────────────────┼────────────────┤│128MB│10.0s│$0.0000208│││256MB│5.5s│$0.0000229│││512MB│3.0s│$0.0000250│││1024MB│1.5s│$0.0000250│←Optimal││2048MB│1.2s│$0.0000400││└─────────────────────────────────────────────────────────┘Tool:AWSLambdaPowerTuning

4. Lambda@Edge & CloudFront Functions

Comparison

┌─────────────────────────────────────────────────────────┐│EDGECOMPUTINGOPTIONS││││CLOUDFRONTFUNCTIONS:││-Sub-millisecondstartup││-JavaScriptonly││-Max10KBcode││-Viewerrequest/responseonly││-Use:URLrewrites,headermanipulation││││LAMBDA@EDGE:││-Regionaldeploymenttoedges││-Node.js,Python││-Package:1MB(viewer)/50MB(origintriggers)││-Alltriggers(viewer+origin)││-Use:Complexlogic,externalcalls│└─────────────────────────────────────────────────────────┘

5. Serverless Application Model (SAM)

SAM Template

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Runtime: python3.12

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      CodeUri: ./src
      Events:
        Api:
          Type: Api
          Properties:
            Path: /items
            Method: GET
      Policies:
        - DynamoDBReadPolicy:
            TableName: !Ref MyTable

6. Câu hỏi ôn tập

  1. 3 loại Lambda invocation là gì?

    Xem đáp án

    (1) Synchronous (RequestResponse) — caller đợi response, xử lý lỗi phía caller (API GW, ALB, Cognito). (2) Asynchronous (Event) — Lambda queue event, retry 2 lần nếu fail, DLQ cho unprocessed events (S3, SNS, EventBridge). (3) Event Source Mapping — Lambda poll source service (SQS, DynamoDB Streams, Kinesis, Kafka), batch processing. Error handling khác nhau per invocation type — quan trọng cho architect design.

  2. Cold start xảy ra khi nào?

    Xem đáp án

    Cold start xảy ra khi không có warm execution environment sẵn sàng: (1) First invocation sau deploy, (2) Scale-out khi cần thêm concurrent executions, (3) Sau period of inactivity (environment bị reclaim). Cold start = download code + init runtime + run init code (import statements, DB connections, SDK clients) = 100ms đến vài giây. Giảm cold start: Provisioned Concurrency, tối ưu init code, dùng SnapStart (Java), lazy-load resources.

  3. Provisioned Concurrency giải quyết vấn đề gì?

    Xem đáp án

    Giải quyết cold start latency bằng cách giữ sẵn N execution environments warm và initialized — function respond ngay lập tức không có cold start delay. Phù hợp cho: latency-sensitive APIs (P99 requirements), functions với heavy init (ML models, connection pools), traffic spikes predictable (8 AM business hours). Chi phí: tính phí theo số provisioned concurrency × thời gian — kể cả khi idle. Trade-off: cost vs latency.

  4. Lambda@Edge khác CloudFront Functions như thế nào?

    Xem đáp án

    Lambda@Edge: runs Node.js/Python, max 5-30 giây execution, có thể gọi network (DynamoDB, Secrets Manager), deployment package max 1 MB cho viewer triggers / 50 MB cho origin triggers, 4 event triggers (viewer/origin request/response). CloudFront Functions: JavaScript only, max 1 ms, NO network calls, 10 KB code limit, chỉ 2 triggers (viewer request/response). CloudFront Functions ~6× rẻ hơn, cho lightweight operations (header manipulation, URL rewrite, simple redirects). Lambda@Edge cho complex logic cần external data.

  5. Event Source Mapping hoạt động như thế nào?

    Xem đáp án

    Event Source Mapping cho phép Lambda poll từ event sources: SQS, DynamoDB Streams, Kinesis Data Streams, Apache Kafka (MSK), self-managed Kafka. Lambda service (không phải function code) poll source và batch records → invoke Lambda function với batch. Config: BatchSize (1-10,000 records), BisectOnFunctionError (split batch khi fail), DestinationConfig (DLQ/DLS for failed records), Filter patterns. SQS: Lambda delete messages sau khi process thành công; Kinesis/DDB Streams: checkpointing tự động.

7. Bài tập thực hành

  1. Lambda Power Tuning: deploy AWS Lambda Power Tuning (Step Functions state machine), chạy tuning cho một function CPU-bound với các mức memory 128MB–2048MB. Xác định điểm optimal cost/duration và đối chiếu với bảng ví dụ trong bài.

  2. Event Source Mapping với SQS: tạo SQS queue + DLQ, cấu hình event source mapping BatchSize 10, maxReceiveCount 3. Gửi message lỗi có chủ đích, quan sát retry và message rơi vào DLQ; giải thích vì sao visibility timeout nên ≥ 6× function timeout.

  3. Provisioned Concurrency + alias: publish version, tạo alias live, bật Provisioned Concurrency = 2 trên alias. Dùng script gọi đồng thời 10 request, so sánh P99 latency trước/sau (cold start biến mất trên 2 environment warm).

  4. SAM deploy: dùng template SAM ở mục 5 (sam build && sam deploy --guided) tạo API GET /items đọc DynamoDB; sau đó sam delete để dọn tài nguyên.


Tài liệu tham khảo chính thức


Ngày tiếp theo: S3 Advanced & Storage