Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

AWS Lambda functions

Clear, exam-focused notes on AWS Lambda: definitions, key concepts (invocations, cold starts, concurrency, roles, layers, timeouts), important CLI/boto3 syntax, worked examples (deploy, invocation flow, cost calc), common mistakes and exam tips.

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

AWS Lambda is a serverless compute service engineers use to run code without managing servers. It helps build event-driven and microservice apps (for example, connect with API Gateway, S3, DynamoDB). Understanding Lambda is essential for cloud-native application design, integrating with API Gateway, Step Functions and IAM, and for cost/performance optimisation.

Key ideas

  • Runtime — the language environment that runs your handler (examples: python3.9, nodejs18.x, java11). Runtime determines how the handler signature looks and which libraries are available. You also choose the CPU architecture (x86_64 or arm64/Graviton).

  • Handler — the entry point in your code that Lambda calls. For Python: module_name.lambda_handler(event, context). Definition: a function object the runtime invokes for each invocation.

  • Execution role (IAM role) — an AWS Identity and Access Management role that Lambda assumes to call other AWS services during function execution. Must be attached when creating the function.

  • Invocation — an event sent to Lambda to execute the handler. Two main types: synchronous invocation (caller waits for response, e.g., API Gateway proxy integration) and asynchronous invocation (Lambda queues the event and returns immediately; retries and dead-letter handling apply). Invoke API payload size limits: up to 6 MB request/response for synchronous (RequestResponse) and up to 256 KB request payload for asynchronous (Event). Asynchronous invocations are retried twice with exponential backoff for up to ~6 hours before failing to a destination or DLQ.

  • Cold start — the additional latency when Lambda creates a new execution environment (container) to run a function for the first time or after scaling to new instances. Caused by runtime startup, code initialisation, and JIT/VM warm-up. For Java workloads, Lambda SnapStart (on supported Java runtimes and on published versions/aliases) can drastically reduce cold start latency by restoring a pre‑initialised snapshot.

  • Warm start — subsequent invocations re-use the same execution environment (container), avoiding cold-start overhead. The execution context (global variables, open connections) remains available between warm invocations until the environment is discarded.

  • Provisioned Concurrency — feature that pre-creates execution environments to eliminate cold starts. It reserves concurrency and incurs charges even when idle.

  • Memory and CPU allocation — you configure memory (128 MB to 10,240 MB) in 1 MB increments; AWS proportionally gives CPU and network to the function. CPU capacity scales roughly linearly with memory allocation; exact CPU share is not published, and additional vCPUs become available at higher memory sizes.

  • Timeout — maximum execution time per invocation (configurable). Lambda stops a function when the timeout is reached and returns an error. Default is 3 seconds; maximum is 900 seconds (15 minutes).

  • Ephemeral storage (/tmp) — local writable storage inside the execution environment. Default size is 512 MB and is configurable up to 10,240 MB; data is lost when the environment is recycled.

  • Concurrency — number of execution environments that can run in parallel for a function. Reserved concurrency both guarantees a minimum and sets a maximum for that function (and prevents others from using that capacity if reserved). There is a per‑Region default account concurrency quota (commonly 1,000) that you can request to increase.

  • Event source — the AWS service or custom source that sends events to Lambda (examples: S3, SNS, SQS, API Gateway, EventBridge, DynamoDB Streams, Kinesis Data Streams). Some sources (synchronous) call Lambda directly; others (polling sources like SQS, DynamoDB Streams, and Kinesis Data Streams) are polled by Lambda's service-managed poller.

  • Destination and Dead-letter queue (DLQ) — for asynchronous invocations, you can configure a destination (SNS, SQS, EventBridge event bus, or another Lambda) for success or failure, or a DLQ (SQS/SNS) to capture failed events after retries (configure either destinations or a DLQ, not both simultaneously).

  • Layers — reusable packages (libraries, native dependencies) that can be attached to functions. A layer is a ZIP archive with a specific directory structure that the runtime merges into the execution environment.

  • Versions and aliases — Lambda supports immutable published versions and mutable aliases that point to versions (useful for blue/green deployments and traffic shifting). Provisioned Concurrency is configured on a version or alias.

