Serverless是什么?FaaS、冷启动与何时选择无服务器架构
DevOps

Serverless是什么?FaaS、冷启动与何时选择无服务器架构

Serverless(无服务器)是一种云计算模型,开发者只需部署函数代码,云服务商负责服务器的供给、运维和弹性扩缩容,按调用次数计费。深入了解FaaS、BaaS、冷启动、执行生命周期以及何时选择无服务器架构。

系列文章: DevOps
  1. 1 API网关是什么?微服务的统一入口点
  2. 2 NAT是什么?计算机网络中的网络地址转换详解
  3. 3 GitLab CI/CD是什么?自动化构建、测试与部署流水线
  4. 4 Apache Kafka是什么?分布式事件流处理平台详解
  5. 5 Serverless是什么?FaaS、冷启动与何时选择无服务器架构
  6. 6 Subnet和CIDR是什么?IP网络分段与现代路由
  7. 7 什么是Kubernetes?当今最流行的容器编排平台
  8. 8 Proxy是什么?正向代理、反向代理与SOCKS5详解
  9. 9 什么是Nginx?集Web服务器、反向代理与负载均衡于一体
✦ 快速摘要
Serverless(无服务器)是一种云计算模型,开发者只需部署函数代码,云服务商负责服务器的供给、运维和弹性扩缩容,按调用次数计费。深入了解FaaS、BaaS、冷启动、执行生命周期以及何时选择无服务器架构。
这篇文章怎么样?

Serverless(无服务器)是一种云计算模型,让您无需关心服务器即可部署和运行代码——云平台自动分配资源、按需扩缩容,并按实际使用量计费。本文将详细介绍Serverless是什么、FaaS与BaaS的区别、冷启动的工作原理、函数执行生命周期,以及何时应该(或不应该)选择无服务器架构。

Serverless是什么?

Serverless(无服务器)是一种云计算执行模型,开发者只需编写和部署代码——通常是独立的函数——而服务器的供给、运维和弹性扩缩容完全由云服务商(AWS、GCP、Azure)负责。

"Serverless"这个名称有些误导性:服务器仍然存在,但您不需要管理它们。您无需担心操作系统补丁、安全漏洞修复、负载均衡器配置或磁盘监控。所有这些都从开发者的视野中完全抽象掉了。

Serverless的两个核心特征:

  • 无需管理服务器: 云平台自动供给、扩缩容并回收计算资源。
  • 按调用付费: 按函数调用次数和实际CPU消耗付费,而非为空闲的服务器容量付费。

Serverless涵盖两大分支:FaaS(函数即服务)和BaaS(后端即服务)。下一节将详细区分这两个概念。

FaaS vs BaaS

虽然两者都属于Serverless范畴,但FaaS和BaaS服务于不同的目的:

FaaS——函数即服务是一种将单个函数部署到云端、由事件驱动调用的模型(HTTP请求、队列消息、定时任务等)。函数执行完毕后,云平台立即回收资源。主要代表:

  • AWS Lambda ——最广泛采用的FaaS平台,支持Python、Node.js、Go、Java、Ruby等。
  • Google Cloud Functions ——与Firebase和GCP生态深度集成。
  • Azure Functions ——与微软服务(Event Hub、Service Bus)强集成。
  • Vercel Edge Functions ——针对Next.js和前端场景优化,在离用户最近的边缘节点运行。

BaaS——后端即服务提供开箱即用的后端服务,可直接从前端调用,无需编写服务器代码。主要代表:

  • Firebase(Google)——实时数据库、身份认证、文件存储和推送通知。
  • Supabase ——带实时订阅、认证和存储的PostgreSQL;开源。
  • AWS Amplify ——为前端集成认证(Cognito)、GraphQL(AppSync)和存储(S3)。

核心区别:FaaS让您在服务端运行自定义业务逻辑;BaaS为常见需求提供预构建的基础设施。实际项目中,很多应用会同时使用两者——在同一个应用中使用Firebase Auth(BaaS)和AWS Lambda(FaaS)。

API网关是什么?微服务架构的入口

冷启动 vs 热启动

冷启动延迟是采用Serverless时最实际的挑战之一。

**热启动(Warm Start)**发生在函数最近被调用过、其容器仍在云内存中存活时。下一次调用会立即得到服务——延迟仅为处理函数的执行时间,对于简单业务逻辑通常不超过10毫秒。

**冷启动(Cold Start)**发生在以下情况:

  • 函数部署后首次被调用。
  • 函数空闲时间过长,云平台已回收其容器。
  • 流量突增超过当前热实例数量。

冷启动期间,云平台必须完成完整的初始化链:

  1. 供给容器 ——创建新的隔离执行环境。
  2. 加载运行时 ——启动解释器、JVM或语言运行时。
  3. 获取部署包 ——下载并解压您的代码。
  4. 初始化模块 ——运行模块级初始化代码(导入、数据库连接、配置解析)。
  5. 执行处理函数 ——最终运行您实际编写的函数。

