AlgoViz

AWS Lambda

medium 25 min

AWS Lambda runs your function when an event arrives and stops charging when it ends.

A tiny Lambda: cold starts and concurrency

Read it, run it, change a line and run it again.

Loading editor…

A model of environments that runs anywhere. The real service has more moving parts.

The same in TypeScript
import type { APIGatewayProxyHandler, S3Handler, SQSHandler, SQSBatchResponse } from "aws-lambda";import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";// Created once per environment, reused by every warm call.const s3 = new S3Client({});export const hello: APIGatewayProxyHandler = async (event) => {  const name = event.queryStringParameters?.name ?? "World";  return {    statusCode: 200,    headers: { "Content-Type": "application/json" },    body: JSON.stringify({ message: "Hello, " + name + "!" }),  };};export const onUpload: S3Handler = async (event) => {  for (const { s3: source } of event.Records) {    // Object keys arrive URL-encoded.    const Key = decodeURIComponent(source.object.key.replace(/\+/g, " "));    const { Body } = await s3.send(new GetObjectCommand({ Bucket: source.bucket.name, Key }));    const bytes = await Body!.transformToByteArray();    console.log(Key, bytes.length);  }};// Needs ReportBatchItemFailures on the event source mapping.export const onQueue: SQSHandler = async (event): Promise<SQSBatchResponse> => {  const batchItemFailures = [];  for (const record of event.Records) {    try {      await handle(JSON.parse(record.body));    } catch (err) {      console.error(record.messageId, err);      batchItemFailures.push({ itemIdentifier: record.messageId });    }  }  return { batchItemFailures };};async function handle(order: unknown) { console.log(order); }// Lazy: only requests that need the database pay for it. Keep the promise, not the result.interface Connection { query(sql: string): Promise<unknown> }declare function connect(): Promise<Connection>;let db: Promise<Connection> | undefined;export const users = async () => {  db ??= connect().catch((e) => { db = undefined; throw e; });  return (await db).query("SELECT id FROM users LIMIT 20");};
The same in Python
import jsonimport timeimport boto3from botocore.exceptions import ClientErrordynamodb = boto3.resource("dynamodb")        # reused while the environment is warmorders = dynamodb.Table("Orders")def hello(event, context):    params = event.get("queryStringParameters") or {}   # the field can be null    name = params.get("name", "World")    return {"statusCode": 200, "headers": {"Content-Type": "application/json"},            "body": json.dumps({"message": f"Hello, {name}!"})}def on_queue(event, context):    failures = []    for record in event["Records"]:        try:            create_order(json.loads(record["body"]))        except Exception:            failures.append({"itemIdentifier": record["messageId"]})    return {"batchItemFailures": failures}def create_order(body):    """The effect and the idempotency check are one conditional write."""    try:        orders.put_item(            Item={"orderId": body["orderId"], "status": "processing", "at": int(time.time())},            ConditionExpression="attribute_not_exists(orderId)")    except ClientError as e:        if e.response["Error"]["Code"] != "ConditionalCheckFailedException":            raise                             # already done is fine, all else is not
The same in Go
package mainimport (	"context"	"fmt"	"github.com/aws/aws-lambda-go/events"	"github.com/aws/aws-lambda-go/lambda")func handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {	name := req.QueryStringParameters["name"]	if name == "" {		name = "World"	}	return events.APIGatewayProxyResponse{StatusCode: 200, Body: fmt.Sprintf("Hello, %s!", name)}, nil}func main() { lambda.Start(handler) }
The same in Java
import com.amazonaws.services.lambda.runtime.Context;import com.amazonaws.services.lambda.runtime.RequestHandler;import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;import java.util.Map;public class Handler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {    @Override    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {        Map<String, String> params = event.getQueryStringParameters();        String name = params == null ? "World" : params.getOrDefault("name", "World");        return new APIGatewayProxyResponseEvent()            .withStatusCode(200)            .withBody("Hello, " + name + "!");    }}