Key derivation (throughput vs concurrency):

  • Let C be maximum concurrent executions available to a function and D be average duration in seconds. Maximum sustained invocations per second (R) the function can handle is approximately R = C / D, assuming evenly distributed arrivals and no queueing. Assumptions: invocations are uniform, and each invocation uses full duration D. If invocations burst, Lambda scales quickly up to an initial burst quota (typically 500–3,000 per function per Region) and then increases by ~500 concurrent executions per minute until function/account concurrency limits are reached.

What to draw (for an exam diagram): draw a sequence diagram left-to-right: Caller (API Gateway) -> Lambda Service -> Execution Environment (container) -> Upstream AWS service (e.g., DynamoDB) for a single synchronous request. Label steps: 1) API Gateway requests, 2) Lambda control plane chooses/creates execution environment (cold start if needed), 3) runtime loads handler and code, 4) handler executes and calls dependent services, 5) response returns to API Gateway. Also draw a second parallel path showing queued asynchronous invocation with DLQ on failure.

Formulas

(Syntax and short commands to remember) aws lambda create-function --function-name NAME --runtime RUNTIME --role ROLE_ARN --handler HANDLER --zip-file fileb://function.zip --timeout SECONDS --memory-size MB — NAME: function name; RUNTIME: e.g., python3.9; ROLE_ARN: IAM role Amazon Resource Name; HANDLER: module.handler (Python) or index.handler (Node.js); SECONDS: timeout; MB: memory in megabytes. Unit: n/a. Applies when creating a function with AWS CLI. Note: --zip-file direct upload limit is 50 MB; for larger packages, upload to S3 and use the --code S3Bucket/S3Key parameters.

aws lambda update-function-configuration --function-name NAME --memory-size MB --timeout SECONDS — changes function settings; symbols as above.

boto3.client('lambda').create_function(FunctionName=NAME, Runtime=RUNTIME, Role=ROLE_ARN, Handler=HANDLER, Code={'ZipFile': b'...'}, Timeout=SECONDS, MemorySize=MB) — Python boto3 call; parameters same meaning.

boto3.client('lambda').invoke(FunctionName=NAME, InvocationType='RequestResponse'|'Event', Payload=json_bytes) — InvocationType 'RequestResponse' = synchronous; 'Event' = asynchronous. Symbols: NAME function name, Payload: event bytes.

Cost_GB_seconds = (Memory_MB / 1024) * Total_execution_time_seconds — Memory_MB in megabytes, Total_execution_time_seconds = sum of durations across invocations. Unit: GB·s. Applies for calculating billed compute consumption (before request charges). Duration is billed in 1 ms increments, rounded up per invocation.

Monthly_cost = Cost_GB_seconds * Price_per_GB_second + Number_of_requests * Price_per_request — symbols: Prices are region-specific. Unit: currency (INR/USD). Applies when estimating Lambda monthly cost. Subtract the Lambda free tier where applicable (400,000 GB·s and 1,000,000 requests per month). Include additional charges if using Provisioned Concurrency.

Max_invocations_per_second ≈ Concurrency_limit / Average_duration_seconds — units: invocations·s⁻¹. Assumptions: constant average duration, no queueing or throttling beyond concurrency.

Worked examples

Example 1 — Deploy a simple Python Lambda (CLI) (step-by-step):

  1. Write handler in file handler.py:
    • def lambda_handler(event, context):\n return {'statusCode': 200, 'body': 'Hello'}
  2. Zip code: zip function.zip handler.py.
  3. Create or identify an execution role with trust policy allowing lambda.amazonaws.com and attach a policy with needed permissions (e.g., CloudWatch Logs write). Suppose ROLE_ARN = arn:aws:iam::123456789012:role/myLambdaRole.
  4. Create function (command shown in Formulas). For example: aws lambda create-function --function-name HelloFn --runtime python3.9 --role arn:...:role/myLambdaRole --handler handler.lambda_handler --zip-file fileb://function.zip --timeout 10 --memory-size 128.
  5. Test: aws lambda invoke --function-name HelloFn out.json and check out.json. Expected: JSON with body "Hello". These steps produce a deployed function and show how to test synchronously.