各运行时典型冷启动时间:

运行时 冷启动时间
Node.js ~100–300毫秒
Python ~100–400毫秒
Go ~50–200毫秒
Java (JVM) ~500毫秒–2秒
.NET ~300毫秒–1秒

减少冷启动的策略:

  • 预置并发(AWS Lambda Provisioned Concurrency): 保持一定数量的实例始终温热,完全消除冷启动——但会增加额外费用。
  • 减小包体积: 删除不必要的依赖,使用Tree-shaking。
  • 避免重量初始化: 不在模块作用域中打开数据库连接;使用懒初始化。
  • 选择轻量运行时: Go和Node.js的冷启动时间明显短于Java/Spring。
  • 定时预热: 使用CloudWatch定时任务每5分钟Ping一次函数以保持温热状态。

执行生命周期:从触发到终止

每次无服务器函数被调用时,都会经历固定的四个阶段:

1. 触发(Trigger) 外部事件触发函数——通过API网关的HTTP请求、来自SQS或Kafka的消息、S3的文件上传或定时Cron事件。云平台接收事件并决定将其分发到哪个实例(热启动或冷启动)。

2. 初始化(Init) 此阶段仅在冷启动时发生。云平台创建执行环境、加载运行时并执行所有模块级代码(处理函数之外的代码)。数据库连接、配置解析和重量导入应放在此处,以便在热调用间复用。

3. 执行(Execute) 您的处理函数被以事件对象和上下文对象作为参数调用。这是您编写的代码,返回结果。在AWS Lambda中,这就是lambda_handler(event, context)

4. 终止(Terminate) 处理函数返回后,云平台"冻结"执行环境——容器不会立即销毁,而是保留用于潜在的热启动复用。空闲一段时间后(Lambda通常为15–45分钟),云平台才真正回收容器。

代码示例

AWS Lambda(Python)

Python
 1import json
 2import boto3
 3
 4# 初始化阶段:执行一次,在热调用间复用
 5s3_client = boto3.client('s3')
 6
 7def lambda_handler(event, context):
 8    """
 9    Lambda主处理函数。
10    event: 包含触发器数据的字典(HTTP请求、SQS消息等)
11    context: 包含执行元数据的对象(请求ID、剩余超时时间等)
12    """
13    # 从API网关代理事件中读取HTTP方法和路径
14    http_method = event.get('httpMethod', 'GET')
15    path = event.get('path', '/')
16
17    # 业务逻辑
18    if http_method == 'GET' and path == '/hello':
19        body = {
20            'message': '来自AWS Lambda的问候!',
21            'requestId': context.aws_request_id,
22        }
23        status_code = 200
24    else:
25        body = {'error': '未找到'}
26        status_code = 404
27
28    # 按API网关代理集成格式返回HTTP响应
29    return {
30        'statusCode': status_code,
31        'headers': {
32            'Content-Type': 'application/json',
33            'Access-Control-Allow-Origin': '*',
34        },
35        'body': json.dumps(body, ensure_ascii=False),
36    }

Vercel边缘函数(JavaScript)

JavaScript
 1// api/hello.js — Vercel Edge Runtime
 2// 在距离用户最近的边缘节点运行,延迟低于标准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') || '世界';
