SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Serverless

Write functions, let the cloud run them on demand, and pay only while they run.

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Serverless means you write small pieces of code (functions) and a cloud provider runs them for you, only when something asks. You do not set up, patch or watch any servers.

  • There are still servers, but the provider owns and manages them. You just upload code.
  • The platform starts copies of your function on demand and scales from zero to thousands, then back to zero.
  • You pay for the time the code runs, not for a server that sits idle.

02Concept: What is it?

In the classic way, you rent a server (or a virtual machine), install your app, keep it running 24 hours a day, and worry about updates, crashes and how many servers you need. You pay whether anyone visits or not.

In the serverless way, you hand the platform a small function, such as "resize this image" or "save this order". You also tell it what should trigger the function: an HTTP request, a new file, a message in a queue, or a timer. When a trigger happens, the platform finds a free machine, starts your code, runs it and then can throw the machine away.

There are two common flavours. FaaS (Function as a Service, like AWS Lambda) runs your code. BaaS (Backend as a Service, like Firebase or managed databases and auth) gives you ready-made backend parts, so you write even less code. Most serverless apps mix both.

What happens on one request
👤TriggerHTTP, file, queue, timer
→↓
🧭Platformfinds or starts a copy
→↓cold: boot first
λYour functionruns, then sleeps
→↓
🗄️Database / storageoutside the function
If no copy of the function is ready, the platform has to start one. This extra wait is called a cold start.
🧠Functions forget everything
A function copy can disappear at any time, so it must be stateless. Anything that must last (users, orders, files) goes to a database or storage service, never to the function's memory or local disk.

03Real-Life Example

🍵A Taxi vs Owning a Car
Owning a car (a server) means you pay for it, park it, fix it and insure it, even on days you never drive. If a big event brings 20 friends, one car is not enough. Taking a taxi (serverless) is different. You pay only for the rides you take, you never worry about a flat tyre, and on a busy night the taxi company sends many cars. But for a daily 8-hour commute, a taxi costs more than your own car, and sometimes you wait a few minutes for the taxi to arrive.
Taxi service
Serverless
Calling for a ride
A trigger (request, file, message, timer)
A taxi that is sent to you
A copy of your function started on demand
Paying per trip
Paying per run and per millisecond
Waiting for the taxi to arrive
Cold start
A taxi already waiting outside
A warm copy that is reused
The company limit of cars on the road
Concurrency limit
The taxi forgets your last trip
Stateless function
Bill for the same day: car vs taxi
Own server, quiet daypaid all day
Serverless, quiet daypaid for a few runs
Own server, very busy daysame bill, may overload
Serverless, very busy dayscales, but the bill grows
Quiet traffic favours pay-per-use. Steady heavy traffic can favour a server you own.

04Why Do We Need It?

🧹No server chores
No operating system updates, no patching, no capacity planning. The provider does that.
📈Scales by itself
From zero to thousands of copies when traffic comes, without you doing anything.
💰Pay for use
Idle time costs nothing. Great for apps with rare or uneven traffic.
🚀Fast to ship
Write a function, connect a trigger, deploy. A small team can launch quickly.
🧩Fits events
Perfect for work that starts from an event: a new file, a payment, a message.
🛡️Built-in availability
The platform runs copies across several data centres, so one failure does not stop you.
Serverless trades control for convenience: you give up the server, and in return you get automatic scaling and a bill that follows real use.

05Where Do We Use It?

🖼️File processing
Resize an image, make a thumbnail or scan a document as soon as it is uploaded.
🌐Web and mobile APIs
A function behind an API gateway handles each request, with a managed database.
⏰Scheduled jobs
A nightly report or clean-up that runs for a minute does not need a server all day.
📬Queue workers
Process messages from a queue, and scale the number of workers with the queue length.
🔗Webhooks
Receive payment or chat callbacks that arrive at unpredictable times.
🤖Glue between services
Small bits of code that connect cloud services, such as react to a database change.

06Types / Parts / How It Works

The main parts of a serverless app

