# Lambda: code without servers

Create a function in the console, test it, give it a public function URL and call it with curl, read its logs, and choose memory, timeout, versions and triggers deliberately.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 12. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/12-lambda

## What you will learn

- Create and invoke a Lambda function with a small deployment package.
- Explain triggers, execution roles, versions and aliases.
- Choose memory, timeout and concurrency settings deliberately.
- Compare a Function URL with an API Gateway HTTP API.
- Delete a temporary public endpoint and its execution role safely.

## A function is still a production workload

Before Lambda, a small event handler still needed a server or a worker that stayed running and waiting. A quiet
job used capacity while idle; a sudden burst meant somebody had to add more servers. Lambda runs a function when
an event arrives and charges for requests and execution time instead of an always-running host.

The service starts an execution environment, invokes your handler with an event, and returns the result to its
caller. That does not make the function production-proof: you still choose its role, timeout, retries, logs and
alarms. In this lesson, you'll create one small function, invoke it from the CLI, console and function URL, inspect
its logs, and then delete it.

> **Figure.** Event sources on the left: a function URL or API Gateway for HTTP, an SQS queue, and a schedule from EventBridge. Each event goes to the Lambda service, which starts or reuses an execution environment with your code and runs the handler academy-hello with the event. The function acts with its execution role's permissions, writes its output to CloudWatch Logs, and returns a result to the caller. You pay per request and per millisecond of run time.
>
> An event starts your handler in an execution environment; it acts with its role, logs to CloudWatch and returns a result.

## Package, role and invocation

**Lambda → Functions → Create function:**

> **Figure.** Create function page: (1) Author from scratch selected, (2) function name academy-hello, (3) runtime Node.js 24.x. Permissions: by default Lambda creates an execution role that can upload logs to CloudWatch Logs.
>
> (1) Author from scratch. (2) A name. (3) A runtime. Lambda creates an execution role that can write logs.

The **execution role** is what the code runs as. Lambda assumes it for every invocation, so the function never
holds access keys. The default role can only write logs; add exactly the extra permissions the code needs.

The handler, `index.mjs`:

```js
export const handler = async (event) => {
  const name = event.queryStringParameters?.name ?? event.name ?? 'world';
  console.log(JSON.stringify({ msg: 'greeting', name }));
  return {
    statusCode: 200,
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ message: `Hello, ${name}!`, region: process.env.AWS_REGION }),
  };
};
```

Deploy it from the CLI and invoke it directly:

```sh
$ zip fn.zip index.mjs
$ aws lambda update-function-code --function-name academy-hello --zip-file fileb://fn.zip
$ aws lambda invoke --function-name academy-hello --cli-binary-format raw-in-base64-out \
    --payload '{"name":"Rajeev"}' out.json && cat out.json
{"statusCode":200,"headers":{"content-type":"application/json"},"body":"{\"message\":\"Hello, Rajeev!\",\"region\":\"ap-south-1\"}"}
```

The **Test** tab does the same from the console:

> **Figure.** Test tab of academy-hello: (1) Executing function: succeeded, with a logs link. (2) The response: statusCode 200, content-type application/json, and a body with message Hello, world! and region ap-south-1. Below, the summary with request ID and execution time.
>
> (1) The test invocation succeeded. (2) The full response object the handler returned.

## Function URLs and API Gateway

A **function URL** gives the function its own HTTPS endpoint:

```sh
$ aws lambda create-function-url-config --function-name academy-hello --auth-type NONE
$ aws lambda add-permission --function-name academy-hello --statement-id url-public \
    --action lambda:InvokeFunctionUrl --principal '*' --function-url-auth-type NONE
$ aws lambda add-permission --function-name academy-hello --statement-id url-invoke \
    --action lambda:InvokeFunction --principal '*' --invoked-via-function-url
$ curl -s "https://<url-id>.lambda-url.ap-south-1.on.aws/?name=learner"
{"message":"Hello, learner!","region":"ap-south-1"}
```

Through a URL, Lambda turns the returned object into a real HTTP response: status 200, the header, and only the
`body`. A public URL needs **both** permission statements; with only the first, requests get `403 Forbidden`.

> **Figure.** Configuration tab, Function URL: a notice that the function URL is public and anyone with it can access the function. Function URL https lambda-url endpoint, (1) Auth type NONE, invoke mode BUFFERED, CORS not enabled.
>
> (1) Auth type NONE: public. The console warns that anyone with the URL can call the function.

