Serverless architecture
Serverless architecture on AWS: principles, components (Lambda, API Gateway, DynamoDB, S3, EventBridge, SNS, SQS, Step Functions), design patterns, cost/scale formulas, worked exam-style examples, common mistakes and quick-check questions.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Serverless architecture lets engineers build applications without managing servers: you write functions and wire managed services. It is used to build scalable, cost-efficient APIs, event-driven back-ends, and microservices where operational overhead must be low.
Key ideas
Explain terms before use. Use plain English.
Serverless (definition): an architectural style where the cloud provider manages server provisioning, scaling, patching, and capacity, and the developer pays for execution of code and managed services rather than for running servers continuously. Assumption: developer accepts provider-managed limits and shared tenancy.
Function as a Service (FaaS): a category of serverless where you deploy small units of code (functions) that run on demand. On AWS the main FaaS product is AWS Lambda. A Lambda runs a handler function in response to an event and is billed for execution time and memory used and per-request; optional Provisioned Concurrency keeps environments warm and incurs additional compute and initialization charges.
Backend as a Service (BaaS): managed services (databases, auth, storage, messaging) you call from code. Examples: Amazon DynamoDB (NoSQL database), Amazon S3 (object storage), Amazon Cognito (authentication), SNS/SQS (messaging).
Event-driven architecture: components communicate by producing/consuming events (messages). Events can trigger Lambdas via Amazon EventBridge, SNS, SQS, or direct service integrations (S3 PUT event -> Lambda). Also note delivery/ordering semantics: SQS → Lambda is at-least-once with batching and visibility timeouts; Kinesis/DynamoDB Streams process per-shard in order (concurrency 1 per shard by default); configure on-failure destinations or DLQs for async invocations.
Cold start: the extra latency when a FaaS platform initializes a new runtime/container to run a function that was not already warm. Cold start time depends on runtime (e.g., Java, .NET often slower than Node.js/Python), function size, and VPC configuration. In exams, state: cold start increases latency for first invocation of a new execution environment. Mitigations on AWS include Provisioned Concurrency (pre-initializes environments at extra cost) and reducing package size/initialization work.
Concurrency and scaling: serverless scales by creating multiple execution environments. Define concurrent executions as the number of function instances running at the same time. For steady-state arrival rate λ (invocations per second) and average duration d (seconds), expected concurrency is λ·d (assumes Poisson arrivals and average holds). AWS has default account limits; you may configure reserved concurrency to limit how many concurrent instances a function can get.
Stateless functions: Lambdas should be stateless — do not rely on local filesystem or in-memory state to be preserved between invocations. Persist state in services (DynamoDB, S3, ElastiCache). If you must reuse objects (e.g., DB clients) explain that reusing them across warm invocations is possible but not guaranteed. You may use /tmp ephemeral storage (up to 10 GB) during an invocation and it can persist across warm reuses of the same environment, but it is not reliable across instances and must not be treated as durable state.
Idempotency: property of operations where repeating the same operation has the same effect as doing it once. Important because retries and at-least-once delivery happen in serverless systems. Design APIs and functions to be idempotent or use deduplication keys.
Security boundary: define least privilege via IAM roles attached to functions. Principle: give each function the minimum set of permissions to call the services it needs.
Observability: instrument functions with logs (CloudWatch Logs), metrics (CloudWatch Metrics), and tracing (AWS X-Ray) to measure latency, errors, and root cause.
Trade-offs: serverless reduces operational work and can be cost-effective at variable loads, but has limits on runtime duration, memory, and control over environment; cold starts and vendor lock-in are concerns. On AWS Lambda: max timeout 15 minutes; memory 128 MB–10,240 MB; ephemeral /tmp storage configurable up to 10 GB; synchronous invocation payload up to 6 MB (request/response), asynchronous up to 256 KB; API Gateway integration timeout limits are ~29 s (REST) and 30 s (HTTP).
Diagram to draw on exam answers (labelled):
- Draw a browser/mobile client at left. Draw an arrow to an API Gateway box labelled "Amazon API Gateway (REST/HTTP)". From API Gateway draw arrow to a Lambda box labelled "AWS Lambda - handler". From Lambda draw arrows to:
- DynamoDB table (label: NoSQL state)
- S3 bucket (label: static files)
- SNS topic / SQS queue (label: pub/sub or decoupling)
- Step Functions state machine (label: orchestrate long workflows)
- Add EventBridge feeding the Lambda for scheduled/other events.
When asked to draw scaling behavior, sketch the time axis (x) and number of concurrent instances (y). Show spikes in concurrency proportional to traffic bursts; note reserved concurrency caps the peak.
Formulas
List syntax and formulas you should remember.
concurrency ≈ λ · d— λ = arrival rate in invocations per second, d = average duration in seconds. Concurrency is dimensionless (number of concurrent executions). Applies for average steady traffic.GB-seconds = memory_GB × duration_seconds × number_of_requests— memory_GB is memory allocated to the function (GB), duration_seconds is billed duration per request (seconds). Unit: GB·s.compute_cost = GB-seconds × price_per_GB-second— price_per_GB-second: provider billing rate. Unit: currency.request_cost = number_of_requests × price_per_request— price_per_request: provider billing per request.total_cost = compute_cost + request_cost + other_service_costs— add costs for DynamoDB, S3, API Gateway, etc.Lambda handler syntax (must-remember examples):
- Node.js (JS) handler:
exports.handler = async (event, context) => { /* code */ } - Python handler:
def lambda_handler(event, context):then return a response object.
- Node.js (JS) handler:
Minimal AWS SAM function resource (syntax snippet to remember):
Type: AWS::Serverless::FunctionwithHandler: file.handler,Runtime: python3.9,MemorySize,Timeout,Policies.
For concurrency capacity planning:
max_throughput ≈ (reserved_concurrency / d)where reserved_concurrency is number of allowed concurrent instances and d is average duration in seconds; units invocations/s.
Worked examples
Example 1 — Design question (model answer) Question: Design a REST API to manage product records (create, read) using serverless. Include storage and explain components. Answer (step-by-step):
- Use Amazon API Gateway (HTTP API or REST API) as the front door for client requests. It handles HTTPS, routing, and throttling.
- For each API route (POST /products, GET /products/{id}) configure integration with AWS Lambda functions.
- Implement
createProductandgetProductLambda functions. Functions are stateless; persist products in a DynamoDB table namedProductswith primary keyproductId(string). - For file uploads (product images) store in S3. Return pre-signed S3 upload URLs (generated by Lambda) to clients to avoid overloading API Gateway.
- Add IAM roles: Lambda gets permissions
dynamodb:PutItem,dynamodb:GetItem,s3:PutObjectfor the specific resources (least privilege). - For asynchronous events (e.g., send notification after creation) publish to SNS from
createProductor push a message to SQS for workers. - Observability: enable CloudWatch Logs, add X-Ray tracing for Lambdas. Set alarms for error rate.
- Draw the diagram described earlier with components labelled. Full-marks answer explains why each service chosen and mentions statelessness, IAM least privilege, idempotency for create (e.g., client-supplied idempotency key), and scaling behavior.
Example 2 — Cost calculation (numeric, exam style) Question: Estimate monthly Lambda compute cost for 1,000,000 requests per month. Each invocation uses 512 MB memory and runs for 200 ms on average. Ignore free tier and other services. Use price_per_GB-second = X and price_per_request = Y (substitute current AWS prices in exam). Here use placeholders and compute with them. Answer (step-by-step):
- Convert memory to GB: memory_GB = 512 MB = 0.5 GB.
- Duration per request in seconds: d = 200 ms = 0.2 s.
- GB-seconds per request = 0.5 × 0.2 = 0.1 GB·s.
- Total GB-seconds per month = 0.1 × 1,000,000 = 100,000 GB·s.
- Compute cost = 100,000 × X (currency) where X = price per GB-second.
- Request cost = 1,000,000 × Y where Y = price per request.
- Total monthly cost = compute cost + request cost. Final answer must substitute the current price values from AWS; verify X and Y before using in real calculations. Bold the numeric final total after substitution.
Example 3 — Concurrency calculation (algorithmic trace) Question: If traffic is 100 requests/sec and average duration is 250 ms, what concurrency should you expect? If you set reserved concurrency to 20, what happens? Answer:
- λ = 100 req/s, d = 0.25 s. Concurrency ≈ λ·d = 100 × 0.25 = 25 concurrent executions expected.
- If reserved concurrency = 20, then at peak only 20 concurrent executions allowed; up to 5 requests may be throttled or queued depending on integration. The Lambda service will raise TooManyRequests (429) when throttled; with a synchronous API Gateway → Lambda integration, clients will see an error (typically 502) unless you map the response or add retries/backoff.
- To avoid throttling either increase reserved concurrency or add an SQS queue to buffer bursts. Final: expected concurrency 25; with reserved 20 you will throttle about 5 concurrent requests.
Common mistakes
- Not designing for idempotency; failing to handle retry duplicate events.
- Ignoring cold start effects when using heavy runtimes or placing Lambdas in VPC without explaining ENI overhead.
- Miscalculating concurrency by forgetting to convert duration to seconds or to include average, not peak, durations.
- Forgetting to add permissions (IAM) or giving overly-broad IAM policies.
- Using synchronous API Gateway-Lambda integration without considering Lambda timeouts vs API Gateway timeouts.
For your exam
Types of questions:
- Definitions and short notes: explain serverless, FaaS, cold start, idempotency. A full answer defines the term, states assumptions, gives a short example.
- Architecture diagram: draw API Gateway -> Lambda -> DynamoDB/S3, label arrows, explain IAM, security and monitoring. Full marks require diagram plus explanation of each component and trade-offs.
- Derivations: show concurrency ≈ λ·d and explain units. Full marks show derivation from rates and time.
- Numerical problems: cost estimation and concurrency calculation. Show units conversion, substitute numbers, and final answer with units.
- Programs/snippets: write a simple Lambda handler in Python or Node.js and explain event and context objects. Full marks include correct syntax and explanation of event shape.
Quick check
- What is the main billing dimensions for AWS Lambda?
- Why should Lambdas be stateless?
- Formula to estimate expected concurrent executions from arrival rate and duration?
Answers: 1) GB-seconds (memory × duration) and number-of-requests. 2) Because execution environments are ephemeral and not guaranteed to persist between invocations; persistent state must be stored in services like DynamoDB/S3. 3) concurrency ≈ λ · d (arrival rate times average duration).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?