AWS Lambda
Function-as-a-service — you give AWS code + a trigger, it gives you compute per invocation. Exam themes: hard limits, sync vs async retry semantics, VPC connectivity, and CodeDeploy shifts.
Function-as-a-service — bạn đưa code + trigger, AWS chạy hộ theo từng invocation. Chủ đề exam: hard limit, retry semantics sync vs async, kết nối VPC, và CodeDeploy shift.
✓ When to reach for it✓ Khi nào dùng
- Event-driven glue (S3 → resize, SQS → process)Keo dán event-driven (S3 → resize, SQS → xử lý)
- Spiky traffic, no idle cost toleranceTraffic bùng nổ, không muốn tốn idle
- API Gateway backends where latency budget allows cold startsBackend cho API GW nếu latency budget chấp nhận cold start
- Chatty jobs < 15 minJob vụn dưới 15 phút
✗ When to avoid✗ Khi nào tránh
- Long-running batch — use ECS/Fargate or BatchBatch dài — dùng ECS/Fargate hoặc Batch
- Arbitrary Docker workloads — ECS/Fargate preferredDocker tuỳ ý — ưu tiên ECS/Fargate
- Large payloads (>6 MB sync) — S3 pre-signed URLsPayload lớn (>6 MB sync) — dùng pre-signed S3 URL
- Predictable steady load — EC2 Reserved is cheaperLoad ổn định — EC2 Reserved rẻ hơn
Sync vs async invocationSync vs async invocation
Retry lives with the caller (sync) or with Lambda (async, 3 attempts → DLQ). Retry thuộc caller (sync) hay Lambda (async, 3 attempt → DLQ).
| Synchronous | Asynchronous | |
|---|---|---|
| CallersAi gọi | CLI · SDK · API Gateway · ALB | S3 · SNS · EventBridge |
| RetriesRetry | Client's job (backoff)Client tự lo (backoff) | Lambda retries 2× (3 attempts) → DLQLambda retry 2× (3 attempt) → DLQ |
| Payload capGiới hạn payload | 6 MB (200 MB streamed)(200 MB nếu stream) | 1 MB |
| IdempotencyIdempotent | Nice-to-haveNên có | Required — retries will happenBắt buộc — chắc chắn có retry |
OnFailure / OnSuccess): more targets (SQS · SNS · Lambda · EventBridge) and the record carries the error context a DLQ drops.
Lỗi async có thể đẩy vào SQS (worker pull xử lý lại) hoặc SNS (fan-out để alert + lưu). Nên ưu tiên Lambda Destinations (OnFailure / OnSuccess): nhiều target hơn (SQS · SNS · Lambda · EventBridge) và record kèm error context mà DLQ không có.
Concurrency & throttlingConcurrency & throttling
1000 concurrent per account (soft). Anything over = Throttle. Use reserved concurrency to firewall one function from starving others. 1000 concurrent/account (soft). Vượt = Throttle. Dùng reserved concurrency để rào 1 function không hút hết slot của cái khác.
- Bump the account cap via AWS Service Quotas — new accounts start below 1000 and get raised with usage. Nâng cap account qua AWS Service Quotas — account mới bắt đầu dưới 1000, tự tăng theo mức dùng.
- Scale-up rate: +1,000 concurrency / 10 s per function (2023 model — the old region-wide 500–3000 burst quota is gone). Tốc độ scale: +1.000 concurrency / 10 s mỗi function (model 2023 — quota burst 500–3000 theo region đã bỏ).
- Set reserved concurrency on the noisy function so a runaway API GW spike can't starve the ALB-fronted one. It's also a max cap — set 0 to switch a function off. Đặt reserved concurrency lên function ồn ào để API GW spike không nuốt slot của ALB-fronted. Nó cũng là cap tối đa — đặt 0 để tắt hẳn function.
- Provisioned concurrency pre-warms sandboxes to kill cold starts (extra cost). SnapStart (Java · Python 3.12+ · .NET 8) restores from a snapshot instead — free for Java, billed for Python/.NET. Provisioned concurrency giữ sẵn sandbox để triệt cold start (tốn thêm phí). SnapStart (Java · Python 3.12+ · .NET 8) khôi phục từ snapshot — miễn phí với Java, tính phí với Python/.NET.
Lambda in a VPCLambda trong VPC
Default = internet + public AWS APIs, no private RDS. In-VPC = private stuff yes, internet gone until NAT. Mặc định = internet + public AWS API, không truy cập RDS private. Vào VPC = truy cập private OK, mất internet cho tới khi có NAT.
| Outside VPC (default)Ngoài VPC (mặc định) | Inside VPCTrong VPC | |
|---|---|---|
| InternetInternet | ✅ | ❌ (need NAT GW)(cần NAT GW) |
| Public AWS API (S3, DDB)API AWS public (S3, DDB) | ✅ | ❌ (need VPC endpoint)(cần VPC endpoint) |
| Private RDS in subnetRDS private trong subnet | ❌ | ✅ |
Deployments — CodeDeploy shiftsDeploy — CodeDeploy shift
Traffic shift is on the alias. Choose the pattern: All-at-once · Linear · Canary. Shift traffic gắn vào alias. Chọn pattern: All-at-once · Linear · Canary.
Logging & tracingLog & tracing
-
CloudWatch Logs — the execution role must allow
logs:CreateLogGroup,logs:CreateLogStream,logs:PutLogEvents. No permission = no logs. CloudWatch Logs — execution role phải cho phéplogs:CreateLogGroup,logs:CreateLogStream,logs:PutLogEvents. Thiếu quyền = mất log. - CloudWatch Metrics — invocations, errors, throttles, duration. CloudWatch Metrics — invocation, error, throttle, duration.
-
X-Ray — flip on tracing in Lambda config, use the AWS SDK, ensure the execution role has
AWSXrayWriteOnlyAccess. X-Ray — bật tracing trong Lambda config, dùng AWS SDK, cấpAWSXrayWriteOnlyAccesscho execution role.
Execution environments — the reuse contractExecution environment — hợp đồng tái sử dụng
An invocation runs inside an execution environment: a container with your code, your /tmp, and your module-level globals. Everything outside the handler runs once per environment, during init; the handler runs once per request. A warm environment may be reused — never assume it will be.
Mỗi invocation chạy trong một execution environment: một container chứa code của bạn, /tmp của bạn, và các biến global ở mức module. Mọi thứ ngoài handler chạy một lần cho mỗi environment, trong pha init; handler chạy một lần cho mỗi request. Environment còn ấm có thể được dùng lại — đừng bao giờ coi là chắc chắn.
Moving the connection out of the handler removes repeat connects on the same environment. It does nothing about parallel environments. The two fixes are complementary, which is why "choose two" questions want both.
Đưa connection ra khỏi handler chỉ bỏ được việc kết nối lặp lại trên cùng một environment. Nó không xử lý các environment chạy song song. Hai cách sửa bổ trợ nhau, nên câu "chọn hai" muốn cả hai.
// ✗ mỗi invocation mở một connection mới
export const handler = async (event) => {
const conn = await connect(); // TCP + TLS + auth mỗi lần
return conn.query("SELECT ...");
};
// ✓ init một lần, tái dùng khi environment còn ấm — kèm kiểm tra stale
let conn = null;
async function getConn() {
if (!conn || !conn.isAlive()) conn = await connect();
return conn; // Lambda có thể bị freeze → DB đóng connection
}
export const handler = async (event) => (await getConn()).query("SELECT ...");
- An environment is reused when it is still alive and idle and a new request arrives. AWS gives no guaranteed lifetime — the "15 minutes" you've read somewhere is folklore.Environment được tái dùng khi nó còn sống và đang rảnh và có request mới tới. AWS không cam kết tuổi thọ — con số "15 phút" bạn từng đọc ở đâu đó là truyền miệng.
- New environments appear on: concurrent requests, scale-out, idle recycling, a code/config deploy, a timeout, an out-of-memory kill, a runtime crash, or AWS maintenance.Environment mới xuất hiện khi: request đồng thời, scale out, bị thu hồi do rảnh, deploy code/config, timeout, hết memory, runtime crash, hoặc AWS bảo trì.
- A frozen environment can have its database connection dropped underneath it. Always re-check and reconnect — a "reused connection" is an optimisation, not a guarantee.Environment bị freeze có thể bị database cắt connection lúc nào không hay. Luôn kiểm tra lại và kết nối lại — "connection tái dùng" là tối ưu hoá, không phải bảo đảm.
- Provisioned concurrency pre-initialises environments, so it removes cold start — it does not reduce connection count. If anything it keeps more environments (and more connections) alive.Provisioned concurrency khởi tạo sẵn environment nên bỏ được cold start — nó không giảm số connection. Nếu có thì nó còn giữ nhiều environment (và nhiều connection) sống hơn.
/tmpand module globals persist across reuse — good for caching config, dangerous for per-request state. Never leak one caller's data into the next invocation./tmpvà biến global ở mức module tồn tại qua các lần tái dùng — tốt để cache config, nguy hiểm với state theo request. Đừng để dữ liệu của caller này rò sang invocation sau.
Function URLsFunction URL
A dedicated HTTPS endpoint on the function itself — https://<id>.lambda-url.<region>.on.aws. No API Gateway, no ALB, no stage, no deployment. When a question wants "expose this Lambda over HTTPS with the least operational overhead" and nothing else, this beats API Gateway.
Một endpoint HTTPS riêng gắn thẳng vào function — https://<id>.lambda-url.<region>.on.aws. Không API Gateway, không ALB, không stage, không deployment. Khi đề muốn "expose Lambda này qua HTTPS với ít operational overhead nhất" và không gì khác, cái này thắng API Gateway.
| Function URLFunction URL | API Gateway | |
|---|---|---|
| Auth optionsTuỳ chọn auth | AWS_IAM orhoặc NONE — that's all— chỉ vậy | IAM · Cognito · JWT · Lambda authorizerLambda authorizer |
| Custom domainDomain riêng | ✗ (put CloudFront in front)✗ (đặt CloudFront phía trước) | ✓ |
| Throttling · usage plans · WAF · cacheThrottling · usage plan · WAF · cache | ✗ | ✓ |
| Routing several paths to several functionsRoute nhiều path tới nhiều function | ✗ — one URL per function✗ — mỗi function một URL | ✓ |
| CostChi phí | just the Lambdachỉ tiền Lambda | Lambda + per-request API feeLambda + phí API theo request |
AuthType: NONE and the function verifies the provider's own HMAC signature (X-Hub-Signature-256) itself. Replacing an EC2 + ASG + ALB webhook receiver with one Function URL per hook is the lowest-overhead answer — API Gateway in front adds routes, stages and per-request cost for nothing.
Git server gọi webhook không ký được SigV4, nên URL chạy với AuthType: NONE và function tự kiểm chữ ký HMAC của nhà cung cấp (X-Hub-Signature-256). Thay một bộ nhận webhook EC2 + ASG + ALB bằng mỗi hook một Function URL là đáp án ít overhead nhất — thêm API Gateway phía trước chỉ tốn route, stage và phí theo request mà chẳng được gì.
Why a VPC Lambda can't have a public IPVì sao Lambda trong VPC không thể có public IP
A Lambda not attached to a VPC already has outbound internet, on AWS's own network, from an address you don't control. Attach it to your VPC and it loses that — from then on it obeys your route tables, and it has only a private IP. Lambda không gắn VPC vốn đã có internet chiều ra, qua mạng của AWS, từ một địa chỉ bạn không kiểm soát. Gắn nó vào VPC của bạn là mất thứ đó — từ đó nó tuân theo route table của bạn, và nó chỉ có private IP.
| Not attached to a VPCKhông gắn VPC | Attached to your VPCGắn vào VPC của bạn | |
|---|---|---|
| Outbound internet by defaultInternet chiều ra mặc định | ✓ | ✗ — needs NAT or a VPC endpoint✗ — cần NAT hoặc VPC endpoint |
| Reach private RDS / ElastiCacheVới tới RDS / ElastiCache private | ✗ | ✓ |
| Source IP seen by a third partyIP nguồn bên thứ ba nhìn thấy | AWS-owned, changescủa AWS, hay đổi | the NAT gateway's Elastic IP — fixedElastic IP của NAT gateway — cố định |
- Lambda's VPC network interface is a Hyperplane ENI, shared across a subnet + security-group combination and managed entirely by Lambda. You don't own its lifecycle, so there is nothing to attach an Elastic IP to.Network interface của Lambda trong VPC là Hyperplane ENI, dùng chung theo tổ hợp subnet + security group và do Lambda quản lý hoàn toàn. Bạn không sở hữu vòng đời của nó, nên không có chỗ nào để gắn Elastic IP.
- Putting the function in a public subnet does not help. "Public subnet" only means the route table points at an IGW; to use an IGW over IPv4 the resource must have a public IPv4 address, and a Hyperplane ENI doesn't.Đặt function vào public subnet không giúp gì. "Public subnet" chỉ nghĩa là route table trỏ tới IGW; muốn đi qua IGW bằng IPv4 thì resource phải có public IPv4, mà Hyperplane ENI thì không.
- So: "the third party allow-lists one public IP" → private subnet → NAT gateway with an Elastic IP → IGW. That EIP is the address they whitelist.Vậy: "bên thứ ba allow-list một public IP" → private subnet → NAT gateway có Elastic IP → IGW. EIP đó là địa chỉ họ whitelist.
- Calling S3/DynamoDB from a VPC Lambda? Use a VPC endpoint and skip NAT charges entirely.Gọi S3/DynamoDB từ Lambda trong VPC? Dùng VPC endpoint và né hẳn phí NAT.
- IPv6-only egress is the egress-only internet gateway — it has nothing to do with IPv4 or Elastic IPs.Egress chỉ IPv6 là việc của egress-only internet gateway — không liên quan gì tới IPv4 hay Elastic IP.
Versions, aliases & canaryVersion, alias & canary
A version is immutable published code. An alias is a stable pointer that callers use — and the alias is the only place traffic can be split. Canary for Lambda is never DNS. Một version là code đã publish, bất biến. Một alias là con trỏ ổn định mà caller dùng — và alias là nơi duy nhất chia được traffic. Canary cho Lambda không bao giờ là DNS.
# 10% sang version 11, alias production vẫn trỏ chính vào version 10
aws lambda update-alias \
--function-name my-function --name production \
--function-version 10 \
--routing-config 'AdditionalVersionWeights={"11":0.10}'
# cutover: đổi primary sang 11 và bỏ weight
aws lambda update-alias --function-name my-function --name production \
--function-version 11 --routing-config 'AdditionalVersionWeights={}'
--routing-configbelongs toupdate-alias. It is not a parameter ofupdate-function-configuration, which only touches$LATEST's memory, timeout, env vars and VPC config.--routing-configthuộc vềupdate-alias. Nó không phải tham số củaupdate-function-configuration— lệnh đó chỉ đụng memory, timeout, env var và VPC config của$LATEST.- You don't need "an alias per version". Keep one long-lived alias (
production) and move weights through it; API Gateway keeps invoking the same alias ARN throughout.Không cần "mỗi version một alias". Giữ một alias lâu dài (production) và dịch weight qua nó; API Gateway vẫn gọi cùng một alias ARN suốt quá trình. - Via CodeDeploy the configurations are
LambdaCanary10Percent5Minutes,LambdaLinear10PercentEvery1Minute,LambdaAllAtOnce.CodeDeployDefault.OneAtATimeis an EC2/on-prem configuration and is a distractor in any Lambda question.Qua CodeDeploy, các configuration làLambdaCanary10Percent5Minutes,LambdaLinear10PercentEvery1Minute,LambdaAllAtOnce.CodeDeployDefault.OneAtATimelà configuration cho EC2/on-prem và là bẫy trong mọi câu hỏi về Lambda. - In IaC, SAM wraps all of this:
AutoPublishAlias+DeploymentPreferencewith alarms, and CodeDeploy rolls back automatically if an alarm fires.Trong IaC, SAM gói gọn tất cả:AutoPublishAlias+DeploymentPreferencekèm alarm, và CodeDeploy tự rollback nếu alarm kêu.
When Lambda is the wrong computeKhi Lambda là compute sai
The hard ceiling is 15 minutes, and it does not move. Packaging the same code as a container image does not change it — a Lambda container image is still a Lambda. Trần cứng là 15 phút, và nó không nhích. Đóng gói cùng code thành container image cũng không đổi được — Lambda container image vẫn là Lambda.
| SymptomTriệu chứng | Move toChuyển sang |
|---|---|
| Timeouts at the 15-minute max, per-job work (video/image transcode)Timeout ở mức 15 phút, công việc theo từng job (transcode video/ảnh) | ECS Fargate standalone task — a Lambda dispatcher calls ecs:RunTask per job; the task exits when doneECS Fargate standalone task — một Lambda dispatcher gọi ecs:RunTask cho mỗi job; task xong thì tự dừng |
| Long-running always-on workerWorker chạy thường trực | ECS service with a desired countECS service có desired count |
| Thousands of queued batch jobs with dependenciesHàng nghìn batch job xếp hàng có phụ thuộc | AWS Batch |
- The dispatcher Lambda needs
ecs:RunTaskandiam:PassRolefor the task role and task execution role. A task definition never runs by itself —RunTaskcreates the task from it.Lambda dispatcher cầnecs:RunTaskvàiam:PassRolecho task role và task execution role. Task definition không tự chạy —RunTaskmới tạo task từ nó. - Task definition : task :: class : instance. One
RunTaskper job means a fresh task per job, not a permanently running container you send requests to.Task definition : task = class : instance. Mỗi job mộtRunTasknghĩa là một task mới cho mỗi job, không phải một container chạy mãi để bạn gửi request vào. - Step Functions
Parallel+ provisioned concurrency does not extend the timeout — parallel branches each still hit 15 minutes.Step FunctionsParallel+ provisioned concurrency không kéo dài timeout — mỗi nhánh song song vẫn đụng trần 15 phút. - In production put SQS between the event and the dispatcher, so 1,000 uploads don't become 1,000 simultaneous Fargate tasks.Trong production hãy đặt SQS giữa event và dispatcher, để 1.000 lần upload không biến thành 1.000 Fargate task cùng lúc.