Example 2 — Invocation flow (API Gateway -> Lambda, permissions) (step-by-step trace): Scenario: API Gateway HTTP request -> Lambda (synchronous) -> DynamoDB GetItem -> Return JSON. Trace steps to write in answer:

  1. Client sends HTTP request to API Gateway endpoint.
  2. API Gateway maps request to Lambda invocation and calls Lambda's Invoke API with InvocationType=RequestResponse.
  3. Lambda service checks for available execution environment. If none, it performs a cold start: creates container, initialises runtime, loads code, runs any initialisers outside handler.
  4. Lambda runs handler with event payload. Handler uses AWS SDK (SDK uses credentials from execution role through temporary credentials provided to function) and calls DynamoDB GetItem.
  5. DynamoDB responds; handler returns a JSON object.
  6. Lambda returns response to API Gateway; API Gateway maps and returns HTTP response to the client. Permissions required:
  • API Gateway must have permission to invoke the Lambda function: add permission with aws lambda add-permission --function-name NAME --statement-id ID --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn 'arn:aws:execute-api:region:acct:restapi-id/stage/GET/resource'.
  • Execution role must allow DynamoDB actions.

Example 3 — Cost calculation (numerical): Problem: A function configured with 512 MB memory runs on average 200 ms per invocation. Monthly invocations = 1,000,000. Use Price_per_GB_second = P (region-specific). Also Request price per 1M requests = Q (region-specific). Compute billed GB·s and cost. Steps:

  1. Memory in GB = 512 MB / 1024 = 0.5 GB.
  2. Average duration per invocation = 200 ms = 0.2 s.
  3. GB·s per invocation = 0.5 * 0.2 = 0.1 GB·s.
  4. Total GB·s per month = 0.1 * 1,000,000 = 100,000 GB·s.
  5. Compute cost = 100,000 * P. Request cost = (1,000,000 / 1,000,000) * Q = Q.
  6. Monthly_cost = 100,000 * P + Q. (Plug region prices for P and Q; region prices must be verified.) Final answer expressed symbolically and with substitution when you insert P and Q.

Common mistakes

  • Expecting CPU to be fixed; CPU scales with memory but is not a separately configured resource.
  • Ignoring cold-start latency in latency-sensitive use-cases; not using Provisioned Concurrency when required.
  • Miscalculating cost: forgetting GB·second billing unit and request charges, or using MB instead of GB in formulas.
  • Storing persistent data in /tmp or assuming two different execution environments share /tmp — they do not.
  • Exceeding account concurrency limits by creating many heavy functions without reservation.

For your exam

Question types:

  • Definitions and short notes: define Lambda, cold start, execution role, layers.
  • Diagrams: draw invocation flow (API Gateway -> Lambda -> external service) and label cold vs warm start steps.
  • Short derivations: show how concurrency and average duration limit throughput (derive R = C / D and explain assumptions).
  • Numerical: cost calculations using GB·s and request counts; example worked above shows the exact steps graders expect.
  • Programs / commands: give CLI/Boto3 examples to create, update and invoke functions; include handler code snippet. A full-marks answer includes clear definitions, assumptions, step-by-step derivations, labelled diagrams where required, and precise CLI/boto3 syntax for programming questions.

Quick check

  1. What is a Lambda execution role and why is it required?
  2. How do synchronous and asynchronous invocations differ in retry behaviour?
  3. If a function has 100 reserved concurrency and average duration 0.25 s, what is the approximate maximum sustained invocations per second? Answers: 1) The execution role is an IAM role Lambda assumes to obtain temporary credentials that allow the function to call AWS services (required for any AWS API calls). 2) Synchronous invocation returns the response to the caller and does not queue automatic retries; asynchronous invocation returns immediately and Lambda retries on failure (and can send failed events to DLQ or destinations). 3) 100 / 0.25 = 400 invocations per second.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?