AWS Lambda in Rust — cargo-lambda, local watch, and LocalStack deploy

Contents

  1. 1. cargo-lambda
  2. 2. Run locally
  3. 3. Build artifact
  4. 4. Deploy

AWS Lambda is a lightweight compute service: pay for what you use and let AWS handle packaging and scaling.

Billing tracks duration and memory, which is where Rust tends to shine—hence all the serverless handlers written in Rust.

Below: cargo-lambda for a Rust handler, local watch, and a LocalStack deploy—you don’t need a real AWS account for the sandbox at the end.

cargo-lambda

cargo-lambda is the usual tool for building Lambda functions (AWS points people at it too).

Install:

1
2
brew tap cargo-lambda/cargo-lambda
brew install cargo-lambda

Scaffold a demo:

1
2
cargo lambda new lambda-demo
> Is this function an HTTP function? Yes

The template pulls in lambda-http and tokio for the runtime.

Handler sketch—a hello-world HTTP response:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use lambda_http::{run, service_fn, tracing, Body, Error, Request, RequestExt, Response};

async fn function_handler(event: Request) -> Result<Response<Body>, Error> {
let who = event
.query_string_parameters_ref()
.and_then(|params| params.first("name"))
.unwrap_or("world");
let message = format!("Hello {who}, this is an AWS Lambda HTTP request");

let resp = Response::builder()
.status(200)
.header("content-type", "text/html")
.body(message.into())
.map_err(Box::new)?;
Ok(resp)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
tracing::init_default_subscriber();

run(service_fn(function_handler)).await
}

Side note: service_fn look familiar? The handler sits on the same Service trait shape as tower—because this stack uses hyper, the usual bedrock for Rust HTTP.

Run locally

During development, watch rebuilds on change and serves invocations locally:

1
2
cargo lambda watch
# INFO invoke server listening on [::]:9000

Invoke from the CLI:

1
cargo lambda invoke lambda-demo --data-ascii "?name=newbmiao"

Build artifact

1
cargo lambda build --release --arm64

Output lands at ./target/lambda/lambda-demo/bootstrap (for a workspace, check the workspace root target tree).

Zip the binary for upload:

1
zip bootstrap.zip bootstrap

Deploy

Deployment is straightforward; the friction is often “I do not have AWS credentials.” LocalStack emulates AWS on your machine.

docker-compose up for LocalStack:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
version: "3.8"

services:
localstack:
container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}"
image: localstack/localstack
ports:
- "127.0.0.1:4566:4566" # LocalStack Gateway
- "127.0.0.1:4510-4559:4510-4559" # external services port range
environment:
# LocalStack configuration: https://docs.localstack.cloud/references/configuration/
- DEBUG=${DEBUG:-0}
volumes:
- "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
- "/var/run/docker.sock:/var/run/docker.sock"

Terraform for the Lambda itself:

1
2
3
4
5
6
7
8
9
10
# build
resource "aws_lambda_function" "lambda_demo" {
filename = "bootstrap.zip"
function_name = "lambda_demo"
role = aws_iam_role.iam_for_lambda_tf.arn
handler = "bootstrap"
source_code_hash = filebase64sha256("bootstrap.zip")
runtime = "provided.al2"
architectures = ["arm64"]
}

IAM plus function URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
resource "aws_lambda_function_url" "lambda_demo_url" {
function_name = aws_lambda_function.lambda_demo.arn
authorization_type = "NONE"
}

output "function_url" {
description = "Function URL."
value = aws_lambda_function_url.lambda_demo_url.function_url
}

resource "aws_iam_role" "iam_for_lambda_tf" {
name = "iam_for_lambda_tf"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}

After terraform apply, grab the URL from outputs, e.g.:

1
2
3
4
5
6
...
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Outputs:

function_url = "http://h6v7ozz6ay3h6apr2hi5edsmnc0wpz80.lambda-url.us-east-1.localhost.localstack.cloud:4566/

End-to-end sample: lambda-demo (build.sh walks through packaging).

Questions? Leave a comment below or email: newbvirgil@gmail.com