Serverless là gì? FaaS, Cold Start và khi nào nên dùng Serverless
DevOps

Serverless là gì? FaaS, Cold Start và khi nào nên dùng Serverless

Serverless là mô hình điện toán đám mây không quản lý server — chỉ viết function, cloud lo phần còn lại. Tìm hiểu FaaS, BaaS, cold start, execution lifecycle và khi nào nên chọn Serverless.

Trong series: DevOps
  1. 1 API Gateway là gì? Cổng vào thống nhất cho Microservices
  2. 2 NAT là gì? Network Address Translation trong mạng máy tính
  3. 3 GitLab CI/CD là gì? Pipeline tự động hóa build, test và deploy
  4. 4 Kafka là gì? Nền tảng Event Streaming phân tán cho hệ thống lớn
  5. 5 Serverless là gì? FaaS, Cold Start và khi nào nên dùng Serverless
  6. 6 Subnet và CIDR là gì? Chia mạng IP và định tuyến hiện đại
  7. 7 Kubernetes là gì? Nền tảng điều phối container phổ biến nhất hiện nay
  8. 8 Proxy là gì? Forward Proxy, Reverse Proxy và SOCKS5
  9. 9 Nginx là gì? Web server, reverse proxy và load balancer trong một
✦ Tóm tắt nhanh
Serverless là mô hình điện toán đám mây không quản lý server — chỉ viết function, cloud lo phần còn lại. Tìm hiểu FaaS, BaaS, cold start, execution lifecycle và khi nào nên chọn Serverless.
Bài này thế nào?

Serverless là mô hình điện toán đám mây cho phép bạn triển khai và chạy code mà không cần quan tâm đến server — cloud tự động cấp phát tài nguyên, scale theo demand và tính tiền theo mức sử dụng thực tế. Bài viết này giải thích Serverless là gì, phân biệt FaaS và BaaS, hiểu rõ vấn đề cold start, vòng đời thực thi function và khi nào nên (hoặc không nên) chọn kiến trúc serverless.

Serverless là gì?

Serverless (hay "không máy chủ") là mô hình điện toán đám mây trong đó nhà phát triển chỉ viết và triển khai code — thường là các hàm (function) riêng lẻ — còn toàn bộ việc cung cấp, vận hành và scale server do nhà cung cấp cloud (AWS, GCP, Azure) đảm nhận hoàn toàn.

Tên gọi "serverless" đôi khi gây hiểu nhầm: server vẫn tồn tại, nhưng bạn không phải quản lý chúng. Bạn không cần lo về cài đặt OS, vá lỗi bảo mật, cấu hình load balancer hay monitor disk. Tất cả được trừu tượng hóa khỏi tầm nhìn của developer.

Hai đặc điểm định nghĩa serverless:

  • No server management: Cloud tự động cấp, scale và thu hồi tài nguyên tính toán.
  • Pay-per-invocation: Bạn trả tiền cho mỗi lần hàm được gọi và thời gian CPU thực tế, không phải cho server ngồi không.

Serverless bao gồm hai nhánh chính: FaaS (Function as a Service) và BaaS (Backend as a Service). Phần dưới sẽ phân biệt rõ hai khái niệm này.

FaaS vs BaaS

Mặc dù cả hai đều thuộc hệ sinh thái serverless, FaaS và BaaS phục vụ mục đích khác nhau:

FaaS — Function as a Service là mô hình bạn viết từng hàm riêng lẻ, triển khai lên cloud và hàm đó được kích hoạt bởi sự kiện (HTTP request, queue message, cron job…). Hàm chạy xong là cloud thu hồi tài nguyên ngay lập tức. Ví dụ điển hình:

  • AWS Lambda — dịch vụ FaaS phổ biến nhất, hỗ trợ Python, Node.js, Go, Java, Ruby…
  • Google Cloud Functions — tích hợp sâu với Firebase và GCP ecosystem.
  • Azure Functions — mạnh về tích hợp với dịch vụ Microsoft (Event Hub, Service Bus).
  • Vercel Edge Functions — tối ưu cho Next.js và web frontend, chạy tại edge node gần user nhất.