|          | Function URL                         | API Gateway (HTTP API / REST API)                                          |
| -------- | ------------------------------------ | -------------------------------------------------------------------------- |
| Endpoint | one per function                     | many routes to many functions                                              |
| Auth     | IAM or none                          | IAM, JWT (Cognito, Auth0), Lambda authorizers, API keys                    |
| Extras   | CORS                                 | throttling, usage plans, custom domains, stages, request validation (REST) |
| Use for  | a webhook, a quick internal endpoint | a real public API                                                          |

> **Anonymous is not a production default.** `--auth-type NONE` makes the endpoint public, which is fine for one curl in a lesson. In production use `AWS_IAM`, or put API Gateway with an authorizer in front, and delete public URLs you no longer need.

> **Video.** [74. Function URLs vs API Gateway](https://www.youtube.com/watch?v=R1LG7pY5k8c&t=67s) (AWS Bites)

## Limits, versions and triggers

> **Figure.** Configuration tab, General configuration: (1) memory 128 MB and (2) timeout 3 seconds, ephemeral storage 512 MB, SnapStart none.
>
> (1) Memory, which also sets CPU. (2) Timeout: 3 seconds by default, up to 15 minutes.

| Setting                    | What to know                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------- |
| **Memory** (128 MB–10 GB)  | CPU grows with memory; more memory often makes a function faster _and_ cheaper              |
| **Timeout** (up to 15 min) | bounds one invocation; set it just above the slowest normal run                             |
| **Concurrency**            | how many run at once; reserved concurrency caps a function so it can't overwhelm a database |
| **Cold start**             | the first request on a new environment loads the runtime and your code; keep packages small |

Every invocation logs to CloudWatch Logs under `/aws/lambda/<function>`, ending with a report line that shows the
bill:

```text
REPORT RequestId: 288a1386-efea-40df-92ed-bbdbe736b6f2  Duration: 12.28 ms  Billed Duration: 13 ms  Memory Size: 128 MB  Max Memory Used: 80 MB
```

**Versions** freeze the code and configuration (`$LATEST` is always the editable one). An **alias** such as
`prod` points at a version, so a rollback is moving the alias back. **Layers** share libraries between
functions, and **container image functions** let you ship up to 10 GB as an image from ECR (lesson 11).

**Triggers** turn events into invocations, each with its own retry behaviour:

| Trigger                    | How it calls         | On failure                                                    |
| -------------------------- | -------------------- | ------------------------------------------------------------- |
| API Gateway / function URL | synchronous          | the caller gets the error                                     |
| S3 events                  | asynchronous         | Lambda retries twice, then a dead-letter queue or destination |
| SQS                        | Lambda polls batches | messages return to the queue, then its DLQ (lesson 14)        |
| EventBridge schedule       | asynchronous         | retries, then a DLQ or destination                            |

Retries mean the same event can arrive twice, so make handlers **idempotent**.

> **Production controls.** Least-privilege execution roles, structured JSON logs, alarms on errors and throttles (lesson 13), explicit timeouts on the function and on everything it calls, secrets from Secrets Manager (lesson 15), versions and an alias for rollback, and the whole thing in IaC (lesson 16).

> **Video.** [How to deploy a lambda function using versioning and aliases + API Gateway](https://www.youtube.com/watch?v=OGMaE63YgEU&t=118s) (BiteSize Academy)

## SQS and HTTP API are production-shaped triggers

An SQS event source mapping polls a queue and batches messages into Lambda events. The function must be
idempotent because a message can be delivered again; configure a visibility timeout longer than the function
timeout and use a dead-letter queue for messages that repeatedly fail. An API Gateway HTTP API is the better
front door when you need routes, authorizers, throttling or access logs; a Function URL is the smaller alternative.

Enable X-Ray tracing when you need a request map across Lambda and downstream calls. It adds useful correlation,
not business-level observability, so retain structured logs and metrics too.

```sh
$ aws lambda get-function-configuration --function-name "$FUNCTION" \
  --query '{Runtime:Runtime,Memory:MemorySize,Timeout:Timeout,Tracing:TracingConfig.Mode}' --output table
$ aws lambda list-event-source-mappings --function-name "$FUNCTION" \
  --query 'EventSourceMappings[].{State:State,Source:EventSourceArn,Batch:BatchSize}' --output table
$ aws apigatewayv2 get-apis --query 'Items[].{Name:Name,Protocol:ProtocolType,Endpoint:ApiEndpoint}' --output table
```

Create the queue, API and mapping only for the exercise, record the returned IDs, and delete each by ID before
leaving the account. Never leave a public endpoint or an event source polling a queue after the lesson.

> **Video.** [AWS Lambda : Event Source Mapping with SQS trigger](https://www.youtube.com/watch?v=YDa5O2glHsE) (Saborni Bhattacharya)

## Mission: A public function, called and removed

Create a function from the console or CLI, invoke it directly, give it a public function URL, call that URL with curl, read its log, then delete the URL, the function, its log group and its role.

- You need: An AWS account and the AWS CLI
- You'll have: Hello, learner! from the URL, a REPORT line in the logs, and ResourceNotFoundException after deletion

```sh
$ # Console: Lambda → Create function → academy-hello, Node.js 24.x → Create (it also creates the role)
$ zip fn.zip index.mjs                                   # the handler from this lesson
$ aws lambda update-function-code --function-name academy-hello --zip-file fileb://fn.zip
$ aws lambda wait function-updated --function-name academy-hello
$ URL=$(aws lambda create-function-url-config --function-name academy-hello --auth-type NONE --query FunctionUrl --output text)
$ aws lambda add-permission --function-name academy-hello --statement-id url-public \
    --action lambda:InvokeFunctionUrl --principal '*' --function-url-auth-type NONE
$ aws lambda add-permission --function-name academy-hello --statement-id url-invoke \
    --action lambda:InvokeFunction --principal '*' --invoked-via-function-url
$ curl -s "${URL}?name=learner"
{"message":"Hello, learner!","region":"ap-south-1"}
$ ROLE=$(aws lambda get-function --function-name academy-hello --query Configuration.Role --output text | awk -F/ '{print $NF}')
$ aws lambda delete-function-url-config --function-name academy-hello
$ aws lambda delete-function --function-name academy-hello
$ aws logs delete-log-group --log-group-name /aws/lambda/academy-hello
$ for p in $(aws iam list-attached-role-policies --role-name $ROLE --query 'AttachedPolicies[].PolicyArn' --output text); do
    aws iam detach-role-policy --role-name $ROLE --policy-arn $p; aws iam delete-policy --policy-arn $p; done
$ aws iam delete-role --role-name $ROLE
```

The console-created role comes with its own small logging policy, which is why the loop deletes the policy too.
A few invocations are far inside Lambda's free tier.

## Try it

- Open a function and inspect its runtime, memory, timeout and execution role.
- Invoke the function through its URL and inspect the JSON response.
- Publish a version and explain why an alias helps controlled rollout.
- Find the concurrency and monitoring controls before changing them.
- Remove the temporary function URL and function after the exercise.

## Quiz

1. What does a Lambda execution role provide?
   - **Temporary permissions for the function code** (answer)
   - A public DNS name
   - CPU on an EC2 host
   Why: The execution role is assumed by Lambda and gives code only the AWS API permissions it needs.

2. What is a cold start?
   - **The initialization work before a new execution environment handles an invocation** (answer)
   - A failed DNS lookup
   - A deleted version
   Why: New environments need to initialize the runtime and package before handling work.

3. When is a Function URL a reasonable fit?
   - **A simple endpoint with a small integration surface** (answer)
   - A complex multi-team API contract by default
   - A private database subnet
   Why: Function URLs are simple. Use API Gateway when you need richer routing, authorizers, throttling or API lifecycle controls.

4. Why set a timeout?
   - **To bound work and cost when a dependency stalls** (answer)
   - To make a function multi-region
   - To encrypt the deployment package
   Why: A timeout limits an invocation. It is not a substitute for retries, idempotency or downstream timeouts.

5. What should protect a production function URL?
   - **AWS_IAM or an application authorizer plus least-privilege access** (answer)
   - A secret in the URL path
   - Anonymous access for every endpoint
   Why: The temporary mission uses NONE only to make the request visible. Public production endpoints need authentication and abuse controls.

## Resources

- [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) (AWS Docs)
- [Lambda function URLs](https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html) (AWS Docs)
- [Lambda execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html) (AWS Docs)
- [Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) (AWS Docs)
- [API Gateway HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html) (AWS Docs)
