Architecture
Intermediate 14 min read Architecture

Serverless Architecture

Serverless (FaaS) lets you run functions that scale from zero to thousands of concurrent invocations, paying only for execution time and billing nobody for idle capacity. It trades operational control for extreme elasticity and offloads servers, autoscaling and patching to the provider.

serverlesslambdafaascold startfunctionsprovisioned concurrencypay per invocation
Introduction

What is this?

Serverless computing, in the function-as-a-service sense, runs your code in response to events without you provisioning servers. The provider starts instances, scales them to match demand — including down to zero — and charges per invocation and per millisecond of execution. 'Serverless' is a billing and operations model, not the absence of servers.

Motivation

Why do you need it?

  • Zero idle cost: you pay only when code actually runs, so low-traffic or spiky workloads become cheap.
  • Automatic scaling: the platform scales from zero to hundreds of concurrent executions without any configuration.
  • No servers to patch, monitor or replace — the provider owns the runtime, security updates and capacity.
  • Perfect fit for event-driven glue: webhooks, queues, object-storage triggers and scheduled jobs.
  • Developers ship small, single-purpose functions, which shortens the deploy loop and the blast radius.
Think about it

Mental model

Imagine

Owning a taxi fleet

Think of

Riding a ride-hailing app

A fleet means buying cars, hiring drivers and idling them at 2 a.m. (servers). Ride-hailing scales to demand and you pay per trip (serverless). During a rush it magically has cars; at midnight you pay for nothing standing still.

Mechanics

How it works

  • You package a function (plus its runtime and dependencies) and register a trigger: HTTP, queue, bucket upload or cron.
  • When the trigger fires, the provider schedules an execution and spins up an isolated container for your function.
  • The platform invokes your handler, streams logs and metrics to your observability tool, and scales instances to match concurrency.
  • Cold starts occur when an instance must be created from scratch; warm instances reuse the runtime to cut latency.
  • When idle, instances are reclaimed, so unused functions cost nothing and the next call pays for a cold start.

A serverless function is invoked by an event, scales elastically, and returns to zero.

Trigger
Provider runtime
Cold start?
Warm instance
Handler runs
Idle
Reference

Key commands

npx serverless create --template aws-nodejs-typescript

Scaffold a Serverless Framework project with a TypeScript template.

serverless deploy

Package the functions and deploy them with their IAM roles and triggers.

✔ Service deployed to stack dev (duration: 42s)
serverless invoke -f hello

Invoke a function directly to test it without hitting the trigger.

{"statusCode":200,"body":"{\"message\":\"Go Serverless v4.0!\"}"}
serverless logs -f hello --tail

Tail the function's CloudWatch logs for debugging.

serverless remove

Tear down the whole stack so nothing is billed afterwards.

Hands-on

Examples

An HTTP Lambda handler

An HTTP Lambda handler
// handler.ts - a serverless function responding to HTTP events
export async function handler(event: {
httpMethod: string
path: string
body?: string
}) {
if (event.httpMethod !== "GET") {
return { statusCode: 405, body: JSON.stringify({ error: "method not allowed" }) }
}
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path: event.path, at: new Date().toISOString() }),
}
}

The provider invokes this function with an API Gateway event and expects an API Gateway response. There is no server, no port and no process to keep alive. Statelessness is assumed: any persistent data must go to a database, object store or queue.

Real world

In production

  • Webhook receivers ingest GitHub or Stripe events into queues with zero idle cost.
  • Image and video pipelines resize assets when an object lands in S3, scaling with upload volume.
  • Scheduled jobs (nightly reports, cache warming, dunning emails) run on cron without a server to keep alive.
  • REST endpoints for low-to-medium traffic workloads run behind API Gateway with built-in throttling and auth.
Guidelines

Best practices

  • Design every function to be stateless; keep session data in a database, cache or object store.
  • Right-size memory and timeout: memory usually sets both the allocated CPU and the price per ms.
  • Warm critical paths with provisioned concurrency to eliminate cold-start latency for interactive endpoints.
  • Set sane concurrency limits and alarms so a runaway loop cannot multiply into a large bill.
  • Treat functions as ephemeral: initialize clients outside the handler and reuse them across warm invocations.
Watch out

Common mistakes

  • Putting long-running, connection-heavy workloads in functions where timeouts and per-ms pricing bite.
  • Ignoring cold starts for user-facing paths, adding a painful second to every request after idle.
  • Leaking infrastructure in code (hard-coded ARNs, region names) that breaks when the stack moves.
  • Missing cost controls: no concurrency caps or budgets, then a spike produces a surprise invoice.
Root cause analysis

Common issues

Error
Task timed out after 3.00 seconds
Root cause

The handler exceeded the configured timeout, often due to a slow external call.

Fix

Raise the timeout if justified, but better: find the slow dependency, add timeouts and move heavy work to async queues.

Error
AccessDeniedException when writing to S3
Root cause

The function's execution role lacks the permission for that bucket and action.

Fix

Add the correct IAM policy (for example s3:PutObject on the bucket ARN) to the function's role.

Error
Endpoint request timed out (API Gateway)
Root cause

API Gateway's 29-second integration timeout was hit, or the function returned a response shape Gateway rejects.

Fix

Keep synchronous paths short and return the API Gateway response shape ({ statusCode, headers, body }); move slow work to async.

When things break

Debugging tips

  • Start with function logs and enable X-Ray (or the provider equivalent) to see latency breakdowns.
  • Test the deployed function with serverless invoke, bypassing the trigger to isolate the bug.
  • Watch for cold-start latency vs. handler latency: cold costs appear at the init/import step in traces.
  • Check the environment and IAM role the function runs with — 'AccessDenied' is usually the role, not your code.
Interviews

Interview checkpoint

Practice

Hands-on lab

Deploy Your First Lambda with Serverless Framework
40 min · intermediate
In progress
Objectives
  • Scaffold a Serverless Framework project
  • Write a stateless HTTP handler
  • Deploy it and invoke it through API Gateway
  • Inspect logs and clean up the stack

Deploy Your First Lambda with Serverless Framework

40 min · intermediate

0/5 steps
0%
sandbox · Linux sandbox
$
Try these commands
Test yourself

Quick quiz

0/3
1

Which property is a hard requirement for well-behaved serverless functions?

2

Serverless platforms charge you for idle capacity when a function is not invoked.

3

A user-facing API returns 1.5s responses whenever it has been idle for a few minutes. What is the most likely cause and fix?

Quick reference

Cheat sheet

Serverless Framework commands
serverless deployDeploy the whole stack
serverless invoke -f <fn>Test without the trigger
serverless logs -f <fn> --tailStream function logs
serverless removeTear down and stop billing
serverless infoShow deployed endpoints and ARNs
Cost and latency levers
Provisioned concurrencyRemoves cold starts at a cost
Memory sizingSets CPU and price per ms
Concurrency capBills can only grow so fast
Budget alarmsAlert before the surprise invoice
Go deeper

Official documentation