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.
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.
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.
Mental model
Owning a taxi fleet
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.
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.
Key commands
npx serverless create --template aws-nodejs-typescriptScaffold a Serverless Framework project with a TypeScript template.
serverless deployPackage the functions and deploy them with their IAM roles and triggers.
✔ Service deployed to stack dev (duration: 42s)
serverless invoke -f helloInvoke a function directly to test it without hitting the trigger.
{"statusCode":200,"body":"{\"message\":\"Go Serverless v4.0!\"}"}serverless logs -f hello --tailTail the function's CloudWatch logs for debugging.
serverless removeTear down the whole stack so nothing is billed afterwards.
Examples
An HTTP Lambda handler
// handler.ts - a serverless function responding to HTTP eventsexport 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.
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.
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.
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.
Common issues
Task timed out after 3.00 secondsThe handler exceeded the configured timeout, often due to a slow external call.
Raise the timeout if justified, but better: find the slow dependency, add timeouts and move heavy work to async queues.
AccessDeniedException when writing to S3The function's execution role lacks the permission for that bucket and action.
Add the correct IAM policy (for example s3:PutObject on the bucket ARN) to the function's role.
Endpoint request timed out (API Gateway)API Gateway's 29-second integration timeout was hit, or the function returned a response shape Gateway rejects.
Keep synchronous paths short and return the API Gateway response shape ({ statusCode, headers, body }); move slow work to async.
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.
Interview checkpoint
Hands-on lab
- 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
Quick quiz
Which property is a hard requirement for well-behaved serverless functions?
Serverless platforms charge you for idle capacity when a function is not invoked.
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?
Cheat sheet
serverless deployDeploy the whole stackserverless invoke -f <fn>Test without the triggerserverless logs -f <fn> --tailStream function logsserverless removeTear down and stop billingserverless infoShow deployed endpoints and ARNsProvisioned concurrencyRemoves cold starts at a costMemory sizingSets CPU and price per msConcurrency capBills can only grow so fastBudget alarmsAlert before the surprise invoice