Skip to content

Serverless — AWS Lambda — Theory (Bản gốc slide / Original slide) ​

1. Serverless là gì? (What's Serverless?) ​

  • Serverless là một paradigm mới, trong đó developer không cần quản lý server nữa…
  • Họ chỉ deploy code
  • Họ chỉ deploy… function!
  • Ban đầu... Serverless == FaaS (Function as a Service)
  • Serverless được AWS Lambda tiên phong, nhưng giờ bao gồm cả mọi thứ "được quản lý": database, messaging, storage…
  • Serverless không có nghĩa là không có server… nó nghĩa là bạn không quản lý/provision/nhìn thấy chúng
  • Serverless is a new paradigm in which developers don't have to manage servers anymore…
  • They just deploy code
  • They just deploy… functions!
  • Initially... Serverless == FaaS (Function as a Service)
  • Serverless was pioneered by AWS Lambda but now also includes anything that's managed: databases, messaging, storage, etc.
  • Serverless does not mean there are no servers… it means you just don't manage/provision/see them

2. Serverless trong AWS (Serverless in AWS) ​

Các dịch vụ serverless tiêu biểu của AWS:

  • AWS Lambda
  • DynamoDB
  • AWS Cognito
  • AWS API Gateway
  • Amazon S3
  • AWS SNS & SQS
  • AWS Kinesis Data Firehose
  • Aurora Serverless
  • Step Functions
  • Fargate

Ví dụ kiến trúc: Client → S3 bucket (static content) hoặc API Gateway (REST API) → Cognito (login) → Lambda (xử lý logic) → DynamoDB (lưu trữ)

Typical AWS serverless services:

  • AWS Lambda
  • DynamoDB
  • AWS Cognito
  • AWS API Gateway
  • Amazon S3
  • AWS SNS & SQS
  • AWS Kinesis Data Firehose
  • Aurora Serverless
  • Step Functions
  • Fargate

Example architecture: Client → S3 bucket (static content) or API Gateway (REST API) → Cognito (login) → Lambda (processing logic) → DynamoDB (storage)

3. Vì sao dùng AWS Lambda? (Why AWS Lambda) ​

Amazon EC2AWS Lambda
Bản chấtVirtual server trên cloudVirtual function — không có server để quản lý!
Giới hạn bởiRAM và CPUThời gian — chỉ chạy trong khoảng ngắn
Vòng đờiChạy liên tụcChạy theo yêu cầu (on-demand)
ScalingCần can thiệp thủ công để thêm/bớt serverTự động hoàn toàn
Amazon EC2AWS Lambda
NatureVirtual server in the cloudVirtual function — no servers to manage!
Limited byRAM and CPUTime — short executions
LifecycleContinuously runningRuns on-demand
ScalingRequires intervention to add/remove serversFully automated

4. Lợi ích của AWS Lambda (Benefits) ​

  • Định giá dễ hiểu (Easy Pricing):
    • Trả tiền theo số lần gọi (request) và thời gian tính toán (compute time)
    • Free tier: 1,000,000 request và 400,000 GB-giây compute time
  • Tích hợp với toàn bộ hệ sinh thái AWS
  • Tích hợp với nhiều ngôn ngữ lập trình
  • Dễ giám sát qua AWS CloudWatch
  • Dễ tăng tài nguyên cho mỗi function (tới 10GB RAM!)
  • Tăng RAM cũng giúp tăng cả CPU lẫn network!
  • Easy Pricing:
    • Pay per request and compute time
    • Free tier of 1,000,000 AWS Lambda requests and 400,000 GB-seconds of compute time
  • Integrated with the whole AWS suite of services
  • Integrated with many programming languages
  • Easy monitoring through AWS CloudWatch
  • Easy to get more resources per function (up to 10GB of RAM!)
  • Increasing RAM will also improve CPU and network!

5. Ngôn ngữ hỗ trợ & Lambda Container Image ​

  • Node.js (JavaScript)
  • Python
  • Java
  • C# (.NET Core) / Powershell
  • Ruby
  • Custom Runtime API (cộng đồng hỗ trợ — ví dụ Rust hoặc Golang)

Lambda Container Image:

  • Container image phải implement Lambda Runtime API
  • ECS/Fargate được ưu tiên hơn nếu muốn chạy Docker image tuỳ ý (không tuân theo Lambda Runtime API)
  • Node.js (JavaScript)
  • Python
  • Java
  • C# (.NET Core) / Powershell
  • Ruby
  • Custom Runtime API (community supported, e.g., Rust or Golang)

Lambda Container Image:

  • The container image must implement the Lambda Runtime API
  • ECS/Fargate is preferred for running arbitrary Docker images (that don't follow the Lambda Runtime API)

6. AWS Lambda Integrations & Ví dụ thực tế ​

New image in S3AWS Lambda FunctionCreates a ThumbnailNew thumbnail in S3Metadata in DynamoDBname, size, date…triggerpushpush

Các tích hợp chính của Lambda:

  • API Gateway, Kinesis, DynamoDB, S3, CloudFront
  • CloudWatch Events/EventBridge, CloudWatch Logs, SNS, SQS, Cognito

Ví dụ: Tạo Thumbnail Serverless

  • Ảnh mới upload lên S3 → trigger Lambda Function → Lambda tạo thumbnail, push thumbnail mới lại vào S3, và push metadata (tên ảnh, kích thước, ngày tạo…) vào DynamoDB

Ví dụ: Serverless CRON Job

  • CloudWatch Events/EventBridge trigger mỗi 1 giờ → gọi Lambda Function để thực hiện một tác vụ

Lambda's main integrations:

  • API Gateway, Kinesis, DynamoDB, S3, CloudFront
  • CloudWatch Events/EventBridge, CloudWatch Logs, SNS, SQS, Cognito

Example: Serverless Thumbnail creation

  • A new image uploaded to S3 → triggers a Lambda Function → Lambda creates a thumbnail, pushes the new thumbnail back to S3, and pushes metadata (image name, size, creation date…) into DynamoDB

Example: Serverless CRON Job

  • CloudWatch Events/EventBridge triggers every 1 hour → invokes a Lambda Function to perform a task

7. AWS Lambda — Pricing ​

  • Xem giá đầy đủ tại: aws.amazon.com/lambda/pricing/
  • Trả theo số lần gọi (pay per calls):
    • 1,000,000 request đầu tiên miễn phí
    • $0.20/1 triệu request sau đó (~$0.0000002/request)
  • Trả theo thời gian (pay per duration) — tính theo đơn vị 1ms:
    • 400,000 GB-giây compute time/tháng MIỄN PHÍ
    • Tương đương 400,000 giây nếu function dùng 1GB RAM
    • Tương đương 3,200,000 giây nếu function dùng 128MB RAM
    • Sau đó $1.00 cho mỗi 600,000 GB-giây
  • Thường rất rẻ khi chạy Lambda → đó là lý do Lambda rất phổ biến
  • Full pricing at: aws.amazon.com/lambda/pricing/
  • Pay per calls:
    • First 1,000,000 requests are free
    • $0.20 per 1 million requests thereafter (~$0.0000002/request)
  • Pay per duration (in increments of 1 ms):
    • 400,000 GB-seconds of compute time per month for FREE
    • == 400,000 seconds if function is 1GB RAM
    • == 3,200,000 seconds if function is 128 MB RAM
    • After that $1.00 for 600,000 GB-seconds
  • It's usually very cheap to run AWS Lambda — that's why it's so popular

8. AWS Lambda — Giới hạn cần biết (Limits, per region) ​

Execution:

  • Memory allocation: 128 MB – 10GB (tăng theo bước 1 MB)
  • Thời gian thực thi tối đa: 900 giây (15 phút)
  • Environment variables: 4 KB
  • Dung lượng đĩa trong "function container" (/tmp): 512 MB tới 10GB
  • Concurrency execution: 1000 (có thể tăng)

Deployment:

  • Kích thước deployment (.zip nén): 50 MB
  • Kích thước sau giải nén (code + dependency): 250 MB
  • Có thể dùng thư mục /tmp để load thêm file lúc khởi động
  • Kích thước environment variables: 4 KB

Execution:

  • Memory allocation: 128 MB – 10GB (1 MB increments)
  • Maximum execution time: 900 seconds (15 minutes)
  • Environment variables: 4 KB
  • Disk capacity in the "function container" (/tmp): 512 MB to 10GB
  • Concurrency executions: 1000 (can be increased)

Deployment:

  • Lambda function deployment size (compressed .zip): 50 MB
  • Size of uncompressed deployment (code + dependencies): 250 MB
  • Can use the /tmp directory to load other files at startup
  • Size of environment variables: 4 KB

9. Lambda — Concurrency & Throttling ​

Many users → ALBFew users → API GW / SDK1000 concurrentLambda executionsTHROTTLE!THROTTLE!
  • Concurrency limit: tối đa 1000 execution đồng thời (per region)
  • Có thể đặt "reserved concurrency" ở cấp function (= giới hạn riêng cho function đó)
  • Mỗi invocation vượt quá concurrency limit sẽ kích hoạt "Throttle"
  • Hành vi Throttle:
    • Nếu là synchronous invocation → trả về ThrottleError - 429
    • Nếu là asynchronous invocation → tự động retry, sau đó chuyển vào DLQ (Dead Letter Queue)
  • Cần limit cao hơn → mở support ticket

⚠️ Vấn đề Concurrency: nếu không đặt reserved concurrency, MỌI nguồn traffic (ALB nhiều user, API Gateway/SDK ít user…) đều dùng chung giới hạn 1000 concurrent execution — một nguồn traffic lớn có thể làm cạn kiệt concurrency và khiến các nguồn khác cũng bị Throttle theo.

Concurrency & Asynchronous Invocations:

  • Nếu function không đủ concurrency để xử lý hết event → request thêm bị throttle
  • Với lỗi throttling (429) và system error (500-series) → Lambda trả event về lại queue và thử chạy lại function tới 6 giờ
  • Khoảng thời gian retry tăng theo cấp số nhân: từ 1 giây sau lần thử đầu tiên, tối đa 5 phút
  • Concurrency limit: up to 1000 concurrent executions (per region)
  • Can set a "reserved concurrency" at the function level (= a limit for that function)
  • Each invocation over the concurrency limit will trigger a "Throttle"
  • Throttle behavior:
    • If synchronous invocation => return ThrottleError - 429
    • If asynchronous invocation => retry automatically and then go to DLQ
  • If you need a higher limit, open a support ticket

⚠️ Concurrency Issue: if you don't reserve (limit) concurrency, ALL traffic sources (many ALB users, few API Gateway/SDK users…) share the same 1000 concurrent executions limit — one large traffic source can exhaust concurrency and cause the others to be throttled too.

Concurrency and Asynchronous Invocations:

  • If the function doesn't have enough concurrency to process all events, additional requests are throttled
  • For throttling errors (429) and system errors (500-series), Lambda returns the event to the queue and attempts to run the function again for up to 6 hours
  • The retry interval increases exponentially: from 1 second after the first attempt, up to a maximum of 5 minutes

10. Cold Starts, Provisioned Concurrency & SnapStart ​

Cold Start:

  • Instance mới => code được load và code ngoài handler chạy (init)
  • Nếu phần init lớn (code, dependency, SDK…) => quá trình này có thể mất thời gian
  • Request đầu tiên do instance mới phục vụ sẽ có latency cao hơn các request sau

Provisioned Concurrency:

  • Concurrency được cấp phát TRƯỚC khi function được gọi
  • => Cold start không bao giờ xảy ra, mọi invocation đều có latency thấp
  • Application Auto Scaling có thể quản lý concurrency (theo lịch hoặc theo target utilization)
  • Lưu ý: cold start trong VPC đã được giảm đáng kể từ tháng 10-11/2019

Lambda SnapStart:

  • Cải thiện hiệu năng Lambda tới 10x mà không tốn thêm phí, cho Java, Python & .NET
  • Khi bật, function được invoke từ trạng thái đã khởi tạo sẵn (pre-initialized) — không cần init từ đầu
  • Khi publish version mới:
    • Lambda khởi tạo function
    • Chụp snapshot của memory và disk state của function đã khởi tạo
    • Snapshot được cache để truy cập độ trễ thấp

Cold Start:

  • New instance => code is loaded and code outside the handler runs (init)
  • If the init is large (code, dependencies, SDK…), this process can take some time
  • The first request served by a new instance has higher latency than the rest

Provisioned Concurrency:

  • Concurrency is allocated before the function is invoked (in advance)
  • So the cold start never happens and all invocations have low latency
  • Application Auto Scaling can manage concurrency (schedule or target utilization)
  • Note: cold starts in VPC have been dramatically reduced in Oct & Nov 2019

Lambda SnapStart:

  • Improves Lambda function performance up to 10x at no extra cost, for Java, Python & .NET
  • When enabled, the function is invoked from a pre-initialized state (no initialization from scratch)
  • When you publish a new version:
    • Lambda initializes your function
    • Takes a snapshot of the memory and disk state of the initialized function
    • The snapshot is cached for low-latency access

11. Customization at the Edge — CloudFront Functions & Lambda@Edge ​

  • Nhiều ứng dụng hiện đại thực thi một phần logic ngay tại edge
  • Edge Function: đoạn code bạn viết và gắn vào CloudFront distribution, chạy gần user để giảm latency
  • CloudFront cung cấp 2 loại: CloudFront Functions & Lambda@Edge
  • Không cần quản lý server nào, được deploy toàn cầu
  • Use case: tuỳ biến nội dung CDN
  • Trả tiền theo mức dùng, hoàn toàn serverless

Use cases chung: bảo mật & quyền riêng tư website, ứng dụng web động tại edge, SEO, định tuyến thông minh qua nhiều origin/data center, chống bot tại edge, biến đổi ảnh real-time, A/B testing, xác thực/uỷ quyền user, ưu tiên hoá user, tracking & analytics user

  • Many modern applications execute some form of logic at the edge
  • Edge Function: code you write and attach to CloudFront distributions, runs close to your users to minimize latency
  • CloudFront provides two types: CloudFront Functions & Lambda@Edge
  • No servers to manage, deployed globally
  • Use case: customize CDN content
  • Pay only for what you use, fully serverless

Common use cases: website security and privacy, dynamic web applications at the edge, SEO, intelligently routing across origins/data centers, bot mitigation at the edge, real-time image transformation, A/B testing, user authentication & authorization, user prioritization, user tracking & analytics

12. CloudFront Functions vs. Lambda@Edge ​

  • CloudFront Functions: function nhẹ viết bằng JavaScript, cho use case scale cao, nhạy cảm độ trễ; tốc độ khởi động dưới mili-giây, xử lý hàng triệu request/giây; dùng để thay đổi Viewer Request (sau khi CloudFront nhận request từ viewer) và Viewer Response (trước khi CloudFront trả response về viewer); là tính năng native của CloudFront
  • Lambda@Edge: function viết bằng NodeJS hoặc Python, scale tới hàng nghìn request/giây; dùng để thay đổi cả 4 điểm: Viewer Request, Origin Request (trước khi forward tới origin), Origin Response (sau khi nhận response từ origin), Viewer Response; viết function ở một region (us-east-1), CloudFront tự replicate ra các location khác

Bảng so sánh:

CloudFront FunctionsLambda@Edge
RuntimeJavaScriptNode.js, Python
Số requestHàng triệu/giâyHàng nghìn/giây
CloudFront TriggersViewer Request/ResponseViewer + Origin Request/Response
Thời gian thực thi tối đa< 1 ms5–10 giây
Bộ nhớ tối đa2 MB128 MB – 10 GB
Kích thước package10 KB1 MB – 50 MB
Truy cập mạng/file systemKhôngCó
Truy cập request bodyKhôngCó
GiáCó free tier, bằng 1/6 giá Lambda@EdgeKhông free tier, tính theo request & duration

Use case điển hình:

  • CloudFront Functions: chuẩn hoá cache key, thao tác HTTP header, rewrite/redirect URL, xác thực request (validate JWT…)
  • Lambda@Edge: thời gian thực thi dài hơn, tuỳ chỉnh CPU/RAM, code phụ thuộc thư viện bên thứ 3 (ví dụ AWS SDK), cần truy cập mạng ngoài, cần truy cập file system hoặc request body
  • CloudFront Functions: lightweight functions in JavaScript, for high-scale, latency-sensitive use cases; sub-ms startup, millions of requests/second; used to change Viewer Request (after CloudFront receives a request) and Viewer Response (before forwarding the response to the viewer); a native CloudFront feature
  • Lambda@Edge: functions in NodeJS or Python, scales to thousands of requests/second; used to change all 4 points: Viewer Request, Origin Request (before forwarding to origin), Origin Response (after receiving from origin), Viewer Response; author functions in one region (us-east-1), CloudFront replicates to its locations

Comparison table:

CloudFront FunctionsLambda@Edge
RuntimeJavaScriptNode.js, Python
# RequestsMillions/secThousands/sec
CloudFront TriggersViewer Request/ResponseViewer + Origin Request/Response
Max. Execution Time< 1 ms5–10 seconds
Max. Memory2 MB128 MB – 10 GB
Package Size10 KB1 MB – 50 MB
Network/File System AccessNoYes
Request Body AccessNoYes
PricingFree tier, 1/6th price of @EdgeNo free tier, charged per request & duration

Typical use cases:

  • CloudFront Functions: cache key normalization, header manipulation, URL rewrites/redirects, request authentication (validate JWT…)
  • Lambda@Edge: longer execution time, adjustable CPU/memory, code depending on 3rd party libraries (e.g., AWS SDK), needs network access, needs file system or request body access

13. Lambda mặc định & Lambda trong VPC ​

Lambda FunctionPrivate subnetENIAmazon RDSRDS Security Group ← Lambda Security Group

Lambda mặc định:

  • Mặc định, Lambda function được chạy NGOÀI VPC của bạn (trong một VPC do AWS sở hữu)
  • Do đó, không thể truy cập tài nguyên trong VPC của bạn (RDS, ElastiCache, internal ELB…)

Lambda trong VPC:

  • Phải định nghĩa VPC ID, Subnet, và Security Group
  • Lambda sẽ tạo một ENI (Elastic Network Interface) trong subnet của bạn để có thể truy cập tài nguyên VPC (ví dụ RDS)

Lambda by default:

  • By default, your Lambda function is launched outside your own VPC (in an AWS-owned VPC)
  • Therefore, it cannot access resources in your VPC (RDS, ElastiCache, internal ELB…)

Lambda in VPC:

  • You must define the VPC ID, Subnets and Security Groups
  • Lambda will create an ENI (Elastic Network Interface) in your subnets to access VPC resources (e.g., RDS)

14. Lambda với RDS Proxy & Invoking Lambda từ RDS/Aurora ​

Lambda với RDS Proxy:

  • Nếu Lambda function truy cập database trực tiếp, có thể mở quá nhiều connection khi tải cao
  • RDS Proxy giúp:
    • Cải thiện khả năng scale bằng cách pool và chia sẻ connection
    • Cải thiện availability bằng cách giảm 66% thời gian failover và giữ nguyên connection
    • Cải thiện bảo mật bằng cách bắt buộc IAM authentication và lưu credential trong Secrets Manager
  • Lambda function phải deploy trong VPC, vì RDS Proxy không bao giờ public

Invoking Lambda từ RDS & Aurora:

  • Có thể gọi Lambda function ngay từ trong DB instance
  • Cho phép xử lý data event ngay trong database
  • Chỉ hỗ trợ RDS for PostgreSQL và Aurora MySQL
  • DB instance phải cho phép outbound traffic tới Lambda function (Public, NAT GW, VPC Endpoint)
  • DB instance cần có quyền gọi Lambda (Lambda Resource-based Policy & IAM Policy)
  • Ví dụ: user INSERT vào DB → DB invoke Lambda function → Lambda gửi email qua Amazon SES

RDS Event Notifications:

  • Thông báo về chính DB instance (created, stopped, start…) — không có thông tin về dữ liệu bên trong
  • Subscribe theo category: DB instance, DB snapshot, DB Parameter Group, DB Security Group, RDS Proxy, Custom Engine Version
  • Sự kiện gần real-time (tối đa 5 phút)
  • Gửi thông báo tới SNS hoặc subscribe qua EventBridge (rồi tới SQS Queue, Lambda function…)

Lambda with RDS Proxy:

  • If Lambda functions access your database directly, they may open too many connections under high load
  • RDS Proxy helps:
    • Improve scalability by pooling and sharing DB connections
    • Improve availability by reducing failover time by 66% and preserving connections
    • Improve security by enforcing IAM authentication and storing credentials in Secrets Manager
  • The Lambda function must be deployed in your VPC, because RDS Proxy is never publicly accessible

Invoking Lambda from RDS & Aurora:

  • Invoke Lambda functions from within your DB instance
  • Allows you to process data events from within a database
  • Supported for RDS for PostgreSQL and Aurora MySQL only
  • Must allow outbound traffic to your Lambda function from within the DB instance (Public, NAT GW, VPC Endpoints)
  • DB instance must have the required permissions to invoke the Lambda function (Lambda Resource-based Policy & IAM Policy)
  • Example: user INSERTs into the DB → the DB invokes a Lambda function → Lambda sends an email via Amazon SES

RDS Event Notifications:

  • Notifications about the DB instance itself (created, stopped, start…) — no information about the data itself
  • Subscribe to event categories: DB instance, DB snapshot, DB Parameter Group, DB Security Group, RDS Proxy, Custom Engine Version
  • Near real-time events (up to 5 minutes)
  • Send notifications to SNS or subscribe via EventBridge (then to SQS Queue, Lambda function…)

Personal notes by thanhlt