AWS 139: AWS Lambda fundamentals
Why this lesson matters
Run event-driven code in managed execution environments while controlling package, runtime, memory, timeout, ephemeral storage, networking, identity, and lifecycle.
Lambda grew from a 2014 event-driven Function-as-a-Service model into a broader compute family, but the default model remains simple: upload a ZIP or container image, configure a handler and execution settings, and Lambda creates isolated execution environments on demand. You own code, dependencies, configuration, data correctness and permissions; AWS owns the default fleet, host OS, isolation and environment lifecycle.
What you will be able to do
By the end, you can:
- explain aws lambda fundamentals in plain language;
- locate the current service controls in the AWS Management Console;
- run the matching CloudShell or AWS CLI queries and explain every important field;
- draw the identity, network, data, failure, and monitoring path;
- choose the service from requirements and reject it when those requirements are absent;
- diagnose a failed or misleading result from evidence;
- state the cost owner and prove cleanup or a no-create result.
Before you start
- Use a personal AWS account only when its owner has approved the lesson. Do not use the root user for daily work.
- CloudShell is the default command environment. AWS028 explains CloudShell; AWS029 and AWS030 explain local AWS CLI installation and profiles.
- The course example Region is
ap-south-1. Global services and services with a required control Region are called out in their commands. - Run
aws sts get-caller-identityprivately. Redact the account number before sharing evidence. - Never paste access keys, passwords, secret values, private object data, presigned URLs, or full account-specific ARNs into a submission.
- This is a no-create lesson. Every Console action and AWS CLI command is read-only. Create the practical artifact locally.
- Console wording can change. Use the Console service search if a menu label has moved, then confirm the current field in the official documentation.
The core model
| Question | What it means in this lesson |
|---|---|
| Purpose | Run event-driven code in managed execution environments while controlling package, runtime, memory, timeout, ephemeral storage, networking, identity, and lifecycle. |
| Scope and boundary | The learner must identify the account and Region scope, resource boundary, identity path, data or network path, failure behavior, observability, and cleanup ownership for AWS Lambda. |
| Evidence of success | Success means the Console fields, CLI result, workload behavior, monitoring evidence, and architecture claim agree. An available state alone is not enough for AWS Lambda. |
| Cost model | Requests, running capacity, storage, logs, data transfer, retained state, and optional features must be priced for the exact design. |
| Safe rejection rule | Avoid treating a warm environment as durable state or putting long-running, stateful server work into a function by habit. |
How the request flows
+----------------------+
| Event |
+----------------------+
|
v
+--------------------------------+
| Lambda execution environment |
+--------------------------------+
|
v
+--------------------------+
| Dependency or response |
+--------------------------+
|
v
+----------------------------------+
| Logs, metrics, and retry owner |
+----------------------------------+
For AWS Lambda, the important boundary is this: The learner must identify the account and Region scope, resource boundary, identity path, data or network path, failure behavior, observability, and cleanup ownership for AWS Lambda. Success means the Console fields, CLI result, workload behavior, monitoring evidence, and architecture claim agree. An available state alone is not enough for AWS Lambda. That is why the lesson pairs the Console with CLI output and a practical artifact. One interface may hide a field, use a cached view, or be scoped differently. Matching evidence is stronger than a screenshot alone.
Architecture decision table
| Situation | Direction | Reason |
|---|---|---|
| Requirement matches | Use Lambda for short-lived event or request processing that fits service quotas and stateless execution. | Select only after scope, behavior, security, recovery, operations, and price evidence agree. |
| Requirement does not match | Avoid treating a warm environment as durable state or putting long-running, stateful server work into a function by habit. | Rejecting an attractive service is a valid architecture result. |
| No create permission or cost approval | Use supplied evidence and local design work | Learning does not depend on creating an hourly resource. |
| Existing resource is unknown or unowned | Inspect only, then stop | Never change or delete a resource merely because it resembles a course example. |
Default Lambda execution model
An invocation supplies an event and context to a handler inside an execution environment. During Init, Lambda starts extensions/runtime and runs initialization code outside the handler. During Invoke, one default execution environment handles one request at a time. Lambda may freeze and later reuse it, or destroy it without warning. Therefore global variables, open connections and /tmp may be useful caches but are never the only durable copy and must be safe when absent or stale. Each concurrent invocation normally needs an environment.
The function configuration includes architecture, managed/custom runtime, ZIP or OCI image package, handler/image command, memory, timeout, ephemeral /tmp storage, environment variables, layers, execution role, resource policy, VPC attachment, dead-letter/destinations, tracing, logging and encryption settings. Increasing memory also increases available CPU and can reduce duration enough to lower total cost. Tune with representative payloads and percentiles, not intuition. A normal default invocation cannot exceed its current 15-minute limit; split work, use Step Functions, a queue/batch/container, or evaluate current durable-function capabilities when the process must wait or run longer.
Cold-start latency includes environment and function initialization. Keep packages/dependencies bounded, initialize reusable clients outside the handler, and measure Init Duration rather than assuming a language is the only cause. Provisioned concurrency pre-initializes qualified versions/aliases for strict latency at an ongoing charge. SnapStart snapshots initialized state for currently supported runtimes/packages but has compatibility constraints: initialization must not freeze duplicate randomness, credentials or network state, and it cannot simply be combined with every feature. Validate current support before selection.
Packaging, runtime and lifecycle
ZIP packages use a Lambda runtime or custom runtime and may use layers for shared content. Container-image functions use images from ECR and still follow Lambda's runtime API and immutable image digest at deployment; they are not general long-running containers. Runtime major upgrades are customer changes with compatibility testing. Track runtime deprecation notices, dependency CVEs, architecture-specific native libraries and image/base-layer provenance. Publish immutable versions and shift aliases only after functional, load, failure and rollback tests.
Environment variables are configuration, not a preferred secret store. Encrypt sensitive configuration with KMS where appropriate and retrieve/rotate secrets through Secrets Manager or Parameter Store with caching that respects rotation. Never log full input events because they can contain tokens or personal data. /tmp is per environment, encrypted and configurable within current limits; extra ephemeral storage can add cost and remains disposable.
Networking and service boundaries
By default Lambda has outbound access through the service-managed network. Attaching a default function to your VPC enables private-resource access through Lambda-managed Hyperplane ENIs associated with selected subnets/security groups; it does not give a public IP. Internet egress then requires an appropriate route/NAT or service VPC endpoints, with their cost and AZ resilience. Put functions in private subnets across AZs, grant only destination ports, and avoid VPC attachment when no private resource requires it.
Three identities are often confused: the caller needs lambda:InvokeFunction and may also be constrained by the function resource policy; the Lambda service needs permission from event sources/resource policies to invoke; the function code receives temporary credentials from its execution role for downstream calls. The user who deployed the function does not become the runtime identity.
Newer Lambda execution choices
Current Lambda documentation also describes durable functions, which checkpoint code-first workflows, persist history and can wait/resume for long-running executions. They have supported-runtime, versioning, execution-ARN, retention, KMS, replay/determinism and pricing considerations and do not erase the need to compare Step Functions. Lambda Managed Instances run functions on EC2 capacity managed through capacity providers in the customer's account. They use instance-based economics, a multi-concurrency model and different scaling/isolation/operations; code must be thread-safe and functions sharing a capacity provider must be mutually trusted. Treat these as explicit alternatives - not assumptions about the default Lambda model - and confirm Region/runtime/feature availability on the design date.
Observability and correctness
Use structured logs with request/correlation IDs, CloudWatch Invocations, Errors, Duration percentiles, Throttles, ConcurrentExecutions, async age/delivery metrics, event-source lag, destinations/DLQs and X-Ray/traces where justified. An invocation can time out after committing a downstream change, and delivery systems can retry. Make handlers idempotent using a stable event/business key plus conditional durable state; set downstream timeouts shorter than remaining function time; use bounded exponential backoff with jitter; and separate retryable dependency faults from invalid business input.
AWS Management Console, step by step
Sign in with the normal non-root learning identity. Write the expected starting state before opening the service.
- Use the Console service search and open Lambda, Functions; confirm the account and Region before reading the page.
- Inspect the supplied or owned resource's status, configuration, permissions, networking, encryption, monitoring, tags, and dependencies without changing it.
- Open the related metrics, logs, events, or history view and record one timestamped signal that would prove or disprove the expected behavior.
- Return to the resource list, clear filters, and record the final inventory. On the read-only track, do not choose Create, Save, or Delete.
CloudShell and AWS CLI, step by step
Start with a known caller and Region:
export AWS_DEFAULT_REGION="ap-south-1"
aws sts get-caller-identity --query Arn --output text
aws configure list
Redact the account part of the ARN in shared evidence. Now run the topic queries:
aws lambda list-functions --query 'Functions[].{Name:FunctionName,Runtime:Runtime,Memory:MemorySize,Timeout:Timeout,Modified:LastModified}' --output table
aws lambda get-account-settings --output json
Expected interpretation
The list is regional and shows configuration, not a successful invocation, correct result, warm performance, dependency health, or least privilege.
Practical work
Create p07-lambda-runtime-plan.md for an order validator. Define input and output, runtime, package, timeout, memory test, /tmp need, VPC choice, logs, idempotency, failure destination, and cleanup.
Add a numeric load model: average/peak requests per second, duration percentile, expected concurrency (requests/second × average seconds as a starting estimate), burst, payload size, downstream connection ceiling and monthly request/GB-second/log/network costs. Compare default Lambda, provisioned concurrency, durable functions, Managed Instances, Fargate and EC2. Reject at least three with evidence. Design tests for cold/warm start, duplicate event, timeout after downstream commit, malformed input, downstream throttle, exhausted concurrency, secret rotation, missing NAT/endpoint and runtime rollback.
Diagnose this topic from its own evidence
| Symptom | First evidence | Likely boundary and correction |
|---|---|---|
| no invocation | caller error/CloudTrail, resource policy or event-source state | invocation permission, qualifier, trigger/filter - not handler code |
Runtime.ImportModuleError/image error | INIT log, handler path, architecture and image/package manifest | package/runtime/native-library mismatch; rebuild reproducibly |
| timeout | REPORT duration/max memory, trace/downstream timing and remaining-time logs | slow/dead dependency, poor timeout hierarchy or work too large; bound calls and redesign |
| works outside VPC but fails inside | subnet routes, SG, DNS and NAT/VPC endpoints | missing egress/private path; adding a public subnet does not give the function a public IP |
| duplicate order | event ID, retry history and durable idempotency record | at-least-once/redelivery or ambiguous timeout; conditionally claim business operation |
| intermittent high latency | Init Duration, version/alias, package and concurrency metrics | cold starts or spillover; optimize and justify SnapStart/provisioned concurrency |
| throttles | function/account claimed concurrency and source backlog | reserved/unreserved limits or burst/backpressure; protect downstream before raising quota |
| cost spike | invocation count, GB-seconds, memory/duration, provisioned/ephemeral/log/NAT costs | retry loop, over-allocation or retained feature; stop loop and reconcile dimensions |
Cost and cleanup
Requests, running capacity, storage, logs, data transfer, retained state, and optional features must be priced for the exact design.
Knowledge check
- What operational purpose is this lesson solving?
Expected direction: Run event-driven code in managed execution environments while controlling package, runtime, memory, timeout, ephemeral storage, networking, identity, and lifecycle.
- Which scope or ownership boundary must be proved first?
Expected direction: The learner must identify the account and Region scope, resource boundary, identity path, data or network path, failure behavior, observability, and cleanup ownership for AWS Lambda.
- What evidence is strong enough to accept the result?
Expected direction: Success means the Console fields, CLI result, workload behavior, monitoring evidence, and architecture claim agree. An available state alone is not enough for AWS Lambda.
- Which tempting design or shortcut must be rejected?
Expected direction: Avoid treating a warm environment as durable state or putting long-running, stateful server work into a function by habit.
- Which cost dimensions and retained resources need an owner?
Expected direction: Requests, running capacity, storage, logs, data transfer, retained state, and optional features must be priced for the exact design.
Lesson acceptance
Pass when the learner can trace caller, Lambda service, execution role, environment and dependency; explain Init/Invoke/reuse and why state is disposable; select package/runtime/memory/timeout//tmp/VPC settings from measured requirements; and distinguish default Lambda, durable functions and Managed Instances. The artifact must quantify concurrency and cost, implement conceptual idempotency and timeout/retry rules, define logs/metrics/traces, include negative and rollback tests, and reject unsuitable long-running/stateful/server workloads. Fail if warm state is treated as durable, VPC attachment is assumed to provide internet, deployment identity is confused with runtime identity, or a successful invocation is accepted without business-result evidence.