</>Học Dev
Bài học

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

Tuần 5 – Ngày 3

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

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

LAMBDAFUNCTIONEXECUTIONENVIRONMENTRuntimeFunctionCode(Python,+DependenciesNode.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

EVENTSOURCEMAPPINGPollSQSLambdaServiceQueueBatchInvokesyour(1-10k)functionwithbatchofrecordsLambdaFunctionBatchSettings:-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):DownloadInitializeInitializeExecuteCodeRuntimeHandlerHandler(50-100ms)(100-300ms)(varies)(varies)Total:500ms-2sWARMSTART(Subsequentinvocations):ExecuteHandlerOnly(varies)Total:Executiontimeonly

Provisioned Concurrency

PROVISIONEDCONCURRENCYPre-initializedexecutionenvironments:WarmWarmWarmWarmEnvEnvEnvEnvBenefits:-Nocoldstart-PredictablelatencyCost:-Payforprovisionedcapacity+invocations

Memory & CPU Optimization

Memory=CPUTestresults(example):MemoryDurationCost/InvocationBestValue128MB10.0s$0.0000208256MB5.5s$0.0000229512MB3.0s$0.00002501024MB1.5s$0.0000250Optimal2048MB1.2s$0.0000400Tool:AWSLambdaPowerTuning

4. Lambda@Edge & CloudFront Functions

Comparison

EDGECOMPUTINGOPTIONSCLOUDFRONTFUNCTIONS:-Sub-millisecondstartup-JavaScriptonly-Max10KBcode-Viewerrequest/responseonly-Use:URLrewrites,headermanipulationLAMBDA@EDGE:-Regionaldeploymenttoedges-Node.js,Python-Max50MB(viewer)/10MBcompressed-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.9

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 đásp á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), max 10 MB deployment package, 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.


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


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