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
DLQ optionsDLQ có thể chọn Async failures can go to SQS (workers pull, do the recovery job) or SNS (fan-out to alerts + storage). Prefer Lambda Destinations (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ó.
Third model — event source mappingMô hình thứ ba — event source mapping SQS · Kinesis · DynamoDB Streams are neither sync nor async: an event source mapping polls for you and invokes synchronously in batches. Streams block the shard on error until records expire — set bisect-on-error, partial batch response, or an on-failure destination. SQS · Kinesis · DynamoDB Streams không phải sync hay async: event source mapping tự poll rồi invoke sync theo batch. Với stream, lỗi sẽ chặn cả shard tới khi record hết hạn — cấu hình bisect-on-error, partial batch response, hoặc on-failure destination.

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 ❌ ✅
Fixed public IPIP public cố định Vendor whitelisting your outbound? Put Lambda in a private subnet → NAT GW → Elastic IP. That EIP is now the constant source IP the vendor sees. Vendor cần whitelist IP outbound? Đặt Lambda vào private subnet → NAT GW → Elastic IP. EIP đó là source IP cố định vendor thấy.

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.

All-at-once 100% immediately100% ngay
Linear grow every N min · e.g. 10%/3mintăng dần mỗi N phút · vd 10%/3phút
Canary X% first, then jump to 100%X% trước, xong nhảy 100%
Pre / Post hooksPre / Post hook CodeDeploy runs PreTraffic (against new version) and PostTraffic (after shift) health-check functions — fail either and it rolls back. CodeDeploy chạy PreTraffic (kiểm tra version mới) và PostTraffic (sau shift) — fail bên nào cũng rollback.

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ép logs: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ấp AWSXrayWriteOnlyAccess cho 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.

Two panels comparing where a database connection is opened. In the top panel the connection is opened inside the handler, so every invocation pays for a TCP connect, a TLS handshake and database authentication, and each one allocates a new connection on the database. In the bottom panel the connection is opened at module level outside the handler, so it is created once during the initialisation phase and reused by every subsequent invocation that lands on the same warm execution environment. Below, a third row shows that concurrency still multiplies connections: one hundred simultaneous requests create roughly one hundred execution environments, each with its own connection, which is why RDS Proxy is needed to pool them in front of the database. ✗ connect inside the handler invocation 1connect · query · close invocation 2connect · query · close invocation 3connect · query · close TCP + TLS + auth on every request latency, and a connection storm ✓ connect at module level, outside the handler INIT phase connect once invoke 1 · query invoke 2 · query invoke 3 · query same warm environment one connection, reused but concurrency still multiplies: 100 simultaneous requests → ~100 environments → ~100 connections, however you wrote the code one environment serves ONE invocation at a time — so concurrency is the number of live environments that is what RDS Proxy is for: it pools the many Lambda connections down to a few real database connections

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.
  • /tmp and module globals persist across reuse — good for caching config, dangerous for per-request state. Never leak one caller's data into the next invocation./tmp và 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 authAWS_IAM orhoặc NONE — that's all— chỉ vậyIAM · 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 LambdaLambda + per-request API feeLambda + phí API theo request
Webhooks are the canonical fitWebhook là chỗ hợp nhất A Git server calling a webhook can't sign SigV4, so the URL runs with 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ấyAWS-owned, changescủa AWS, hay đổithe 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-config belongs to update-alias. It is not a parameter of update-function-configuration, which only touches $LATEST's memory, timeout, env vars and VPC config.--routing-config thuộc về update-alias. Nó không phải tham số của update-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.OneAtATime is an EC2/on-prem configuration and is a distractor in any Lambda question.Qua CodeDeploy, các configuration là LambdaCanary10Percent5Minutes, LambdaLinear10PercentEvery1Minute, LambdaAllAtOnce. CodeDeployDefault.OneAtATime là 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 + DeploymentPreference with alarms, and CodeDeploy rolls back automatically if an alarm fires.Trong IaC, SAM gói gọn tất cả: AutoPublishAlias + DeploymentPreference kè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ựcECS 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ộcAWS Batch
  • The dispatcher Lambda needs ecs:RunTask and iam:PassRole for the task role and task execution role. A task definition never runs by itself — RunTask creates the task from it.Lambda dispatcher cần ecs:RunTask và iam:PassRole cho task role và task execution role. Task definition không tự chạy — RunTask mới tạo task từ nó.
  • Task definition : task :: class : instance. One RunTask per 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ột RunTask nghĩ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 Functions Parallel + 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.