Recommend alternatives to Axum

I'm looking for a simpler alternative to Axum server. The main problems I find with it are:

  1. Too slow to cargo check. I had to split it off my main app, because LLVM lines count was ~8K for each of several binaries, and ~230K for the web server binary (that uses Axum). It was so slow, I had to same a file twice, because from the first save, I didn't see any cargo c, and after two of these, I saw some new updated error messages after a ~minute. It seems that the axum-based server had much more LLVM lines than all the other binaries combined.
  2. Too much magic, poorly documented. E.g. you give it a function and it expects objects to come in a certain way: path object, app state, then form data. There's no doc telling this explicitly, and no source reading can shed light on layers of macros. I just found some discussion on a forum/SO that gave me a hint how to make forms with Axum.

Is there any more straightforward tool?

I need

  1. normal web page
  2. static files
  3. web method with parameters
  4. json in request payload & response body
  5. form with files uploaded
  6. testability (call a method directly from a test code)

I've considered warp for newer projects recently. It looks really nice and simple.


The request body is an asynchronous stream that can only be consumed once. Therefore you can only have one extractor that consumes the request body. axum enforces this by requiring such extractors to be the last argument your handler takes.

~ axum::extract - Rust

Thanks, will try it!

By the way, it's exactly the quote that I saw that time when I had difficulties with forms. Probably someone pointed it to me.

Looks like it was VSCode / the docs of Form :slightly_smiling_face: :

Just made a simple test, a blank project in Axum, with only Axum and Tokio as dependencies, and only one Get method that does nothing. 71K lines of LLVM code, which is like 10 of my average binaries.

use axum::{
    extract::{Path, State},
	http::{HeaderMap, StatusCode}, routing::get, Router as AxumRouter
};


// use utils::{autocli, Res, Timer};

type Res<T> = Result<(), T>;

#[derive(Clone)]
pub struct AppState {}

#[tokio::main]
async fn main() -> Res<()> {
	let host_port = "0.0.0.0:8000";
    
	// let mut t = Timer::new();
	let st2 = AppState {};
    let app = AxumRouter::new()
	
        .route("/route/v1/:coords", get(do_route))
        .with_state(st2);
    
    let listener = tokio::net::TcpListener::bind(host_port).await.unwrap();
	// t.show_total("ready to start").unwrap();
	axum::serve(listener, app).await.unwrap();
	Ok(())
}

async fn do_route(Path((coords)): Path<(String)>, State(ast): State<AppState>) -> Result<(HeaderMap, String), (StatusCode, String)> {
    todo!()
}

