In this article I'm going to show you how to move a Rust API from Lambda to a container without rewriting a single handler, and which parts to leave on Lambda. We'll do it in seven steps, with code you can adapt.
I build Gitmoap, a code forge I run on my own. Its REST API is 912 operations in Rust. Between February and August 2026 it went from 41 binaries on 41 Lambda functions, to one binary on 199 functions, to one axum server on ECS Fargate. Beside that server, 80 Lambda functions still run everything that isn't a request.
The story of why is in LINK: My API was 199 Lambda functions. Now it's one Rust binary. This one is the how. The code below is a sketch I wrote for this article in Gitmoap's shape, not Gitmoap's own source, for axum 0.8, tower-http 0.6, sqlx and lambda_http 1.x.
The short version, if you are in a hurry
- "Lambdalith or a function per endpoint?" is two decisions: how many things you build, and how many you deploy. Fix them separately.
- Write your handlers as plain axum handlers and your cross-cutting code as layers. Then the same
Routerruns underlambda_http::runoraxum::serve, and the runtime is a line inmain. - Before you leave API Gateway, list what it did for you, size the server and its pools yourself, and keep queues, schedules and Lambda-only callers on Lambda.
Let's get started!
Step 1: separate what you build from what you deploy
Before you change anything, write down where you are on each of the two axes. Here's the grid, with the three places Gitmoap has been:
The build axis decides compile time, artifact size and how many things you upload. The deploy axis decides cold starts, connection pools, in-memory caches, where your middleware lives and how a deploy rolls out.
Gitmoap's first fix, in February, moved only on the build axis: 41 binaries became one, deployed to every function, and requests felt no difference at all. So if your pain is the build, you may not need to move on the other axis.
Step 2: staying on Lambda? One binary, many functions
If you're staying on functions for now, collapse the binaries first. Here's the commit where I did it:
Real output, from Gitmoap's own repository.
The pattern is a dispatch table, resolved once at cold start:
// worker/src/main.rs — one binary, one Lambda function per handler
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use serde_json::Value;
type Handler =
for<'a> fn(&'a Ctx, &'a Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + 'a>>;
/// Every name a function may be deployed with. Tests reconcile this against the deploy list.
pub const HANDLER_NAMES: &[&str] = &["branch_sync", "repo_repack"];
fn dispatch(name: &str) -> Handler {
match name {
"branch_sync" => |ctx, ev| Box::pin(consumers::branch_sync(ctx, ev)),
"repo_repack" => |ctx, ev| Box::pin(consumers::repo_repack(ctx, ev)),
// A misnamed function should fail its cold start, loudly, not answer every event with an error.
_ => panic!("unknown HANDLER_NAME {name:?}"),
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let name = std::env::var("HANDLER_NAME").expect("HANDLER_NAME is required");
let handler = dispatch(&name); // before anything expensive
let ctx = Arc::new(Ctx::new().await?); // once per execution environment, never per event
run(service_fn(move |event: LambdaEvent<Value>| {
let ctx = ctx.clone();
async move {
let out = handler(&ctx, &event.payload).await;
// A Lambda environment is frozen between invocations, so telemetry has to leave
// before this returns. Give it a budget: this flush is on the invocation's clock.
ctx.flush_telemetry(Duration::from_secs(1)).await;
out
}
}))
.await
}
Three habits in there, and the first two come from things that went wrong:
- Resolve the name before building the context. Gitmoap's tick binary does it in that order "so a misnamed function fails its cold start on the name rather than after opening a database pool."
- Build the context once per environment. The same binary's comment says why: a context built per tick "opened a fresh pool whose token refresher kept it alive forever."
- Bound the flush. It runs on the invocation's clock, and a Cognito trigger gets 5 seconds in all. Gitmoap's sign-in triggers get 300 ms and every other worker one second, and an environment that misses its budget skips flushing for a minute.
Then test the deploy list against the dispatch table. With one function per handler, the list of functions you deploy is a second copy of the list of handlers, and copies drift. A handler missing from the deploy list keeps whatever placeholder code your infrastructure created it with:
#[test]
fn every_handler_is_deployed_and_every_deployed_function_has_a_handler() {
use std::collections::BTreeSet;
let deployed: BTreeSet<&str> = include_str!("../../deploy/worker-functions.txt")
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect();
let served: BTreeSet<&str> = HANDLER_NAMES.iter().copied().collect();
assert_eq!(deployed, served, "a handler nobody deploys runs placeholder code forever");
}
I left a consumer off Gitmoap's deploy list three times, and each one ran placeholder code and failed every invocation. Gitmoap now holds its deploy lists equal to each other, and a make target finds a function still on the placeholder. The test above is the one I'd write first.
If your function names differ from your handler names (Gitmoap's Terraform says mr-pipeline-activity where the code says mr_pipeline_activity), put the mapping in the test.
Step 3: write the handlers and the chokepoint as axum code
This is the step that makes everything after it cheap. Gitmoap's February handlers took &lambda_http::Request. That turned out survivable, because lambda_http::Request is the http crate's Request, so in June an axum server could adapt each request into it.
But the adapter had a price. Every handler had to fit one function-pointer type, so none could use axum's extractors, and the route table was rebuilt from the OpenAPI document at every process start. The better shape is the reverse: handlers are axum handlers, and Lambda is the adapter.
// app/src/lib.rs — the library both runtimes share
use std::{sync::Arc, time::Duration};
use axum::{
extract::{DefaultBodyLimit, Path, State},
http::StatusCode,
middleware,
routing::get,
Extension, Json, Router,
};
use tower_http::{catch_panic::CatchPanicLayer, timeout::TimeoutLayer};
pub struct AppState {
pub db: sqlx::PgPool,
}
pub type Shared = Arc<AppState>;
/// The whole API. Both binaries call this; neither adds a route.
pub fn build_router(state: Shared) -> Router {
Router::new()
.route("/repositories/{id}", get(get_repo))
// … every other route
// `route_layer` wraps the routes registered so far, and only matched requests:
.route_layer(middleware::from_fn_with_state(state.clone(), chokepoint))
// Registered after `route_layer`, so the probe skips auth and answers while the DB is down.
.route("/health", get(|| async { StatusCode::OK }))
.layer(CatchPanicLayer::new()) // a panic becomes a 500 (needs panic = "unwind")
.layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_secs(30)))
.layer(DefaultBodyLimit::max(10 * 1024 * 1024)) // axum's silent default is 2 MB
.layer(cors_layer())
.with_state(state)
}
async fn get_repo(
State(state): State<Shared>,
Extension(caller): Extension<Caller>, // put there by the chokepoint
Path(id): Path<uuid::Uuid>,
) -> Result<Json<Repo>, AppError> {
let repo = repos::get(&state.db, &caller, id).await?.ok_or(AppError::NotFound)?;
Ok(Json(repo))
}
The layer order matters, and it reads inside out: each .layer call wraps the ones before it. Gitmoap's own comment on its stack: "The layer order is load-bearing, not stylistic." Here's its stack, from the inside:
Gitmoap's own layer names. Each one wraps everything drawn inside it.
On Lambda it's tempting to do auth in each handler, or in the binary's main loop. Gitmoap had it in the loop, and when the server arrived in June it got a second copy, kept identical by hand. As a route_layer it exists once:
// app/src/chokepoint.rs (a sketch)
use axum::{extract::{MatchedPath, Request, State}, middleware::Next, response::{IntoResponse, Response}};
pub async fn chokepoint(
State(state): State<Shared>,
matched: MatchedPath,
mut req: Request,
next: Next,
) -> Response {
let op = Operation::resolve(req.method(), matched.as_str());
let Some(op) = op else {
// The router matched but your table doesn't know the operation: refuse, never run unguarded.
return AppError::Internal("no route metadata").into_response();
};
let response = match authenticate(&state, req.headers()).await {
Err(refusal) => refusal.into_response(),
Ok(caller) if !caller.scopes.allows(op.scope) => AppError::InsufficientScope.into_response(),
Ok(caller) => {
req.extensions_mut().insert(caller.clone());
next.run(req).await
}
};
// Every exit path, refusals included: a refused request is still a request that happened.
audit(&state, &op, &response).await;
response
}
One trap waits in Operation::resolve. axum 0.8 answers a HEAD from the GET route, and routes a method the path doesn't declare into your layer as well. So let's follow one HEAD:
The last line is the chokepoint's own log message.
Gitmoap's chokepoint answered every HEAD on every routed path with a 500, until a curl -I during a deploy check showed it. So resolve HEAD to its GET operation, answer an undeclared method 405 with an Allow header, and keep the hard 500 for a path your table really doesn't know.
And if a route hands out something expensive before the body is sent (a presigned download, a reserved byte budget), decide what its HEAD means, or refuse it. Gitmoap refuses those with 405.
Step 4: run the same router as a function and as a server
With the router in a library, each runtime is a few lines. As a function, behind API Gateway or a function URL:
// lambda-shell/src/main.rs
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), lambda_http::Error> {
let db = app::pool(app::PoolShape::Function).await?; // once per environment
lambda_http::run(app::build_router(Arc::new(app::AppState { db }))).await
}
lambda_http::run takes any tower Service over HTTP requests, and an axum Router is one. Behind an API Gateway stage, the runtime's axum example also sets AWS_LAMBDA_HTTP_IGNORE_STAGE_IN_PATH=true, so /prod/repositories/… routes as /repositories/…. And if you'd rather run the server binary itself on Lambda, AWS's Lambda Web Adapter does that as an extension, on port 8080 by default.
As a server, on ECS or anywhere:
// server/src/main.rs
use std::{future::IntoFuture, net::SocketAddr, sync::Arc, time::Duration};
use tokio::{net::TcpListener, signal::unix::{signal, SignalKind}, sync::Notify};
/// tokio sizes its pool from `available_parallelism()`, which reads the container's CPU quota.
/// One vCPU or less reads as one thread, and one blocking call then stalls every request.
const MIN_WORKER_THREADS: usize = 2;
/// Below the orchestrator's stop timeout (ECS: `stopTimeout`), so we exit 0 before SIGKILL.
const SHUTDOWN_GRACE: Duration = Duration::from_secs(25);
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.max(MIN_WORKER_THREADS);
tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build()?
.block_on(run())
}
async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let db = app::pool(app::PoolShape::LongRunning).await?;
let router = app::build_router(Arc::new(app::AppState { db }));
let listener = TcpListener::bind(SocketAddr::from(([0, 0, 0, 0], 8080))).await?;
let signalled = Arc::new(Notify::new());
let server = {
let signalled = signalled.clone();
axum::serve(listener, router)
.with_graceful_shutdown(async move {
shutdown_signal().await;
signalled.notify_waiters();
})
.into_future()
};
// Graceful shutdown waits for *every* connection to close, and a load balancer keeps its
// keep-alive connections open. Without a deadline the drain only ends at SIGKILL.
tokio::select! {
res = server => res?,
() = async { signalled.notified().await; tokio::time::sleep(SHUTDOWN_GRACE).await } => {
tracing::warn!("drain exceeded its budget; exiting with connections still open");
}
}
Ok(()) // flush telemetry here, once, rather than per request
}
async fn shutdown_signal() {
let mut term = signal(SignalKind::terminate()).expect("install a SIGTERM handler");
tokio::select! {
_ = term.recv() => {},
_ = tokio::signal::ctrl_c() => {},
}
}
Two numbers in there came from my own mistakes. The first is MIN_WORKER_THREADS. Gitmoap's API first ran on a quarter of a vCPU, and its runtime had one worker thread, because available_parallelism() read the quota as one. A Fargate task at 0.25 vCPU gets about 25 ms of CPU per 100 ms period. Here's what one period looked like:
The 75 ms is the worst case: a burst that spends its 25 ms at once. The 65 ms is one measured call that sets the tenant on a connection.
The hourly CPU average said 6 to 7% while that happened. Now the task has one vCPU and 2 GiB, the runtime has at least two threads, and the cgroup's throttling counters (cpu.stat: periods, throttled periods, throttled time) are exported as metrics. Export them from day one, because an average can't show you a limit that binds every 100 ms.
The second number is the drain. Here's how Gitmoap's shutdown is timed on ECS:
Gitmoap's values. The load balancer's deregistration delay is 5 seconds, not the default 300.
The rest of the container is operations a function never needed. Here's the part of the task definition that matters:
{
"name": "api",
"essential": true,
"stopTimeout": 30,
"linuxParameters": { "initProcessEnabled": true },
"healthCheck": {
"command": ["CMD-SHELL", "curl -fsS http://localhost:8080/health || exit 1"],
"interval": 30, "timeout": 5, "retries": 3, "startPeriod": 15
}
}
-
Signals. With an exec-form
ENTRYPOINT, your binary is PID 1, and the kernel applies no default signal actions to PID 1. Without a handler,SIGTERMdoes nothing.initProcessEnabledadds an init process in front that forwards signals and reaps zombies, which matters if you spawn children. Gitmoap's API runs git. -
Health. A probe outside auth, which answers while the database is down. Gitmoap first registered its probe before the chokepoint, and the chokepoint, finding no route metadata for
/health, refused it with a 500. A health check failing its own health check. - Rollouts. A rolling deployment, with the circuit breaker on and rollback enabled.
-
Two build profiles. The server profile unwinds on panic, so
CatchPanicLayercan turn a handler panic into a 500 instead of killing the process. The Lambda profile keepspanic = "abort",opt-level = "z"andstrip = true, because there a panic ends one invocation and a smaller zip helps the cold start.
Step 5: size the pool for the runtime
This is where the deploy axis costs most, and it's easy to miss, because each environment looks small:
// app/src/pool.rs
use std::time::Duration;
use sqlx::postgres::{PgConnectOptions, PgPool, PgPoolOptions};
pub enum PoolShape {
/// One process serves every request: keep connections warm, and keep them.
LongRunning,
/// One environment serves one request at a time, and there may be hundreds of environments.
Function,
}
pub async fn pool(shape: PoolShape) -> Result<PgPool, sqlx::Error> {
let options = match shape {
PoolShape::LongRunning => PgPoolOptions::new()
.max_connections(10)
.min_connections(3) // a burst after a quiet minute doesn't pay for handshakes
.idle_timeout(None) // keep what you opened
.max_lifetime(Duration::from_secs(6 * 3600)),
PoolShape::Function => PgPoolOptions::new()
.max_connections(3) // multiplied by every warm environment of every function
.min_connections(0),
};
options
.test_before_acquire(false) // ping in `before_acquire` only after a long idle instead
.connect_with(PgConnectOptions::new()) // reads PGHOST, PGUSER, … from the environment
.await
}
Let's do the arithmetic for the function side. Gitmoap's small RDS instance allows about 200 connections. Each process holds two pools (one per database role), and the default ceiling is ten per pool:
At the default ceiling of ten connections per pool.
So Gitmoap's worker functions now cap each pool at three.
On the server side, the numbers that decided it: a fresh connection with TLS and IAM authentication costs 150 to 200 ms, and on sqlx's defaults (no minimum, idle connections closed after ten minutes) a burst of about twenty requests after a quiet minute reopened the pools. Hence the warm floor.
Two more things belong here:
-
A caller with a deadline should connect lazily. Cognito gives a trigger 5 seconds, cold start included. Gitmoap's triggers build their pool with
connect_lazy_with, so a trigger that needs no query never waits for a database. -
If you use IAM database auth, the token is the password and lives 15 minutes, but it's only checked when a connection opens. A long
max_lifetimeis fine. Just refresh the token the pool uses to open new ones.
Step 6: rebuild what the gateway did for you
The day the API stops being functions behind a gateway, all of this becomes yours. Make the list before you cut over:
| API Gateway + Lambda gave you | In the server, you need | Gitmoap's choice |
|---|---|---|
| a function timeout | a request timeout layer | 30 s, 408, raised per route for byte-heavy ones |
| a payload limit (Lambda's is 6 MB each way, synchronous) | a body limit, per route class | 10 MB default; 16 MB for web commits; 512 MB for the package registries; 64 KiB for an anonymous form |
CORS preflight (often a MOCK that says *) |
a CORS layer | allowlist reflected with credentials; * refused outside dev mode |
| per-resource methods | a decision about HEAD and undeclared methods |
HEAD = its GET, metered as zero bytes; undeclared = 405 with Allow
|
| one crashed invocation | panic isolation |
CatchPanicLayer, build profile with panic = "unwind"
|
| a request id | adopt the one the edge sends, echo it | adopt, never mint (minting consumed seeded entropy in tests) |
| TLS, WAF, throttling | an edge | CloudFront with a web ACL, reaching a private load balancer through a VPC origin |
| per-function metrics | per-route metrics you emit yourself | one span, one latency sample and one log line per request |
Two rows deserve a warning. The body limit first: axum's default is 2 MB, applied silently, so a large upload fails as a client error. Every npm, Cargo and PyPI publish to Gitmoap would have failed that way with every test green. The 512 MB registry limit went in with the same change that removed the adapter.
Then the edge. With API Gateway gone, its 29-second integration timeout and 10 MB payload limit went too, which is what lets Gitmoap's registries take a publish bigger than 10 MB. Gitmoap holds its limits to each other at compile time, which costs four lines:
const _: () = {
assert!(REGISTRY_BODY_LIMIT > BODY_LIMIT);
assert!(BODY_LIMIT > 2 * 1024 * 1024); // otherwise it's axum's default wearing a name
};
Step 7: keep the workers on Lambda
Moving the API doesn't mean moving everything. Gitmoap's 80 remaining functions are five binaries, one per event source. Here they are, counted from the deploy lists:
Real output, 28 November 2026.
And here's why each family stays a function:
| Family | Functions | Why it stays a function |
|---|---|---|
SQS consumers (sqs-worker) |
52 | The event source mapping polls, batches, retries and dead-letters for free; jobs range from 256 MB to 3 GB and from seconds to 15 minutes; 18 of them mount EFS |
Scheduled ticks (pipeline-worker) |
16 | Scheduler targets Lambda directly; nothing runs between ticks |
Git over WebSocket (git-websocket) |
7 | API Gateway's WebSocket routes integrate with Lambda; push and fetch need 3 GB and minutes |
| Cognito triggers | 4 | Cognito only invokes Lambda, with a 5-second budget |
| Release uploads | 1 | an S3 notification, through SQS |
For SQS consumers, turn on ReportBatchItemFailures on the event source mapping, and return {"batchItemFailures": [{"itemIdentifier": "<messageId>"}]} for the records that failed, so one bad record doesn't redeliver the whole batch. Gitmoap builds that response with aws_lambda_events::sqs::SqsBatchResponse rather than by hand, so the field names are the SDK's problem.
To decide which side a new piece of work goes on, ask one question:
And know what the split costs you:
- Two deploy units can disagree. Gitmoap's workers once ran a build from before a feature its API already served, and a push of mine registered nothing. Stamp both with the build they run, and compare.
-
Account concurrency is shared. A new AWS account started at a Lambda concurrency limit of 10. One
git pushfanned out to consumers that took all ten, and the next push's WebSocket$connectwas throttled into an HTTP 500 that no log explained. Runaws lambda get-account-settingson day one. - Per-function configuration drifts. Gitmoap's one function that built its own IAM role and environment block missed the PostgreSQL cutover. Give every function the shared role and the shared environment.
What it costs
-
Every gateway feature in step 6 becomes code you own, and one of mine (
HEAD) failed before I found it. - The server needs sizing, and its averages lie. Mine ran on a quarter of a vCPU while its dashboard said 6 to 7% busy.
- Telemetry needs two shapes: cumulative export in the background for the server, and a delta with a bounded flush at the end of every invocation for the functions.
- Per-route IAM is yours to write. AWS lists "Hard to enforce least privilege" among the drawbacks of one function for everything, and it's right in principle. But my 199 functions each had their own IAM role, and every role carried the same policy. You only get least privilege per function by writing a policy per function.
- AWS is moving. Lambda Managed Instances lets one environment serve several invocations at once, and Lambda Web Functions runs an HTTP server with concurrent requests per environment. As of 20 November 2026, AWS's docs say Web Functions "currently support Node.js runtimes only", so not a Rust server yet.
What it bought: one set of database connections instead of one per environment, one chokepoint instead of two, in-memory caches that see every request (a polled merge check went from six git processes to two rev-parses and two lookups), an MCP server that calls the REST router in process, and a deploy that is one image rolling out.
What I'd copy if I were you
If you only take one thing from this article, take this one:
Write your handlers so they don't know where they run. Then Lambda or a container is one line in
main, and you can change your mind later.
And then, in order of value:
-
Put the router in a library, with the chokepoint as a
route_layerand the probe registered after it. -
Resolve
HEADand undeclared methods on purpose. Then runcurl -Iagainst every kind of route. - Set a body limit per route class, and assert at compile time that it's above axum's 2 MB.
- Give tokio a floor of two threads, and export the cgroup's throttling counters.
- Bound the drain below the stop timeout, and shorten the load balancer's deregistration delay.
- Size pools per runtime: a warm floor in the server, a cap of a few per Lambda environment.
- Test the deploy list against the dispatch table for every worker binary you keep.
An invite to you
Gitmoap is a code forge: git hosting, code review, work items whose Definition of Done is checked by tests, pipelines as code, package registries, and an MCP server for agents. Everything in this article runs it. It's free and I run it alone. Your code is stored in AWS Ireland and isn't used to train generative AI models.
Two gaps: clone and push go through Gitmoap's own git helper for now (no HTTPS or SSH yet), and there's no importer yet.
And you can try the result today! All 912 operations that one router serves are in the API reference, with a sandbox.
- API reference and sandbox: https://developers.gitmoap.com
- Try it: https://gitmoap.com
If you've done this migration the other way, from a server to functions, and it went well, I'd love to hear what made it work.
Questions, ideas, criticism: all welcome, in the comments below.
Cheers!
Kevin









Top comments (0)