Run Actix web, Rocket, Warp on AWS Lambda

API Gateway HTTP API with Amazon Linux 2 custom runtime or Docker container image

lambda-web

Features

Web frameworks

Supported

  • Actix Web 4.0.0-beta.8
  • Rocket 0.5.0-rc.1
  • Warp 0.3.1

AWS infrastructure

Supported

  • API Gateway HTTP API with payload format version 2.0

Not supported

  • API Gateway HTTP API with payload format version 1.0
  • API Gateway REST API
  • Application Load Balancer (ALB)

Example

Actix Web

Cargo.toml

[[bin]]
name = "bootstrap"
path = "src/main.rs"

[dependencies]
lambda-web = { version = "0.1.6", features=["actix4"] }

main.rs

use lambda_web::actix_web::{self, get, App, HttpServer, Responder};
use lambda_web::{is_running_on_lambda, run_actix_on_lambda, LambdaError};

#[get("/")]
async fn hello() -> impl Responder {
    format!("Hello")
}

#[actix_web::main]
async fn main() -> Result<(),LambdaError> {
    let factory = move || {
        App::new().service(hello)
    };

    if is_running_on_lambda() {
        // Run on AWS Lambda
        run_actix_on_lambda(factory).await?;
    } else {
        // Local server
        HttpServer::new(factory)
            .bind("127.0.0.1:8080")?
            .run()
            .await?;
    }
    Ok(())
}

Rocket

Cargo.toml

[[bin]]
name = "bootstrap"
path = "src/main.rs"

[dependencies]
lambda-web = { version = "0.1.6", features=["rocket05"] }
rocket = "0.5.0-rc.1"

main.rs

use rocket::{self, get, routes};
use lambda_web::{is_running_on_lambda, launch_rocket_on_lambda, LambdaError};

#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

#[rocket::main]
async fn main() -> Result<(), LambdaError> {
    let rocket = rocket::build().mount("/", routes![hello]);
    if is_running_on_lambda() {
        // Launch on AWS Lambda
        launch_rocket_on_lambda(rocket).await?;
    } else {
        // Launch local server
        rocket.launch().await?;
    }
    Ok(())
}

Warp

Cargo.toml

[[bin]]
name = "bootstrap"
path = "src/main.rs"

[dependencies]
lambda-web = { version = "0.1.6", features=["warp03"] }
tokio = { version = "1" }

main.rs

use lambda_web::warp::{self, Filter};
use lambda_web::{is_running_on_lambda, run_warp_on_lambda, LambdaError};

#[tokio::main]
async fn main() -> Result<(), LambdaError> {
    // GET /hello/warp => 200 OK with body "Hello, warp!"
    let hello = warp::path!("hello" / String).map(|name| format!("Hello, {}", name));

    if is_running_on_lambda() {
        // Run on AWS Lambda
        run_warp_on_lambda(warp::service(hello)).await?;
    } else {
        // Run local server
        warp::serve(hello).run(([127, 0, 0, 1], 8080)).await;
    }
    Ok(())
}

Create deploy ZIP file

Currentry (Jun 2021), we have two options to run Rust on AWS Lambda: Amazon Linux 2 custom runtime or Docker container image.

I recommend Amazon Linux 2 custom runtime deploy because it's faster cold start time than container image.

To build Amazon Linux 2 compatible binary, it's better to build inside container. First, build Amazon Linux 2 container with Rust toolchain. This repository contains sample Dockerfile .

$ git clone https://github.com/hanabu/lambda-web
...
$ docker build -t lambda_builder lambda-web/docker
...

or
$ buildah bud -t lambda_builder lambda-web/docker
...

Once you get lambda_builder image, then build your code with Amazon Linux.

$ cd your_app_crate_dir
$ docker run -it --rm -v ~/.cargo/registry:/root/.cargo/registry:z -v .:/build:z lambda_builder
...

or
$ podman run -it --rm -v ~/.cargo/registry:/root/.cargo/registry:z -v .:/build:z lambda_builder
...