BaaS — Backend as a Service cung cấp các dịch vụ backend dựng sẵn mà bạn gọi trực tiếp từ frontend mà không cần viết server code. Ví dụ điển hình:

  • Firebase (Google) — realtime database, auth, file storage, push notification.
  • Supabase — PostgreSQL + realtime subscriptions + auth + storage, mã nguồn mở.
  • AWS Amplify — tích hợp auth (Cognito), GraphQL (AppSync), storage (S3) cho frontend.

Điểm khác biệt cốt lõi: FaaS cho phép bạn viết logic nghiệp vụ tùy chỉnh chạy phía backend, còn BaaS cung cấp infrastructure dựng sẵn cho các nhu cầu phổ biến. Trong thực tế, nhiều dự án kết hợp cả hai — dùng Firebase Auth (BaaS) và AWS Lambda (FaaS) trong cùng một ứng dụng.

API Gateway là gì? Cổng vào của kiến trúc microservice

Cold Start vs Warm Start

Đây là một trong những thách thức thực tế nhất khi dùng serverless — cold start latency.

Warm start xảy ra khi một function vừa được gọi gần đây và container chứa nó vẫn còn sống trong bộ nhớ của cloud. Lần gọi tiếp theo được phục vụ ngay lập tức — latency chỉ là thời gian thực thi code, thường dưới 10ms với business logic đơn giản.

Cold start xảy ra khi:

  • Function được gọi lần đầu tiên sau khi deploy.
  • Function không được gọi trong một thời gian dài (cloud đã thu hồi container).
  • Traffic tăng đột biến vượt quá số instance đang warm.

Trong cold start, cloud phải thực hiện toàn bộ chuỗi khởi tạo:

  1. Provision container — tạo môi trường cô lập mới.
  2. Load runtime — khởi động interpreter/JVM/runtime cho ngôn ngữ bạn dùng.
  3. Nạp deployment package — download và giải nén code của bạn.
  4. Init module — chạy code khởi tạo ở cấp module (import, connect DB…).
  5. Execute handler — cuối cùng mới chạy hàm thực sự.

Thời gian cold start điển hình theo ngôn ngữ:

Runtime Cold Start
Node.js ~100–300ms
Python ~100–400ms
Go ~50–200ms
Java (JVM) ~500ms–2s
.NET ~300ms–1s

Chiến lược giảm cold start:

  • Provisioned Concurrency (AWS Lambda): Giữ một số instance luôn warm, loại bỏ hoàn toàn cold start — nhưng tốn thêm chi phí.
  • Giảm kích thước package: Loại bỏ dependencies không cần thiết, dùng tree-shaking.
  • Tránh heavy initialization: Không connect database trong module scope; dùng lazy initialization.
  • Chọn runtime nhẹ: Go và Node.js có cold start ngắn hơn Java/Spring đáng kể.
  • Scheduled warm-up: CloudWatch cron ping function mỗi 5 phút để giữ warm.

Execution Lifecycle: từ Trigger đến Terminate

Mỗi lần một serverless function được kích hoạt, nó đi qua một vòng đời cố định gồm 4 giai đoạn:

1. Trigger (Kích hoạt) Một sự kiện từ bên ngoài kích hoạt function — HTTP request qua API Gateway, message từ SQS/Kafka, file upload lên S3, hoặc cron job theo lịch. Cloud nhận sự kiện và quyết định dispatch đến function instance nào (warm hoặc cold start).

2. Init (Khởi tạo) Giai đoạn chỉ xảy ra trong cold start. Cloud tạo execution environment, nạp runtime và chạy toàn bộ code ở cấp module (ngoài handler function). Đây là lý do tại sao các kết nối database, config parsing và import nặng nên được thực hiện ở giai đoạn này để tái sử dụng giữa các warm invocation.