PartWhat it doesExamples
FaaS (functions)Runs your code when triggered, then stopsAWS Lambda, Azure Functions, Google Cloud Functions, Cloudflare Workers
TriggersThe event that starts a functionHTTP, file upload, queue message, database change, timer
API gatewayA front door that turns HTTP requests into function callsAmazon API Gateway, Azure API Management
Managed data storesStorage that is also serverless (scales and bills by use)DynamoDB, S3, Firestore, Aurora Serverless
BaaSReady-made backend featuresFirebase, Auth0, Cognito, Supabase
OrchestrationJoins many functions into one workflow with retriesAWS Step Functions, Azure Durable Functions

Cold start and warm start

Two ways a request can start
Cold start (slow first call)
📥Get code
→↓
⚙️Start runtime
→↓
λRun
Time to first answer100 ms to a few seconds
Warm start (reuse)
♻️Copy already waiting
→↓
λRun
Time to first answerjust your code
Cold Warm
A warm copy is reused for the next request. A cold start downloads code, starts the runtime and runs setup code before your function can answer.

Ways to reduce cold starts

IdeaHow it helpsCost
Keep the function smallLess code to download and loadMore careful packaging
Fast runtimes (Node.js, Go, Python)They start faster than heavy onesLanguage choice may be limited
Provisioned / reserved copiesA number of copies are always readyYou pay for them even when idle
Do set-up outside the handlerConnections and settings are made once and reused on warm callsState must be safe to reuse
Scheduled warm-up pingKeeps a copy aliveHacky, and not reliable for bursts
VisualizerServers vs serverless: the bill, cold starts and the limitPick 'Rare spikes' and compare the bill. Switch to 'Steady' and watch the servers win. Raise the cold start time and shorten the keep-warm time to see slow first users.
How do you run your code?
Traffic over 24 minutes
Requests per second, each column is one minute (amber = cold starts, red = throttled)
Copies you pay for in each minute (only while code runs)
0 min12 min24 min
Your bill
14,580
cost units
Other option
8,640
if always-on servers
Cold starts
39
slow first user: 1000 ms
Dropped
0
requests
39 cold starts: a new copy had to boot, so those first users waited about 1000 ms instead of 200 ms. A longer keep-warm time or provisioned copies would reduce this.

A simplified model with no random numbers. One server runs 4 requests at once and costs 1 unit per second. Serverless costs 3 units per busy second but nothing when idle, and allows 100 copies at once. Real prices differ by provider.

07How to Use It / Steps / Implementation

Building a serverless feature

  1. 1
    Pick the trigger
    Decide what starts the work: an HTTP call, a file, a queue message or a timer.
  2. 2
    Write a small function
    One job per function. Keep it short, quick and easy to test.
  3. 3
    Keep it stateless
    Store data in a database or object storage. Never rely on memory or local files to last.
  4. 4
    Do set-up once
    Create database clients and read settings outside the handler, so warm calls can reuse them.
  5. 5
    Make it safe to run twice
    Triggers are often delivered at least once, so a function may be called again for the same event. Use idempotent writes.
  6. 6
    Set limits
    Set a timeout, a memory size and a maximum concurrency, so one bug or spike cannot eat the budget or flood the database.
  7. 7
    Log and watch
    Send logs and metrics to a central place. Track errors, duration, cold starts and cost.
💡Protect the database
1,000 functions starting at once can open 1,000 database connections. Use a managed proxy (such as RDS Proxy) or a serverless-friendly database, and cap the concurrency.
⚠️Watch for loops
A function that writes a file which triggers the same function again will run forever and create a huge bill. Use different buckets or prefixes, and set budget alarms.

08Key Terms to Know

TermMeaning in easy words
Function (FaaS)A small piece of code that the platform runs when a trigger fires
Trigger / event sourceWhat starts a function: HTTP, file, queue, timer, database change
Cold startThe extra delay when a new copy of the function must be started
Warm startRunning on a copy that is already started and waiting
StatelessKeeps nothing between calls. Anything important is stored elsewhere
Concurrency limitThe most copies of your function that may run at the same time
TimeoutThe longest time one run may take before the platform stops it
BaaSBackend as a Service: ready-made backend features like auth or a database
Scale to zeroWhen nobody uses the app, no copies run and the cost is zero
Vendor lock-inBeing tied to one cloud provider's special features
Provisioned concurrencyCopies kept ready in advance to avoid cold starts, at a fixed price

