What is the significance of the 'handler' in AWS Lambda?

Instruction: Describe the purpose and function of the 'handler' in AWS Lambda functions.

Context: This question tests the candidate's knowledge of AWS Lambda's execution model, specifically the role of the handler function as the entry point for Lambda execution.

Updated

Official answer

The handler is the runtime entry point called for an invocation. Its configured name must match the deployed module/function and the selected runtime's signature. Initialization code outside it may run once per execution environment and be reused across invocations.

For Python, save this as app.py and configure app.handler. This example accepts a direct invocation with a JSON object containing a name; it is not an API Gateway proxy-response example:

def handler(event, context):
    if not isinstance(event, dict):
        raise ValueError("Expected an object event")
    name = event.get("name")
    if not isinstance(name, str) or not name.strip():
        raise ValueError("name must be a nonempty string")
    if len(name) > 100:
        raise ValueError("name is too long")
    return {
        "greeting": f"Hello, {name.strip()}",
        "request_id": context.aws_request_id,
    }

The event shape and required response depend on the invoker. Context supplies invocation information such as the request ID and remaining execution time. Return a supported response and await required work in runtimes with asynchronous handlers; do not rely on unfinished background work after completion.

A thrown error is handled according to the invocation source's retry/failure semantics. Returning an HTTP-style status object does not universally mark a non-HTTP invocation as failed. Keep request-specific state isolated even when clients or caches are reused.

Lambda Duration measures event-processing time and excludes cold-start initialization; it is not total producer-to-response latency. Measure initialization, queueing and client latency separately when diagnosing performance.

Python handler contract, execution lifecycle, metrics

Related Questions