3. Execute (Thực thi) Handler function của bạn được gọi với event object và context object. Đây là phần code bạn viết và trả về kết quả. Với AWS Lambda, đây là hàm lambda_handler(event, context).

4. Terminate (Kết thúc) Sau khi handler trả về, cloud "đóng băng" execution environment — container không bị xóa ngay mà được giữ lại để phục vụ warm start cho lần gọi tiếp theo. Sau một thời gian idle (thường 15–45 phút với Lambda), cloud mới thực sự thu hồi container.

Ví dụ Code thực tế

AWS Lambda (Python)

Python
 1import json
 2import boto3
 3
 4# Init phase: chạy một lần, tái sử dụng cho warm invocations
 5s3_client = boto3.client('s3')
 6
 7def lambda_handler(event, context):
 8    """
 9    Handler chính của Lambda function.
10    event: dict chứa dữ liệu từ trigger (HTTP request, SQS message, v.v.)
11    context: object chứa metadata về execution (request_id, timeout còn lại...)
12    """
13    # Đọc HTTP method và path từ API Gateway event
14    http_method = event.get('httpMethod', 'GET')
15    path = event.get('path', '/')
16    
17    # Logic nghiệp vụ
18    if http_method == 'GET' and path == '/hello':
19        body = {
20            'message': 'Hello from AWS Lambda!',
21            'requestId': context.aws_request_id,
22        }
23        status_code = 200
24    else:
25        body = {'error': 'Not Found'}
26        status_code = 404
27
28    # Trả về HTTP response theo định dạng API Gateway proxy integration
29    return {
30        'statusCode': status_code,
31        'headers': {
32            'Content-Type': 'application/json',
33            'Access-Control-Allow-Origin': '*',
34        },
35        'body': json.dumps(body),
36    }

Vercel Edge Function (JavaScript)

JavaScript
 1// api/hello.js — Vercel Edge Runtime
 2// Chạy tại edge node gần user nhất, latency thấp hơn Lambda thông thường
 3
 4export const config = {
 5  runtime: 'edge',
 6};
 7
 8export default async function handler(request) {
 9  const { searchParams } = new URL(request.url);
10  const name = searchParams.get('name') || 'World';
11
12  // Edge function nhận Web standard Request, trả về Web standard Response
13  return new Response(
14    JSON.stringify({
15      message: `Hello, ${name}! Powered by Vercel Edge.`,
16      region: process.env.VERCEL_REGION || 'unknown',
17    }),
18    {
19      status: 200,
20      headers: {
21        'Content-Type': 'application/json',
22        'Cache-Control': 's-maxage=60, stale-while-revalidate',
23      },
24    }
25  );
26}

Các loại Event Trigger

Serverless function có thể được kích hoạt bởi nhiều loại sự kiện khác nhau:

HTTP / API Gateway Trigger phổ biến nhất — API Gateway nhận HTTP request và chuyển tiếp đến Lambda dưới dạng event object chuẩn hóa. Phù hợp cho REST API, webhook endpoint, và backend-for-frontend.

Queue Message (SQS / Kafka / Pub/Sub) Function được kích hoạt khi có message mới trong hàng đợi. Lambda poll SQS queue theo batch, xử lý song song nhiều message. Phù hợp cho async task processing và event-driven architecture.

Kafka là gì? Message queue cho hệ thống phân tán

Schedule (Cron Job) AWS EventBridge Scheduler (hay CloudWatch Events cũ) kích hoạt Lambda theo lịch cron — ví dụ: chạy báo cáo lúc 00:00 mỗi ngày, dọn dẹp data mỗi Chủ nhật. Thay thế hoàn toàn crontab trên server truyền thống.

Storage Event (S3 / Cloud Storage) Function tự động kích hoạt khi file được upload lên S3 bucket. Dùng phổ biến cho image processing pipeline — user upload ảnh gốc → S3 trigger Lambda → Lambda resize ảnh thành nhiều kích thước → lưu vào bucket khác.

