1.2.6 Lambda Performance Tuning
Cold Start vs Warm Start
Cold Start: Download code → Init runtime → Init dependencies → Handler
Warm Start: Handler (container reused)
- Cold start xảy ra khi không có container sẵn
- Init phase: tối đa 10s (có thể lên 15s cho VPC)
- Warm container được reuse cho invocations tiếp theo
Cold Start Mitigation
| Strategy | Mô tả | Trade-off |
|---|
| Provisioned Concurrency | Pre-warm containers | Cost cao hơn |
| Giữ package nhỏ | Giảm download + init time | Cần tối ưu dependencies |
| Init code ngoài handler | Chỉ chạy 1 lần per container | — |
| Avoid VPC (nếu không cần) | VPC cold start chậm hơn | — |
| SnapStart (Java) | Snapshot init state | Chỉ cho Java |
Best Practices — Code Optimization
# GOOD: SDK client ngoài handler (reuse across invocations)
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Orders')
def handler(event, context):
return table.get_item(Key={'id': event['id']})
# BAD: Tạo client mỗi lần invoke
def handler(event, context):
dynamodb = boto3.resource('dynamodb') # Tạo mới mỗi lần!
table = dynamodb.Table('Orders')
return table.get_item(Key={'id': event['id']})
Concurrency Types
| Type | Mô tả | Use Case |
|---|
| Unreserved | Shared pool (account-level 1000 default) | Default cho mọi functions |
| Reserved | Guaranteed + capped cho function | Protect critical functions, throttle others |
| Provisioned | Pre-initialized containers | Eliminate cold starts |
Memory & CPU
- Memory: 128MB → 10,240MB
- CPU scales linearly với memory
- 1,769MB = 1 vCPU
- Dùng Lambda Power Tuning tool để tìm optimal setting
/tmp Storage
- 512MB → 10,240MB
- Persist giữa các invocations (warm container)
- Dùng cho temporary files, cache
Exam Tip: Lambda Power Tuning giúp tìm optimal memory. Init code ngoài handler = reuse connections. Provisioned Concurrency = no cold starts nhưng tốn tiền. Reserved Concurrency = giới hạn + đảm bảo concurrency.