INFRASTRUCTURE LEARNINGINFRASTRUCTURE LEARNING
インフラ大全インフラ大全IT INFRASTRUCTURE / LEARNING
Infrastructure learning guide
Find a lesson or lab/

Esc to close · Search terms stay on your device

LEARNING日本語

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.

What you will learn

Distinguish events and handlers, caller permissions and execution roles, invocation modes/retries, and duration/state requirements.

Prerequisite

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

Example: synchronously invoking a default Event Function
Example: synchronously invoking a default Event Function1: Caller — Verify invocation permissions and event format. — Handler. 2: Handler — Synchronous invocation waits for the response; asynchronous acceptance is different. — Function response12CallerHandlerFunction responseExample: synchronously invoking a default Event Function1: Caller — Verify invocation permissions and event format. — Handler. 2: Handler — Synchronous invocation waits for the response; asynchronous acceptance is different. — Function response12CallerHandlerFunctionresponse
  1. Caller → HandlerVerify invocation permissions and event format.
  2. 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.
Terms to keep separate
TermMeaningThis example
EventInput supplied to the functionA JSON object containing reportId
HandlerEntry point executed by the runtimeValidate the input and return a label
TriggerConfiguration connecting an occurrence to invocationFor example, S3 event notifications; none are created here
Execution roleAWS-resource permissions used by function codeReview required grants before adding operations such as S3 reads

Who can invoke and what the function can access are separate

Review both permission directions
QuestionCaller and resource to inspectKeep separate
Who may invoke the function?Invoking principal, target function, required actions and applicable policiesAttaching an execution role does not allow everyone to invoke
What may function code read/update?Execution role, target AWS resources and applicable controlsInvocation 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 succeeds, but an S3 read inside the handler is denied. Where should you start?
Read the answer and reason

Answer: The execution role, S3 target and applicable controls · Invocation and AWS access inside the function involve different permission decisions. Establish the caller, action and resource for the failed operation.

Invocation modes differ in acceptance and retry behavior

Do not generalize error handling across invocation modes
ModeWhat the caller observesFailure-handling checks
SynchronousWaits for the function’s response/errorDirect callers handle function errors; also check an integrating service’s retry behavior
AsynchronousReturns event acceptance before processing completesAcceptance is not completion; inspect retries, event age and failure handling
Event source mappingLambda polls queues/streams and supplies batchesReview 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.

An asynchronous invocation was accepted. Can you conclude processing completed?
Read the answer and reason

Answer: No: inspect processing outcomes and artifacts · Asynchronous processing follows acceptance. Failures and retries can occur, so acceptance and business completion are separate outcomes.

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.

Validate the event and return the same label for identical input
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 };
}
What the example checks; these are not live AWS execution results
InputResultNot performed
{"reportId":"demo-001"}Return reportId and “Report demo-001”Searching, storing or reading a report
Repeat the same inputReturn identical values without persistenceVerifying deduplication of database updates
Missing reportId / array / invalid charactersReject the inputImplementing 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.

Follow the input, then separate returned data from records
Follow the input, then separate returned data from records1: Test event — Supply JSON input — Handler. 2: Handler — Return data to the invoker — Return value. 3: Handler — Emit a separate diagnostic record — Diagnostic log123Test eventHandlerReturn valueDiagnostic logFollow the input, then separate returned data from records1: Test event — Supply JSON input — Handler. 2: Handler — Return data to the invoker — Return value. 3: Handler — Emit a separate diagnostic record — Diagnostic log123Test eventHandlerReturn valueDiagnostic log
  1. Test event → HandlerSupply JSON input
  2. Handler → Return valueReturn data to the invoker
  3. 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.
Fixed example: one invocation, different return data and records
EvidenceStipulated contentWhat 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 recordRequest alias lambda-A / step: label-created / reportId: demo-001The separate variant is stipulated to record this processing step; it is not the return value.
Runtime record summarySTART / END / REPORT for the same lambda-AInvocation-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.

Identify which layer a 200 or success statement describes
Mode / observationEvidence in this exampleConclusion
Direct Lambda Invoke / RequestResponseStatusCode 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.0A 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 completionSeparately 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.

The return value contains reportId/label, while diagnostics record a step and request correspondence. How should this difference be read?
Read the answer and reason

Answer: Inspect the response to the input separately from the processing record · The test event is input, the return value is response data, and logs are records. They need not match; this example does not establish a saved report.

A direct synchronous Invoke result has StatusCode:200 and FunctionError. Does it establish function success?
Read the answer and reason

Answer: No; inspect FunctionError and the response payload · The API status alone does not represent function errors. This case supplies FunctionError, so neither function success nor business completion is established.

A separate HTTP example returns 200 and ready. Does that alone prove report storage and notification completed?
Read the answer and reason

Answer: Verify the required storage/notification outcomes separately · An HTTP response and application-defined state do not establish storage or delivery outcomes. This example performs neither operation.

api-A has an established correspondence to lambda-B. Logs for lambda-C also appear nearby. How should you correlate them?
Read the answer and reason

Answer: Use api-A→lambda-B and verify subject, version and time · Gateway and Lambda identifiers have different scopes. Use established correspondence without mixing in another nearby invocation.

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.

  1. Define the source/event shape and completion criterion.
  2. Separate invocation permissions, execution role and resource-side controls.
  3. Choose the invocation mode and define retry, duplicate and failure handling.
  4. Review duration, concurrency, state, downstream capacity and costs.
  5. Check repeated and invalid inputs; distinguish code tests from unperformed live AWS verification.

Check, then explain in your own words

  1. Separate invocation, code execution and business completion.
  2. Explain permission directions and mode-specific failures.
  3. 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.