Database Stream (DynamoDB Streams / Firestore) Mỗi thay đổi trong database (insert/update/delete) tạo ra event kích hoạt function. Dùng để đồng bộ dữ liệu sang ElasticSearch, gửi notification, hoặc invalidate cache.

Serverless vs Container vs VM

Khi thiết kế hệ thống, đây là bảng so sánh thực tế để chọn đúng compute model:

Tiêu chí Serverless Container (K8s/ECS) VM
Quản lý hạ tầng Cloud lo hoàn toàn Quản lý cluster/pod Quản lý toàn bộ OS
Scale Tự động, instant Auto HPA, cần cấu hình Manual hoặc auto scaling group
Chi phí idle $0 (không chạy = không tốn) Trả tiền cho node đang chạy Trả tiền cho VM 24/7
Cold start Có (50ms–2s) Không đáng kể Không có
Timeout Tối đa 15 phút (Lambda) Không giới hạn Không giới hạn
Stateful Không (mỗi invocation độc lập) Có (PVC, statefulset)
Networking Hạn chế, cần cấu hình VPC Linh hoạt Toàn quyền kiểm soát
Độ phức tạp vận hành Thấp nhất Trung bình–cao Cao nhất
Phù hợp cho Event-driven, spike traffic Long-running service Legacy app, GPU workload

Kubernetes là gì? Container orchestration cho production

Khi nào chọn Serverless:

  • Workload không liên tục, traffic thất thường hoặc unpredictable.
  • Muốn tốc độ phát triển cao, không muốn tốn thời gian vận hành infrastructure.
  • Tác vụ event-driven: xử lý ảnh, webhook, ETL pipeline, scheduled job.
  • MVP hoặc microservice nhỏ với budget hạn chế.

Khi nào KHÔNG nên chọn Serverless:

  • Function cần chạy liên tục hơn 15 phút.
  • Ứng dụng cần giữ state trong bộ nhớ giữa các request.
  • Workload liên tục cao tải (chi phí leo thang).
  • Cần kiểm soát chi tiết về runtime, network, GPU.
  • Latency cực thấp không chấp nhận cold start.

Use Cases thực tế

1. Image Resize Pipeline User upload ảnh gốc → S3 trigger Lambda → Lambda dùng Pillow/Sharp resize thành 3 kích thước (thumbnail 150px, medium 600px, large 1200px) → lưu vào S3 CDN bucket. Chi phí gần bằng $0 khi không có upload, scale tự động khi traffic tăng.

2. Webhook Handler Khi Stripe gửi payment webhook → API Gateway nhận → Lambda xác thực signature, cập nhật order status trong database và gửi email xác nhận. Serverless lý tưởng vì webhook không liên tục — trả tiền đúng theo số lần được gọi.

3. Scheduled Report Job EventBridge Scheduler kích hoạt Lambda mỗi sáng 6h → Lambda query BigQuery/Redshift, tổng hợp báo cáo doanh thu ngày hôm trước → gửi Slack notification đến channel của team. Không cần server chạy 24/7 chỉ để làm công việc 2 phút mỗi ngày.