11
12  // 边缘函数使用Web标准的Request和Response对象
13  return new Response(
14    JSON.stringify({
15      message: `你好,${name}!由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}

事件触发器类型

无服务器函数可以由多种不同的事件源触发:

HTTP / API网关 最常见的触发器——API网关接收HTTP请求并以标准化事件对象的形式转发给Lambda。适合REST API、Webhook端点和前端后端(BFF)模式。

消息队列(SQS / Kafka / Pub/Sub) 当队列中有新消息时触发函数。Lambda批量轮询SQS队列并并行处理消息。适合异步任务处理和事件驱动架构。

Kafka是什么?分布式系统的消息队列

定时任务(Cron Job) AWS EventBridge Scheduler按Cron计划触发Lambda——例如每天午夜生成营收报告或每周日运行清理任务。完全替代传统服务器上的Crontab。

存储事件(S3 / Cloud Storage) 文件上传到S3存储桶时自动触发函数。广泛用于图片处理流水线——用户上传原始图片→S3触发Lambda→Lambda调整为多个尺寸→保存到CDN存储桶。

数据库流(DynamoDB Streams / Firestore) 每次数据库变更(增/改/删)都会生成触发函数的事件。用于将数据同步到Elasticsearch、发送通知或使缓存失效。

Serverless vs 容器 vs 虚拟机

在设计系统时,以下实用对比矩阵有助于选择正确的计算模型:

评估维度 Serverless 容器(K8s/ECS) 虚拟机
基础设施管理 云全托管 管理集群/Pod 管理完整操作系统
扩缩容 自动、即时 自动HPA,需配置 手动或Auto Scaling Group
空闲成本 $0(不运行=不收费) 为运行中的节点付费 虚拟机24/7付费
冷启动 存在(50毫秒–2秒) 可忽略不计
超时限制 最长15分钟(Lambda) 无限制 无限制
有状态 否(每次调用独立) 是(PVC、StatefulSet)
网络 受限,需配置VPC 灵活 完全控制
运维复杂度 最低 中等至高 最高
最适合 事件驱动、突发流量 长期运行服务 遗留应用、GPU工作负载

Kubernetes是什么?生产环境的容器编排

何时选择Serverless:

  • 间歇性、突发性或不可预测的流量模式。
  • 追求高开发效率,不想投入时间运维基础设施。
  • 事件驱动任务:图片处理、Webhook、ETL流水线、定时任务。
  • 预算有限的MVP或小型微服务。

何时不应选择Serverless:

  • 函数需要持续运行超过15分钟。
  • 应用需要在请求间保持内存中的状态(有状态)。
  • 持续高流量导致成本急剧上升。
  • 需要对运行时、网络或GPU进行精细控制。
  • 需要亚毫秒级延迟、无法接受冷启动延迟。

真实应用场景

1. 图片缩放流水线 用户上传原始图片→S3触发Lambda→Lambda使用Pillow/Sharp调整为3种尺寸(150px缩略图、600px中等、1200px大图)→保存到S3 CDN存储桶。没有上传时成本接近零;流量突增时自动扩缩容。

2. Webhook处理器 Stripe发送支付Webhook→API网关接收→Lambda验证签名、更新数据库中的订单状态并发送确认邮件。Serverless非常适合,因为Webhook是偶发性的——按实际使用量精确付费。

3. 定时报告任务 EventBridge Scheduler每天早上6点触发Lambda→Lambda查询BigQuery/Redshift,汇总前一天的营收报告→向团队Slack频道发送通知。无需服务器24/7运行,只为每天执行2分钟的任务。


API网关是什么?微服务架构的入口

Kafka是什么?分布式系统的消息队列

Kubernetes是什么?生产环境的容器编排

常见问题Q&A
Serverless(无服务器)是什么?
Serverless是一种云计算模型,开发者只需编写并部署代码(通常是独立的函数),服务器的供给、运维和弹性扩缩容完全由云服务商(如AWS、GCP、Azure)负责。您无需租用固定服务器,按函数调用次数和实际CPU执行时间计费。名称有些误导性:服务器仍然存在,但对开发者完全透明不可见。
冷启动是什么?如何减少冷启动延迟?
冷启动发生在函数首次被调用(或长时间空闲后)时——云平台需要创建容器、加载运行时、下载部署包,才能执行您的处理函数,这会增加50毫秒至2秒的额外延迟(具体取决于编程语言)。减少冷启动的方法:使用预置并发(AWS Lambda Provisioned Concurrency)、选择轻量运行时(Node.js/Python优于Java)、减小部署包体积、避免模块级别的重量初始化,以及用定时Ping保持函数温热。
FaaS和BaaS有什么区别?
FaaS(函数即服务)允许您将单个事件驱动的函数部署到云端——AWS Lambda和Google Cloud Functions是典型代表。BaaS(后端即服务)提供开箱即用的后端服务,如数据库、身份认证和文件存储,可直接从客户端调用——Firebase和Supabase是典型代表。两者都属于Serverless,因为您都不需要管理服务器,但FaaS在自定义逻辑方面更灵活,BaaS则更适合快速构建标准CRUD功能。
Serverless能自动弹性扩缩容吗?
可以——自动扩缩容是Serverless最大的优势之一。云平台会在流量增加时自动创建更多函数实例,在流量下降时自动回收,对开发者完全透明。AWS Lambda默认支持1000个并发执行,可按需提高上限。您无需配置Auto Scaling Group或Kubernetes HPA。
Serverless比VPS贵吗?
取决于您的流量模式。对于突发性、间歇性流量(长时间空闲),Serverless通常便宜得多,因为函数不运行时不收费。对于持续高流量的工作负载,按调用计费可能超过VPS成本。AWS Lambda收费约为每100万次请求0.2美元,加上每GB-秒0.0000166667美元。一台4GB/2核VPS约每月20美元——如果函数接近全天候运行,VPS更划算。
什么情况下不应该使用Serverless?
以下情况不适合Serverless:(1)函数需要运行超过超时限制(AWS Lambda最长15分钟);(2)应用需要在请求间保持内存中的状态(有状态应用);(3)持续高流量导致成本急剧上升;(4)需要对运行时、网络或GPU进行精细控制;(5)需要亚毫秒级延迟、无法接受冷启动。这些情况下,容器或虚拟机是更好的选择。

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.