09Pros, Cons and Trade-offs

✅ Pros
  • No servers to manage or patch
  • Scales automatically, even to zero
  • Pay only when code runs
  • Quick to build and deploy
  • Built-in availability across data centres
⚠️ Cons
  • Cold starts add delay to some requests
  • Time limits make long jobs hard
  • Heavy steady traffic can cost more than servers
  • Harder to test and debug locally
  • Tied to one provider's tools (lock-in)

Trade-offs

ChoiceWe gainWe lose
Serverless instead of serversNo operations work, automatic scalingControl over the machine and runtime
Pay per runA bill that follows real useCost can surprise you under steady or runaway load
Provisioned copiesSteady, low latencyYou pay even when idle, like a server
Many tiny functionsSimple, separate piecesMore wiring, more to monitor
Managed services (BaaS)Less code to write and runLock-in and less flexibility
Scale without limitHandles any spikeCan overload the database behind it

10Common Problems and Mistakes

Common mistakes

  1. Ignoring cold starts. A user-facing API with rare traffic may feel slow on the first call.
  2. Keeping state inside the function. A new copy starts with empty memory, so data is lost.
  3. Overloading the database. Thousands of copies open thousands of connections.
  4. Long jobs in one function. Functions have time limits. Split the work or use a workflow service.
  5. Infinite trigger loops. A function triggers itself and runs up a large bill.
  6. Not handling retries. Events can arrive twice, so a non-idempotent function charges a customer twice.
  7. Assuming serverless is always cheaper. For constant high traffic, a rented server is often cheaper.

Things to watch

🥶Cold start latency
Measure the slowest requests (p99), not just the average.
⛓️Chained functions
Function A calls B calls C. Each cold start and each network hop adds delay.
🔒Lock-in
Triggers and permissions are provider-specific. Keep business logic in plain code.
🔍Debugging
Many short-lived copies make tracing hard. Use request IDs and distributed tracing.

11Real-World Examples

📺Netflix
Has described using AWS Lambda for event-driven tasks such as file checks and encoding workflows.
🏦Coca-Cola vending
Moved a payment flow for vending machines to Lambda and reported big savings in cost.
📰News and media sites
Resize images on upload and handle huge traffic spikes on breaking news.
🔥Firebase apps
Mobile apps use Cloud Functions to react to database changes and send notifications.
🌍Edge functions
Cloudflare Workers and similar run code close to users, for fast redirects and personalisation.
🧾Back-office tasks
Nightly reports, invoice emails and data clean-up that run for a few minutes.
📝Note
Company stories and prices change over time. Check the provider's pricing page and case studies before planning a budget.
Mini case: photo upload
📱User uploads
→↓
🪣Object storagenew file event
→↓trigger
λResize functionstarts on demand
→↓
🗄️Thumbnails + metadata
Nothing runs while nobody uploads. Each upload starts its own function copy.

12Related Topics to Read Next

Microservices→

Serverless is often used to build small, separate services.

Event-Driven Architecture→

Most functions are started by events.

Message Queues→

A common trigger and a way to smooth traffic spikes.

Webhooks→

A good fit for functions, since callbacks arrive at random times.

Idempotency→

Functions can run more than once for the same event.

Connection Pooling→

Many copies can exhaust database connections.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: small functions that the cloud runs on demand. No servers to manage.
  • ✔Pay: per run and per millisecond. Idle costs nothing.
  • ✔Scale: automatic, from zero to thousands, up to a concurrency limit.
  • ✔Triggers: HTTP, file, queue, timer, database change.
  • ✔Cold start: a slow first call while a new copy boots. Warm calls are fast.
  • ✔Rules: stateless, idempotent, short, with a timeout and a concurrency cap.
  • ✔Best for: spiky traffic and event work. Worse for: steady heavy load and long jobs.
  • ✔One line: “Upload a function, let the cloud run it when needed, and pay only for the run.”
← Previous
Microservices
Next →
Event-Driven Architecture