Cargo.toml: (the features are for my main project, can't remember exactly what for, but they add cost)

[dependencies]
axum = {version="0.7", features=["multipart"]}
tokio = { version = "1.0", features = ["full"] }
tokio-util = { version = "0.7", features = ["io"] }
€ cargo llvm-lines | head -20

  Lines                Copies              Function name
  -----                ------              -------------
  71667                2513                (TOTAL)
   1138 (1.6%,  1.6%)    16 (0.6%,  0.6%)  std::thread::local::LocalKey<T>::try_with
    787 (1.1%,  2.7%)    19 (0.8%,  1.4%)  <alloc::boxed::Box<T,A> as core::ops::drop::Drop>::drop
    780 (1.1%,  3.8%)     1 (0.0%,  1.4%)  matchit::tree::Node<T>::insert
    738 (1.0%,  4.8%)     3 (0.1%,  1.6%)  hashbrown::raw::RawTable<T,A>::clone_from_impl
    730 (1.0%,  5.8%)     2 (0.1%,  1.6%)  tokio::runtime::scheduler::current_thread::CoreGuard::block_on::{{closure}}
    706 (1.0%,  6.8%)    43 (1.7%,  3.3%)  core::ops::function::FnOnce::call_once
    686 (1.0%,  7.8%)    30 (1.2%,  4.5%)  alloc::boxed::Box<T>::new
    680 (0.9%,  8.7%)    20 (0.8%,  5.3%)  std::panic::catch_unwind
    616 (0.9%,  9.6%)    20 (0.8%,  6.1%)  tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut
    603 (0.8%, 10.4%)     1 (0.0%,  6.2%)  axum::routing::method_routing::MethodRouter<S,E>::call_with_state
    594 (0.8%, 11.2%)     4 (0.2%,  6.3%)  tokio::runtime::task::core::Cell<T,S>::new
    592 (0.8%, 12.1%)     1 (0.0%,  6.4%)  matchit::tree::Node<T>::insert_child
    581 (0.8%, 12.9%)     1 (0.0%,  6.4%)  http::header::name::StandardHeader::as_str
    581 (0.8%, 13.7%)     1 (0.0%,  6.4%)  hyper::proto::h1::dispatch::Dispatcher<D,Bs,I,T>::poll_write
    555 (0.8%, 14.5%)     1 (0.0%,  6.5%)  <axum::serve::Serve<M,S> as core::future::into_future::IntoFuture>::into_future::{{closure}}
    516 (0.7%, 15.2%)     4 (0.2%,  6.6%)  tokio::runtime::scheduler::current_thread::Context::enter
    492 (0.7%, 15.9%)     2 (0.1%,  6.7%)  axum::routing::path_router::PathRouter<S,_>::call_with_state

This looks like many items called a few times, and I suppose most functions are small, in line with clean code ideas.

And out of curiosity, I tested actix-web, the "app state" example. It created 133K LLVM LOC on a blank project! (Even if I commented-out the env_logger lines and didn't include it in Cargo.toml.)

cargo llvm-lines | head -20
   Compiling server2 v0.1.0
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 8.18s
  Lines                 Copies              Function name
  -----                 ------              -------------
  133690                3963                (TOTAL)
    2275 (1.7%,  1.7%)     1 (0.0%,  0.0%)  h2::proto::connection::DynConnection<B>::recv_frame
    2059 (1.5%,  3.2%)     1 (0.0%,  0.1%)  h2::proto::streams::prioritize::Prioritize::pop_frame
    1787 (1.3%,  4.6%)     1 (0.0%,  0.1%)  h2::codec::framed_write::Encoder<B>::buffer
    1605 (1.2%,  5.8%)    23 (0.6%,  0.7%)  std::thread::local::LocalKey<T>::try_with
    1498 (1.1%,  6.9%)     1 (0.0%,  0.7%)  actix_http::h1::dispatcher::InnerDispatcher<T,S,B,X,U>::poll_request
    1384 (1.0%,  7.9%)    44 (1.1%,  1.8%)  tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut
    1361 (1.0%,  9.0%)     1 (0.0%,  1.8%)  <actix_http::h1::dispatcher::Dispatcher<T,S,B,X,U> as core::future::future::Future>::poll
    1360 (1.0%, 10.0%)    40 (1.0%,  2.8%)  std::panic::catch_unwind
    1353 (1.0%, 11.0%)     1 (0.0%,  2.9%)  actix_http::h1::dispatcher::InnerDispatcher<T,S,B,X,U>::poll_response
    1188 (0.9%, 11.9%)     8 (0.2%,  3.1%)  tokio::runtime::task::core::Cell<T,S>::new
    1163 (0.9%, 12.7%)    27 (0.7%,  3.7%)  <alloc::boxed::Box<T,A> as core::ops::drop::Drop>::drop
    1110 (0.8%, 13.6%)     2 (0.1%,  3.8%)  actix_http::h2::dispatcher::handle_response::{{closure}}
    1058 (0.8%, 14.4%)     1 (0.0%,  3.8%)  <h2::server::Handshake<T,B> as core::future::future::Future>::poll
    1016 (0.8%, 15.1%)    45 (1.1%,  4.9%)  alloc::boxed::Box<T>::new
     880 (0.7%, 15.8%)    40 (1.0%,  6.0%)  std::panicking::try::do_catch
     868 (0.6%, 16.4%)     2 (0.1%,  6.0%)  <actix_http::h2::dispatcher::Dispatcher<T,S,B,X,U> as core::future::future::Future>::poll::{{closure}}
     800 (0.6%, 17.0%)     8 (0.2%,  6.2%)  tokio::runtime::task::harness::poll_future

Btw, do you really need the full features from tokio ? My axum projects usually only require the basics, the rt-multithread and macros features.

Hmmm, a most basic example with app state, is also too heavy. I took this project and simplfied as much as possible.

[dependencies]
tokio = { version= "1", features = ["full"] }
warp = "0.3"
use std::{collections::HashMap, convert::Infallible, sync::Arc};
use tokio::sync::Mutex;
use warp::{http::StatusCode, reply::{self, Html, WithStatus}, Filter, Rejection, Reply};

mod handlers;
mod models;

type ItemsDb = Arc<Mutex<HashMap<usize, usize>>>;
type Result<T> = std::result::Result<T, Rejection>;

pub async fn handler(items_db: ItemsDb) -> Result<impl Reply> {
    let mut l = items_db.lock().await;
    
    l.insert(12345, 6790);
    Ok(reply::with_status(
        reply::html("delete success"),
        StatusCode::OK,
    ))
}


fn with_items_db(
    items_db: ItemsDb,
) -> impl Filter<Extract = (ItemsDb,), Error = Infallible> + Clone {
    warp::any().map(move || items_db.clone())
}

#[tokio::main]
async fn main() {
    let items_db: ItemsDb = Arc::new(Mutex::new(HashMap::new()));
    let root = warp::path::end().and(with_items_db(items_db)).and_then(handler);
    
    let routes = root
        .with(warp::cors().allow_any_origin());

    warp::serve(routes).run(([127, 0, 0, 1], 5000)).await;
}

results: 134K LOC of LLVM:

Lines                 Copies              Function name
  -----                 ------              -------------
  134384                3393                (TOTAL)
    2275 (1.7%,  1.7%)     1 (0.0%,  0.0%)  h2::proto::connection::DynConnection<B>::recv_frame
    2256 (1.7%,  3.4%)     4 (0.1%,  0.1%)  hyper::proto::h1::io::WriteBuf<B>::buffer
    2059 (1.5%,  4.9%)     1 (0.0%,  0.2%)  h2::proto::streams::prioritize::Prioritize::pop_frame
    1800 (1.3%,  6.2%)     1 (0.0%,  0.2%)  hyper::proto::h2::server::Serving<T,B>::poll_server
    1787 (1.3%,  7.6%)     1 (0.0%,  0.2%)  h2::codec::framed_write::Encoder<B>::buffer
    1670 (1.2%,  8.8%)     1 (0.0%,  0.3%)  hyper::proto::h2::server::H2Stream<F,B>::poll2
    1628 (1.2%, 10.0%)    23 (0.7%,  0.9%)  std::thread::local::LocalKey<T>::try_with
    1360 (1.0%, 11.0%)    40 (1.2%,  2.1%)  std::panic::catch_unwind
    1232 (0.9%, 12.0%)    40 (1.2%,  3.3%)  tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut
    1188 (0.9%, 12.8%)     8 (0.2%,  3.5%)  tokio::runtime::task::core::Cell<T,S>::new
    1058 (0.8%, 13.6%)     1 (0.0%,  3.6%)  <h2::server::Handshake<T,B> as core::future::future::Future>::poll
    1023 (0.8%, 14.4%)     1 (0.0%,  3.6%)  hyper::proto::h1::dispatch::Dispatcher<D,Bs,I,T>::poll_write
     936 (0.7%, 15.1%)     1 (0.0%,  3.6%)  <hyper::proto::h2::PipeToSendStream<S> as core::future::future::Future>::poll
     880 (0.7%, 15.7%)    40 (1.2%,  4.8%)  std::panicking::try::do_catch
     864 (0.6%, 16.4%)     1 (0.0%,  4.8%)  hyper::proto::h1::io::Buffered<T,B>::parse
     853 (0.6%, 17.0%)     1 (0.0%,  4.9%)  hyper::proto::h1::conn::Conn<I,B,T>::poll_read_body
     827 (0.6%, 17.6%)     1 (0.0%,  4.9%)  hyper::proto::h1::conn::Conn<I,B,T>::require_empty_read

So, in this metric, Axum actually is the lightest server. Hmm. And I can tell from observation that cargo-checking a minimal app with actix and warp took notably longer.

When I remove full feature, I get this:

  --> src/main.rs:28:10
   |
28 | #[tokio::main]
   |          ^^^^ could not find `main` in `tokio`

So, from these tests it seems that Axum isn't that bad.

My problem with compilation times hit hard when I switched developing from CLI prototypes to web app and was adding features.

Writing this, I understood why I had to save twice with a pause of 10-15 seconds: the first time, rust VSCode plugin timed out waiting for cargo-check, and the second time it waited for cargo lock and then there were no changes, and cargo-check would run quickly.

When I used cargo-llvm-lines and saw the web app was ~40 times heavier than any CLI app, I decided to just move it out into another crate. After that, working on either the core, or the web part, became easy, the editor is again responsive enough.

The minimum requirement to use #[tokio::main] is to enable the macros feature. The full feature just enables many other features, so you never have to use full in particular.

You're right. I was meanwhile trying to reduce the number of features and compile warp-based server, and it also requires rt-multi-thread. So I set features = ["macros", "rt-multi-thread"] and ran cargo-llvm-lines, and the result is the same: 134K LOC.

That's unsurprising; if a feature flag only adds items that you are not using (as opposed to adding more behavior or instrumentation to existing items) then it only affects how long the build takes, not the code in the final binary.

Another observation in the collection: tried a stateful example (just the managed queue) from Rocket framework.

I took even fewer code than in the example.

[dependencies]
rocket = "0.5"
flume = "0.10"

mod paste_id;
use rocket::{get, launch, routes, put};
use rocket::State;
use rocket::fairing::AdHoc;
use rocket::http::Status;
struct Tx(flume::Sender<String>);
struct Rx(flume::Receiver<String>);

#[put("/push?<event>")]
fn push(event: String, tx: &State<Tx>) -> Result<(), Status> {
    tx.0.try_send(event).map_err(|_| Status::ServiceUnavailable)
}

#[get("/pop")]
fn pop(rx: &State<Rx>) -> Option<String> {
    rx.0.try_recv().ok()
}

pub fn stage() -> AdHoc {
    AdHoc::on_ignite("Managed Queue", |rocket| async {
        let (tx, rx) = flume::bounded(32);
        rocket.mount("/queue", routes![push, pop])
            .manage(Tx(tx))
            .manage(Rx(rx))
    })
}

#[get("/")]
fn index() -> &'static str {
    "hi"
}

#[launch]
fn rocket() -> _ {
    rocket::build().attach(stage()).mount("/", routes![index])
}

Result: 155K LLVM LOC (the heaviest framework so far).

cargo llvm-lines | head -20
   Compiling server2 v0.1.0
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 9.63s
  Lines                 Copies              Function name
  -----                 ------              -------------
  155060                5348                (TOTAL)
    3060 (2.0%,  2.0%)    90 (1.7%,  1.7%)  std::panic::catch_unwind
    2836 (1.8%,  3.8%)    92 (1.7%,  3.4%)  tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut
    2695 (1.7%,  5.5%)    18 (0.3%,  3.7%)  tokio::runtime::task::core::Cell<T,S>::new
    1980 (1.3%,  6.8%)    90 (1.7%,  5.4%)  std::panicking::try::do_catch
    1800 (1.2%,  8.0%)    18 (0.3%,  5.8%)  tokio::runtime::task::harness::poll_future
    1651 (1.1%,  9.0%)     1 (0.0%,  5.8%)  rocket::server::<impl rocket::rkt::Rocket<rocket::phase::Orbit>>::http_server::{{closure}}
    1570 (1.0%, 10.1%)    22 (0.4%,  6.2%)  std::thread::local::LocalKey<T>::try_with
    1564 (1.0%, 11.1%)    40 (0.7%,  6.9%)  <alloc::boxed::Box<T,A> as core::ops::drop::Drop>::drop
    1539 (1.0%, 12.1%)     5 (0.1%,  7.0%)  rocket::ext::CancellableIo<F,I>::poll_trigger_then
    1321 (0.9%, 12.9%)    92 (1.7%,  8.8%)  core::ops::function::FnOnce::call_once
    1272 (0.8%, 13.7%)    56 (1.0%,  9.8%)  alloc::boxed::Box<T>::new
    1210 (0.8%, 14.5%)    18 (0.3%, 10.1%)  tokio::runtime::task::raw::RawTask::new
    1188 (0.8%, 15.3%)    90 (1.7%, 11.8%)  std::panicking::try::do_call
    1133 (0.7%, 16.0%)     1 (0.0%, 11.8%)  h2::proto::streams::prioritize::Prioritize::pop_frame
    1128 (0.7%, 16.7%)     4 (0.1%, 11.9%)  hyper::proto::h1::io::WriteBuf<B>::buffer
    1123 (0.7%, 17.5%)     1 (0.0%, 11.9%)  hyper::proto::h2::server::Serving<T,B>::poll_server
    1107 (0.7%, 18.2%)     1 (0.0%, 11.9%)  h2::proto::connection::DynConnection<B>::recv_frame

I must note that editing is at ok speed, I don't have to wait, it takes couple of seconds to highlight errors, when I press save. Compiling took ~10 s. But this is just a blank project.

So, my conclusion is that I probably have to live with Axum's magic, which is inconvenient when implementing new features, but once you get it right, you can forget it. Whereas all other frameworks aren't very argonomic -- the builder patterns are still inconvenient -- and take noteably longer to check the code & compile.

cargo check does not perform codegen, the LLVM lines count is unrelated to its performance.

Does your average binary also implement more than a 10th of the features a HTTP web server needs to support though? It seems to me that you're comparing apples to oranges.

LLVM lines does not give you the number of times a function is called, it gives you the number of times a function was instantiated.

Ok. I'll check how fast/slow things work in the other frameworks.

I didn't understand, please explain.

You're complaining that the LLVM lines for a web server are 10x the ones for your "average" binaries, but the comparison doesn't make sense if your average binaries don't have to support the same amount of features.

Most http servers these days get deployed behind some sort of reverse proxy, load balancer or similar. Why should the back end server need to implement a full on HTTP server then? Why not use something simpler? (Am I advocating for a return to fcgi? Maybe?)

Also, a more concrete and actionable suggestion: why should incremental builds be slow? Most of the Http server code really shouldn't change when you are working on routes in your application logic. You should even be able to use the tricks that bevy uses to compile most of it to a dylib.

Correct, but I didn't mean it should be as small. Just took a figure for comparison.

I wonder about that. There are web servers on billions of devices of all kinds. Cameras, routers, TV's, God knows what else.