Topic lessonTopic: Lambda and API Gateway: inputs, testing and failure investigation
AWS Lambda for beginners: events, functions, permissions and execution limits
AWS Lambda runs code while AWS manages the underlying servers. Its compute options include Event Functions, Web Functions and MicroVMs. This introduction focuses on Event Functions in the default Lambda execution environment: an event invokes a handler, the entry point to your code. Distinguish accepting an invocation from completing the intended data processing.
Distinguish events and handlers, caller permissions and execution roles, invocation modes/retries, and duration/state requirements.
Know IAM callers/actions/resources and S3’s role. No real functions or triggers are created. The example only transforms a fictional reportId into a label; it retrieves or stores no business data.
An event invokes the handler
- Caller → HandlerVerify invocation permissions and event format.
- Handler → Function responseSynchronous invocation waits for the response; asynchronous acceptance is different.
- Caller
- Supplies an event describing the requested work.
- Handler
- Reads input and runs the defined code.
- Function response
- The caller inspects the returned value or error.
| Term | Meaning | This example |
|---|---|---|
| Event | Input supplied to the function | A JSON object containing reportId |
| Handler | Entry point executed by the runtime | Validate the input and return a label |
| Trigger | Configuration connecting an occurrence to invocation | For example, S3 event notifications; none are created here |
| Execution role | AWS-resource permissions used by function code | Review required grants before adding operations such as S3 reads |
Who can invoke and what the function can access are separate
| Question | Caller and resource to inspect | Keep separate |
|---|---|---|
| Who may invoke the function? | Invoking principal, target function, required actions and applicable policies | Attaching an execution role does not allow everyone to invoke |
| What may function code read/update? | Execution role, target AWS resources and applicable controls | Invocation success does not imply S3 read access |
An execution role is an IAM role Lambda assumes for the function. Grant only required access, such as logging or a specific S3 operation. Invocation involves caller policies and applicable function resource-based permissions, with checks depending on method/account boundaries. Resource-side, encryption and networking conditions remain separate checks.
Choose an option to see the result and explanation.
Invocation modes differ in acceptance and retry behavior
| Mode | What the caller observes | Failure-handling checks |
|---|---|---|
| Synchronous | Waits for the function’s response/error | Direct callers handle function errors; also check an integrating service’s retry behavior |
| Asynchronous | Returns event acceptance before processing completes | Acceptance is not completion; inspect retries, event age and failure handling |
| Event source mapping | Lambda polls queues/streams and supplies batches | Review source-specific batch failures, retries and duplicate handling |
Idempotency prevents repeated requests from causing unintended duplicate effects. Event source mappings can process records more than once. An acceptance response alone does not prove that a report was saved; verify function outcomes and the business artifact.
Choose an option to see the result and explanation.
Worked example: validate input and return a label
The following JavaScript example is a pure transformation. It does not read reports from S3, save data, send notifications or transmit logs. It accepts a reportId of 1–40 ASCII letters, digits or hyphens. Real event formats depend on the source; this custom shape is not an S3 or API Gateway event.
export async function handler(event) {
if (!event || typeof event !== 'object' || Array.isArray(event) ||
!Object.hasOwn(event, 'reportId') ||
typeof event.reportId !== 'string' ||
!/^[A-Za-z0-9-]{1,40}$/.test(event.reportId)) {
throw new Error('Invalid reportId');
}
return { reportId: event.reportId, label: 'Report ' + event.reportId };
}| Input | Result | Not performed |
|---|---|---|
| {"reportId":"demo-001"} | Return reportId and “Report demo-001” | Searching, storing or reading a report |
| Repeat the same input | Return identical values without persistence | Verifying deduplication of database updates |
| Missing reportId / array / invalid characters | Reject the input | Implementing production retry destinations or HTTP translation |
Separate return values, logs and HTTP responses
A test event is JSON input for the handler. A console test invokes synchronously; inspect its returned value and log output separately. A return value is data sent to the invoker. A log records processing events. Its contents do not automatically become the returned value or HTTP body.
- Test event → HandlerSupply JSON input
- Handler → Return valueReturn data to the invoker
- Handler → Diagnostic logEmit a separate diagnostic record
- Test event
- A reportId input in a synchronous test.
- Handler
- Validates and processes input; logging is a separate output.
- Return value
- Returns reportId and a label in this example.
- Diagnostic log
- Records a processing step and request correspondence.
| Evidence | Stipulated content | What it establishes |
|---|---|---|
| Input event | {"reportId":"demo-001"} | Input for the handler, with no instruction to store or send a report. |
| Handler return value | {"reportId":"demo-001","label":"Report demo-001"} | A generated label, not evidence of saving a report. |
| Application diagnostic record | Request alias lambda-A / step: label-created / reportId: demo-001 | The separate variant is stipulated to record this processing step; it is not the return value. |
| Runtime record summary | START / END / REPORT for the same lambda-A | Invocation-related records do not automatically establish a business artifact such as a saved report. |
lambda-A is a documentation alias, not an AWS field value. The example concerns documentation account 111122223333, ap-northeast-1, function report-label version 7, around 2026-10-27 00:00:00 UTC. In an investigation, align account, Region, function/version and time window, then correlate invocation identifiers such as Lambda awsRequestId. Nearby times, the same reportId or the same log stream alone do not identify one request.
| Mode / observation | Evidence in this example | Conclusion |
|---|---|---|
| Direct Lambda Invoke / RequestResponse | StatusCode is 200, but FunctionError is present and Payload contains an Invalid reportId error. | 200 alone is not function success; inspect the function-error details. |
| HTTP API → Lambda / payload format 2.0 | A different handler explicitly returns statusCode:200 and a body containing reportId/ready. | Successful transfer produces an HTTP 200. ready is application-defined and does not establish storage or notification completion. |
| Business completion | Separately verify the required artifact or target operation outcome. | Normal function return, HTTP 2xx and completion of the intended business task are different facts. |
For HTTP APIs, do not assume API Gateway requestContext.requestId equals Lambda awsRequestId. Link API-side api-A to Lambda-side lambda-B only when their correspondence is established. Another invocation lambda-C at a similar time is not a substitute. The custom reportId input shown above also does not automatically become a payload format 2.0 HTTP API event.
Choose an option to see the result and explanation.
Review duration, concurrency and state
For the default Event Function execution environment, one invocation has a maximum duration of 900 seconds (15 minutes). Concurrency also has Region/account conditions and quotas. Design duration, waiting, admitted load and downstream capacity together. Do not apply this duration statement wholesale to supported Managed Instances invocation modes or Durable Functions.
Execution environments may be reused, preserving memory or temporary /tmp data, but they are not guaranteed durable storage. Do not retain user-specific data in shared variables/caches or depend on the next invocation reaching the same environment. Manage required state in appropriate storage with suitable access controls.
Review requests, memory, duration and surrounding resources
For default Event Functions, request count, memory configuration and execution duration are cost factors. Review retries, pre-provisioned concurrency, added temporary storage, logs and other services where applicable. Neither an idle interval nor a serverless label proves zero system cost or lower cost than EC2.
- Define the source/event shape and completion criterion.
- Separate invocation permissions, execution role and resource-side controls.
- Choose the invocation mode and define retry, duplicate and failure handling.
- Review duration, concurrency, state, downstream capacity and costs.
- Check repeated and invalid inputs; distinguish code tests from unperformed live AWS verification.
Check, then explain in your own words
- Separate invocation, code execution and business completion.
- Explain permission directions and mode-specific failures.
- State the execution option before assessing duration, state and costs.
Check your understanding: Does successful invocation prove the function accessed its required AWS resources and completed the work?
No. Verify invocation permission, execution-role access, processing results and artifacts separately.
Acceptance or function startup does not prove that storage, notification or another business operation succeeded. Verify outcomes under the defined conditions.
Sources and conditions checked
The official references used in this lesson are collected here with their scope, conditions and corresponding sections. Independent expert review and live AWS comparison have not been performed.
- What is AWS Lambda?Checked:
Scope and conditionsCurrent Event Functions/Web Functions/MicroVMs distinction. Teaching is scoped to default Event Functions, not every compute primitive or extension.
Used in this lessonAn event invokes the handler Review duration, concurrency and state
Scope and conditionsRole assumed by Lambda for code accessing AWS resources, least privilege and separation from invocation permissions.
Used in this lessonAn event invokes the handler Who can invoke and what the function can access are separate Review duration, concurrency and state
Scope and conditionsResource-based invocation permissions and principal/action/resource/conditions; no blanket execution-role grant or policy replacement performed.
Used in this lessonWho can invoke and what the function can access are separate
Scope and conditionsWait for function response; transport/API success alone does not establish a successful business outcome.
Used in this lessonAn event invokes the handler Invocation modes differ in acceptance and retry behavior
Scope and conditionsEvent acceptance/queueing before processing and separate outcome handling; not proof of completed processing.
Used in this lessonInvocation modes differ in acceptance and retry behavior
Scope and conditionsPollers/batching, source-specific failure behavior and at-least-once records. Distinguishes source-owned triggers from mappings.
Used in this lessonAn event invokes the handler Invocation modes differ in acceptance and retry behavior
Scope and conditionsDirect caller handling versus async/source retries and idempotent business effects. No exactly-once guarantee.
Used in this lessonInvocation modes differ in acceptance and retry behavior
- Lambda quotasChecked:
Scope and conditionsDefault Event Function 900-second invocation timeout and account/Region concurrency conditions. Explicitly excludes other Managed Instances/Durable/Web/MicroVM conditions.
Used in this lessonAn event invokes the handler Review duration, concurrency and state
Scope and conditionsDefault environment reuse, cold initialization and transient memory/tmp, with different Managed Instances/Durable lifecycles excluded.
Used in this lessonReview duration, concurrency and state
Scope and conditionsValidate/idempotent input handling, no user-data retention across reused environments, recursion and downstream/cost considerations.
Used in this lessonReview duration, concurrency and state
- AWS Lambda pricingChecked:
Scope and conditionsDefault Event Functions request/memory-duration factors and conditional extras; separate pricing of other compute options. No numeric estimate or always-cheaper claim.
Used in this lessonReview requests, memory, duration and surrounding resources
Scope and conditionsTest events are JSON inputs and console tests invoke synchronously; the lesson uses a fictional custom reportId input without running a console test.
Used in this lessonSeparate return values, logs and HTTP responses
Scope and conditionsLogging requires execution-role permissions and has destination/delivery conditions; missing retrieved logs do not prove non-execution. Associated CloudWatch costs remain separate.
Used in this lessonSeparate return values, logs and HTTP responses
Scope and conditionsDistinguish runtime START/END/REPORT and application output; inspect timestamp/requestId/message and log-level filtering. Do not adopt the sample that dumps environment variables and events.
Used in this lessonSeparate return values, logs and HTTP responses
- Invoke — AWS Lambda APIChecked:
Scope and conditionsRequestResponse API StatusCode 200 does not reflect function errors. Inspect FunctionError/Payload separately from LogResult.
Used in this lessonSeparate return values, logs and HTTP responses
Scope and conditionsawsRequestId identifies a Lambda invocation; functionName/functionVersion/invokedFunctionArn help identify the subject.
Used in this lessonSeparate return values, logs and HTTP responses
Scope and conditionsHTTP API payload format 2.0, explicit statusCode/body response and API requestContext.requestId; distinguish from direct Invoke and custom events.
Used in this lessonSeparate return values, logs and HTTP responses
- Customize HTTP API access logsChecked:
Scope and conditionsGateway request ID, integration request ID, Lambda service status and function status are separate fields; do not assume identifiers across layers are equal.
Used in this lessonSeparate return values, logs and HTTP responses
Scope and conditionsDistinguish intentionally formatted HTTP errors from function exceptions/invalid formats; normal return, HTTP 2xx and business success are not equivalent.
Used in this lessonSeparate return values, logs and HTTP responses