Câu hỏi thường gặpQ&A
Serverless là gì?
Serverless là mô hình điện toán đám mây trong đó nhà phát triển chỉ viết và triển khai code (thường là các hàm riêng lẻ), còn toàn bộ việc cung cấp, vận hành và scale server do nhà cung cấp cloud đảm nhận. Bạn không thuê server cố định — bạn trả tiền theo số lần hàm được gọi và thời gian chạy thực tế.
Cold start là gì và làm thế nào để giảm thiểu?
Cold start xảy ra khi một function serverless được kích hoạt lần đầu tiên (hoặc sau một thời gian dài không dùng) — cloud phải khởi tạo container, nạp runtime và load code, làm tăng latency đáng kể (50ms–2s tùy ngôn ngữ). Để giảm thiểu: dùng provisioned concurrency (AWS Lambda), chọn runtime nhẹ (Node.js/Python thay vì Java), giảm kích thước deployment package, và dùng scheduled warm-up ping để giữ function luôn ấm.
FaaS và BaaS khác nhau thế nào?
FaaS (Function as a Service) cho phép bạn triển khai từng hàm riêng lẻ được kích hoạt bởi sự kiện — AWS Lambda, Google Cloud Functions là ví dụ điển hình. BaaS (Backend as a Service) cung cấp các dịch vụ backend dựng sẵn như database, auth, storage mà bạn gọi trực tiếp từ client — Firebase, Supabase là ví dụ. Cả hai đều là serverless vì bạn không quản lý server, nhưng FaaS linh hoạt hơn với logic tùy chỉnh còn BaaS nhanh hơn cho ứng dụng CRUD đơn giản.
Serverless có tự động scale không?
Có — đây là một trong những ưu điểm lớn nhất của serverless. Cloud tự động tạo thêm instance của function khi traffic tăng và thu hồi khi traffic giảm, hoàn toàn minh bạch với developer. AWS Lambda mặc định cho phép đến 1.000 concurrent executions và có thể tăng lên theo yêu cầu. Bạn không cần cấu hình auto-scaling group hay HPA như với container.
Serverless có đắt hơn VPS không?
Phụ thuộc vào traffic pattern. Với workload thất thường (spike ngắn, idle dài) serverless thường rẻ hơn nhiều vì bạn không trả tiền khi function không chạy. Với workload liên tục cao tải, chi phí serverless có thể vượt VPS do tính tiền theo invocation. AWS Lambda tính phí ~$0.20 per 1M requests + $0.0000166667 per GB-second. Một VPS 4GB/2vCPU tốn ~$20/tháng — nếu function chạy gần 24/7 thì VPS rẻ hơn.
Khi nào không nên dùng Serverless?
Serverless không phù hợp khi: (1) Function cần chạy lâu hơn giới hạn timeout (AWS Lambda tối đa 15 phút); (2) Ứng dụng cần trạng thái trong bộ nhớ giữa các request (stateful); (3) Workload liên tục cao tải làm chi phí leo thang; (4) Cần kiểm soát chi tiết về môi trường runtime, network hoặc GPU; (5) Latency cực thấp (sub-millisecond) không chấp nhận cold start. Trong các trường hợp này, container hoặc VM là lựa chọn tốt hơn.

