Building Web Applications with Rust and Rocket
In the world of web development, Rust and Rocket are becoming increasingly popular due to their inherent safety, speed, and concurrency. Let’s explore how we can build a web application using these powerful tools.
Introduction to Rust and Rocket
Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. It’s gaining traction for web development due to its performance and safety features.
Rocket is a web framework for Rust that makes it simple to write fast and reliable web applications without sacrificing flexibility, usability, or type safety.
Setting Up
To start, ensure that you have Rust and Cargo (Rust’s package manager) installed. You can install Rust via rustup
, which you can download from here.
Rocket requires Rust nightly version because it uses several unstable features. You can switch to the nightly version of Rust by running the following command:
rustup default nightly
Creating a New Rocket Project
Next, create a new Rocket project by running:
cargo new rocket_app
cd rocket_app
This will create a new directory called rocket_app
with a basic Rust project.
Next, open the Cargo.toml
file and add Rocket as a dependency:
[dependencies]
rocket = "0.5.0-rc.1"
After saving the Cargo.toml
file, Cargo will fetch the Rocket libraries when you build your project.
Creating a Simple Handler
In a Rocket application, a handler is a function that handles a route. Here’s an example of a simple handler in the src/main.rs
file:
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
This example consists of a single route ("/"
) that maps to the index
handler. When you navigate to the root URL, you will see the text “Hello, world!”.
Running the Application
You can run the application by executing the command cargo run
. Then, open a web browser and navigate to http://localhost:8000
to see your Rocket application in action!
The fastest Rust backend web framework in 2024
We’ll try to find the fastest Rust backend web framework using a simple ‘Hello <uuid>’ case. This is slightly different from the classic ‘Hello World’ with added randomness in each response. We’ll be comparing the following frameworks: Rocket, Actix, Axum, Warp, and Gotham. Let’s get started.
Test setup
All tests are executed on MacBook Pro M2 with 16G RAM & 8+4 cores. The rust version is 1.76.0. The load tester is Bombardier. The application code is as follows:
use axum::{ routing::get, Router, }; use uuid::Uuid; #[tokio::main] async fn main() { let app = Router::new().route("/", get(|| async { "Hello ".to_owned() + &Uuid::new_v4().to_string() })); let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); axum::serve(listener, app).await.unwrap(); }
use gotham::prelude::*; use gotham::router::{build_simple_router, Router}; use gotham::state::State; use uuid::Uuid; pub fn say_hello(state: State) -> (State, String) { (state, "Hello ".to_owned() + &Uuid::new_v4().to_string()) } fn router() -> Router { build_simple_router(|route| { route.get("/").to(say_hello); }) } pub fn main() { let addr = "127.0.0.1:3000"; gotham::start(addr, router()).unwrap(); }
#[macro_use] extern crate rocket; use uuid::Uuid; #[get("/")] fn index() -> String { return "Hello ".to_owned() + &Uuid::new_v4().to_string(); } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![index]) }
use warp::Filter; use uuid::Uuid; #[tokio::main] async fn main() { let routes = warp::path::end().map(|| "Hello ".to_owned() + &Uuid::new_v4().to_string() ); warp::serve(routes) .run(([127, 0, 0, 1], 3000)) .await; }
All the rust apps have been built in release mode.
Results
Each test with 300 concurrent connections is executed for 10M requests. A 1K request warm up is provided before taking readings. The results in chart form are as follows:
Verdict
There is hardly any noticeable difference between the frameworks. However, for RPS, Rocket is the fastest & Actix is the slowest. Rocket’s CPU usage is pretty high, Actix’s CPU usage is the lowest.
Winner: Rocket (ignoring CPU usage)
Vi aspettiamo al prossimo workshop gratuito per parlarne dal vivo insieme a Denny Biasiolli!
Clicca qui per registrarti!
Non perderti, ogni mese, gli approfondimenti sulle ultime novità in campo digital! Se vuoi sapere di più, visita la sezione “Blog“ sulla nostra pagina!