Then, you get deploy ZIP package in your_app_crate_dir/target_lambda/deploy.zip .

Make sure, your Cargo.toml has bootstrap binary name.

[[bin]]
name = "bootstrap"
path = "src/main.rs"

Setup AWS Lambda & API gateway

Lambda

  • Create lambda function with provided.al2 custom runtime. Choose "Provide your own bootstrap on Amazon Linux 2" .
  • Upload ZIP file described above.
  • IAM role, memory settings, etc. are as your demands.
    As sample code above consumes only 30MB of memory, many simple Rust app can fit in 128MB setting.

API Gateway

  • Create HTTP API
  • Create single route "$default" and attach Lambda integration. Make sure, payload format version is "2.0"
Issues

Collection of the latest Issues

vporton

vporton

0

I deployed on Lambda. I added this Lambda as the backend of an AWS HTTP API. The HTTP API has only $default stage.

https://XXX.execute-api.us-east-1.amazonaws.com/ produces correct result (what my packaged Web server outputs when the root is requested).

But https://XXX.execute-api.us-east-1.amazonaws.com/p/YYY produces: {"message":"Not Found"} what is surely not my Web server's output.

sedrik

sedrik

3

Hi

I get the following error when running a request to an API REST gateway that uses a lambda integration. I could not find a easy way to print the actual request sent from the API gateway so if you know a way please tell me and I can give a better error report.

Error: Error("data did not match any variant of untagged enum LambdaHttpEvent", line: 0, column: 0)

bennichols

bennichols

2

Hi, I'm trying to get the example application working with axum (0.3.4, although I've tried with the latest as well). I'm use CodeBuild using the same buildspec.yml file recommended, and everything seems to be building correctly. I push the build to the lambda and then create the API Gateway HTTP proxy as recommended. When I try to hit the generated endpoint, the response is:

API Gateway Logs:

Interestingly, if I use the Test functionality in the lambda, it seems like the code is flowing correctly:

Any ideas? I think I've followed the instructions well and have only added some logging to the code.

Thanks!

dholroyd

dholroyd

0

Hi!

Just playing around with warp on Lambda. Would love to be able to access event.requestContext.authorizer.jwt.claims.* properties so I can play try JWT authorizers. Tried to work out how to expose this and I suppose it could fit a hyper Request object extension?

mwnDK1402

mwnDK1402

0

I'm getting this error on Windows, trying to build for Lambda in a container:

Seeing a real example repository with a GitHub Action for continuous deployment would help a lot.

Information - Updated Apr 28, 2022

Stars: 6
Forks: 0
Issues: 1

Repositories & Extras

Rust port of my CHIP-8 Emulator (interpreted)

cargo run &lt;path-to-ROM-file&gt;

Rust port of my CHIP-8 Emulator (interpreted)

QEMU support using RustSBI

When running cargo qemu, the test kernel will build and run

QEMU support using RustSBI

hs-probe-firmware

A CMSIS-DAP firmware for cargo-binutils and run:

hs-probe-firmware

Runs embedded programs just like native ones

probe-run is a custom Cargo runner that transparently runs Rust firmware on a

Runs embedded programs just like native ones

Run cargo build to install all dependencies

Run cargo run to play the game

Run cargo build to install all dependencies

Simple Blockchain

cargo run para ejecutar la app, cargo build para crear un ejecutable

Simple Blockchain

Types and traits for http clients

cargo add installed run:

Types and traits for http clients

A game in rust to learn rust and some opengl

Still cargo run to run executable, this main program watches over changes in

A game in rust to learn rust and some opengl

Light weight image library which focus on plotting!

type cargo run --example &lt;example_name&gt; in your terminal to see these example images crafted by our library

Light weight image library which focus on plotting!

little annoy is written in pure Rust

Run cargo run --example demo in your terminal

little annoy is written in pure Rust
Facebook Instagram Twitter GitHub Dribbble
Privacy