Serverless is a cloud computing model that lets you deploy and run code without worrying about servers — the cloud automatically allocates resources, scales on demand, and bills only for actual usage. This article explains what Serverless is, the difference between FaaS and BaaS, how cold starts work, the function execution lifecycle, and when you should (or shouldn't) choose a serverless architecture.

What is Serverless?

Serverless is a cloud computing execution model where developers only write and deploy code — typically individual functions — while the cloud provider (AWS, GCP, Azure) fully handles server provisioning, operations, and scaling.

The name "serverless" can be misleading: servers still exist, but you don't manage them. You don't worry about OS patching, load balancer configuration, disk monitoring, or capacity planning. All of that is abstracted away from the developer.

Two properties define serverless:

  • No server management: The cloud automatically provisions, scales, and reclaims compute resources.
  • Pay-per-invocation: You pay for each function invocation and actual CPU time consumed, not for idle server capacity.

Serverless encompasses two main branches: FaaS (Function as a Service) and BaaS (Backend as a Service). The next section explains the distinction clearly.

FaaS vs BaaS

Although both fall under the serverless umbrella, FaaS and BaaS serve different purposes:

FaaS — Function as a Service is a model where you write individual functions, deploy them to the cloud, and they're invoked by events (HTTP requests, queue messages, cron schedules, and so on). Once the function completes, the cloud immediately reclaims the resources. Key examples:

  • AWS Lambda — the most widely adopted FaaS platform, supporting Python, Node.js, Go, Java, Ruby, and more.
  • Google Cloud Functions — deeply integrated with Firebase and the GCP ecosystem.
  • Azure Functions — strong integration with Microsoft services (Event Hub, Service Bus).
  • Vercel Edge Functions — optimized for Next.js and frontend use cases, running at edge nodes closest to the user.

BaaS — Backend as a Service provides pre-built backend services that you call directly from the frontend without writing server code. Key examples:

  • Firebase (Google) — realtime database, auth, file storage, and push notifications.
  • Supabase — PostgreSQL with realtime subscriptions, auth, and storage; open source.
  • AWS Amplify — integrates auth (Cognito), GraphQL (AppSync), and storage (S3) for frontend apps.

The core distinction: FaaS lets you run custom business logic server-side; BaaS provides pre-built infrastructure for common needs. In practice, many projects combine both — using Firebase Auth (BaaS) alongside AWS Lambda (FaaS) in the same application.

What is an API Gateway? The Front Door of Microservice Architecture

Cold Start vs Warm Start

Cold start latency is one of the most practical challenges when adopting serverless.

Warm start occurs when a function was invoked recently and its container is still alive in the cloud's memory. The next invocation is served immediately — latency is only your handler execution time, typically under 10ms for simple business logic.

Cold start occurs when:

  • The function is invoked for the first time after a deploy.
  • The function has been idle long enough that the cloud reclaimed its container.
  • A traffic spike exceeds the number of currently warm instances.

During a cold start, the cloud must complete the full initialization chain:

  1. Provision container — create a new isolated execution environment.
  2. Load runtime — start the interpreter, JVM, or language runtime.
  3. Fetch deployment package — download and decompress your code.
  4. Init module — run module-level initialization code (imports, DB connections, config parsing).
  5. Execute handler — finally run your actual function.

Typical cold start durations by runtime:

Runtime Cold Start
Node.js ~100–300ms
Python ~100–400ms
Go ~50–200ms
Java (JVM) ~500ms–2s
.NET ~300ms–1s

Strategies to reduce cold starts:

  • Provisioned Concurrency (AWS Lambda): Keeps a set number of instances warm, completely eliminating cold starts — at an additional cost.
  • Reduce package size: Remove unused dependencies, apply tree-shaking.
  • Avoid heavy initialization: Don't open database connections in module scope; use lazy initialization.
  • Choose lightweight runtimes: Go and Node.js have significantly shorter cold starts than Java/Spring.
  • Scheduled warm-up: Use a CloudWatch cron to ping your function every 5 minutes to keep it warm.

Execution Lifecycle: from Trigger to Terminate

Every time a serverless function is invoked, it passes through a fixed four-phase lifecycle:

1. Trigger An external event fires the function — an HTTP request through API Gateway, a message from SQS or Kafka, a file upload to S3, or a scheduled cron event. The cloud receives the event and decides which instance to dispatch it to (warm or cold start).

2. Init This phase only occurs on a cold start. The cloud creates the execution environment, loads the runtime, and runs all module-level code (outside the handler function). Database connections, config parsing, and heavy imports should live here so they're reused across warm invocations.

3. Execute Your handler function is called with the event object and the context object. This is the code you write; it returns a result. With AWS Lambda, this is lambda_handler(event, context).

4. Terminate After the handler returns, the cloud "freezes" the execution environment — the container isn't immediately destroyed, but is held for potential warm reuse. After a period of idleness (typically 15–45 minutes for Lambda), the cloud truly reclaims the container.

Code Examples

AWS Lambda (Python)

Python
 1import json
 2import boto3
 3
 4# Init phase: runs once and is reused across warm invocations
 5s3_client = boto3.client('s3')
 6
 7def lambda_handler(event, context):
 8    """
 9    Main Lambda handler.
10    event: dict containing trigger data (HTTP request, SQS message, etc.)
11    context: object with execution metadata (request_id, remaining timeout, etc.)
12    """
13    # Read HTTP method and path from API Gateway proxy event
14    http_method = event.get('httpMethod', 'GET')
15    path = event.get('path', '/')
16
17    # Business logic
18    if http_method == 'GET' and path == '/hello':
19        body = {
20            'message': 'Hello from AWS Lambda!',
21            'requestId': context.aws_request_id,
22        }
23        status_code = 200
24    else:
25        body = {'error': 'Not Found'}
26        status_code = 404
27
28    # Return HTTP response in API Gateway proxy integration format
29    return {
30        'statusCode': status_code,
31        'headers': {
32            'Content-Type': 'application/json',
33            'Access-Control-Allow-Origin': '*',
34        },
35        'body': json.dumps(body),
36    }

Vercel Edge Function (JavaScript)

JavaScript
 1// api/hello.js — Vercel Edge Runtime
 2// Runs at the edge node closest to the user for lower latency than standard Lambda
 3
 4export const config = {
 5  runtime: 'edge',
 6};
 7
 8export default async function handler(request) {
 9  const { searchParams } = new URL(request.url);
10  const name = searchParams.get('name') || 'World';
11
12  // Edge functions use Web standard Request and Response objects
13  return new Response(
14    JSON.stringify({
15      message: `Hello, ${name}! Powered by Vercel Edge.`,
16      region: process.env.VERCEL_REGION || 'unknown',
17    }),
18    {
19      status: 200,
20      headers: {
21        'Content-Type': 'application/json',
22        'Cache-Control': 's-maxage=60, stale-while-revalidate',
23      },
24    }
25  );
26}

Event Triggers

Serverless functions can be invoked by a variety of event sources:

HTTP / API Gateway The most common trigger — API Gateway receives an HTTP request and forwards it to Lambda as a normalized event object. Ideal for REST APIs, webhook endpoints, and backend-for-frontend patterns.

Queue Message (SQS / Kafka / Pub/Sub) Functions are triggered when new messages arrive in a queue. Lambda polls SQS in batches and processes messages in parallel. Ideal for async task processing and event-driven architectures.

What is Kafka? Message Queue for Distributed Systems

Schedule (Cron Job) AWS EventBridge Scheduler triggers Lambda on a cron schedule — for example, generating a revenue report at midnight or running cleanup jobs every Sunday. A complete replacement for traditional server crontabs.

Storage Event (S3 / Cloud Storage) Functions automatically trigger when files are uploaded to an S3 bucket. Widely used for image processing pipelines — user uploads a photo → S3 triggers Lambda → Lambda resizes to multiple dimensions → saves to a CDN bucket.

Database Stream (DynamoDB Streams / Firestore) Every database change (insert/update/delete) generates an event that triggers a function. Used for syncing data to Elasticsearch, sending notifications, or invalidating caches.

Serverless vs Container vs VM

When designing a system, here is a practical comparison matrix to help choose the right compute model:

Criterion Serverless Container (K8s/ECS) VM
Infrastructure management Fully managed by cloud Manage cluster/pods Manage full OS
Scaling Automatic, instant Auto HPA, requires config Manual or auto-scaling group
Idle cost $0 (no run = no charge) Pay for running nodes Pay for VM 24/7
Cold start Yes (50ms–2s) Negligible None
Timeout Max 15 minutes (Lambda) Unlimited Unlimited
Stateful No (each invocation is isolated) Yes (PVC, StatefulSet) Yes
Networking Limited, requires VPC config Flexible Full control
Operational complexity Lowest Medium–high Highest
Best for Event-driven, spike traffic Long-running services Legacy apps, GPU workloads

What is Kubernetes? Container Orchestration for Production

When to choose Serverless:

  • Intermittent, bursty, or unpredictable traffic patterns.
  • High development velocity with minimal infrastructure operations.
  • Event-driven tasks: image processing, webhooks, ETL pipelines, scheduled jobs.
  • MVPs or small microservices with a tight budget.

When NOT to choose Serverless:

  • Functions that need to run continuously beyond 15 minutes.
  • Applications that require in-memory state between requests.
  • Continuously high traffic where costs escalate.
  • Fine-grained runtime, networking, or GPU control required.
  • Sub-millisecond latency that cannot tolerate cold start delays.

Real-World Use Cases

1. Image Resize Pipeline User uploads a photo → S3 triggers Lambda → Lambda uses Pillow/Sharp to resize into 3 dimensions (150px thumbnail, 600px medium, 1200px large) → saves to an S3 CDN bucket. Near-zero cost when no uploads are happening; auto-scales when traffic spikes.

2. Webhook Handler Stripe sends a payment webhook → API Gateway receives it → Lambda verifies the signature, updates the order status in the database, and sends a confirmation email. Serverless is ideal because webhooks are sporadic — you pay exactly for what you use.

3. Scheduled Report Job EventBridge Scheduler triggers Lambda every morning at 6 AM → Lambda queries BigQuery/Redshift, aggregates the previous day's revenue report → sends a Slack notification to the team channel. No server running 24/7 just to perform a 2-minute task once a day.


What is an API Gateway? The Front Door of Microservice Architecture

What is Kafka? Message Queue for Distributed Systems

What is Kubernetes? Container Orchestration for Production

Frequently Asked QuestionsQ&A
What is Serverless in simple terms?
Serverless is a cloud computing model where developers only write and deploy code — usually individual functions — while the cloud provider fully handles server provisioning, operations, and scaling. You don't rent a fixed server; you pay per invocation and actual CPU execution time. The name is slightly misleading: servers still exist, but they're completely abstracted away from the developer.
What is a cold start and how can you minimize it?
A cold start occurs when a serverless function is invoked for the first time (or after a long idle period) — the cloud must provision a container, load the runtime, and fetch your deployment package before executing your handler, adding 50ms–2s of latency depending on the language. To minimize it: use Provisioned Concurrency (AWS Lambda), choose a lightweight runtime (Node.js/Python over Java), reduce deployment package size, avoid heavy module-level initialization, and use scheduled warm-up pings every 5 minutes.
What is the difference between FaaS and BaaS?
FaaS (Function as a Service) lets you deploy individual event-triggered functions to the cloud — AWS Lambda and Google Cloud Functions are prime examples. BaaS (Backend as a Service) provides pre-built backend services like database, auth, and storage that you call directly from the client — Firebase and Supabase are examples. Both are serverless because you don't manage servers, but FaaS offers more flexibility for custom logic while BaaS is faster for standard CRUD features.
Does Serverless scale automatically?
Yes — automatic scaling is one of serverless's biggest advantages. The cloud automatically spawns additional function instances when traffic increases and reclaims them when traffic drops, completely transparently to the developer. AWS Lambda defaults to 1,000 concurrent executions and can be increased on request. You don't need to configure auto-scaling groups or Kubernetes HPA.
Is Serverless more expensive than a VPS?
It depends on your traffic pattern. For bursty, unpredictable workloads with long idle periods, serverless is usually much cheaper because you pay nothing when functions aren't running. For continuously high-traffic workloads, serverless costs can exceed a VPS since you're billed per invocation. AWS Lambda charges ~$0.20 per 1M requests plus $0.0000166667 per GB-second. A 4GB/2vCPU VPS costs ~$20/month — if your function runs near 24/7, the VPS is cheaper.
When should you NOT use Serverless?
Serverless is a poor fit when: (1) Functions need to run longer than the timeout limit (AWS Lambda max is 15 minutes); (2) Your application requires in-memory state between requests (stateful); (3) Continuously high traffic makes costs spiral; (4) You need fine-grained control over runtime, networking, or GPU; (5) You need sub-millisecond latency that can't tolerate cold start. In these cases, containers or VMs are better choices.