Answer#
HttpServer::new calls its closure once per worker thread. State created inside the closure would therefore exist once per worker, and each worker would count separately. Create it outside and clone the web::Data (a shared pointer) into each one:
use actix_web::{get, test, web, App};
use std::sync::Mutex;
struct Counter { hits: Mutex<u32> }
#[get("/hit")]
async fn hit(data: web::Data<Counter>) -> String {
let mut n = data.hits.lock().unwrap();
*n += 1;
format!("hit {n}")
}
#[actix_web::main]
async fn main() {
// Create the state once, outside the factory closure. HttpServer::new calls the closure once per worker,
// so state created inside it would be one copy per worker.
let data = web::Data::new(Counter { hits: Mutex::new(0) });
let app = test::init_service(App::new().app_data(data.clone()).service(hit)).await;
for _ in 0..2 {
let body = test::call_and_read_body(&app, test::TestRequest::get().uri("/hit").to_request()).await;
println!("{}", String::from_utf8_lossy(&body));
}
println!("seen from outside: {}", data.hits.lock().unwrap());
}hit 1
hit 2
seen from outside: 2- Both requests went through the same counter (
hit 1,hit 2), and the program saw the final value2from outside. - The
Mutexis inside the state becauseweb::Datagives shared, read-only access. test::init_servicebuilds theAppwithout a network port;call_and_read_bodysends aTestRequestand returns the body. The same functions work for status codes and headers (seetest::call_servicein the thread on routes and JSON).
actix-web = "4.21.0"For a real server the sequence is let data = web::Data::new(...); HttpServer::new(move || App::new().app_data(data.clone()) ...).
Common mistakes#
- Creating the state in the closure and wondering why counters differ between requests.
- Holding a
std::sync::Mutexguard across an.awaitin a handler. Finish with the lock before awaiting. - Using the wrong type in the handler:
web::Data<Counter>must match the type given toapp_dataexactly.
Related questions#
Why is the counter behind a Mutex?#
web::Data<T> hands out shared references, so changing the value needs interior mutability such as Mutex, RwLock or an atomic.
Sources#
- actix-web,
web::Data: https://docs.rs/actix-web/4.21.0/actix_web/web/struct.Data.html (read 2026-12-05) - actix-web,
test: https://docs.rs/actix-web/4.21.0/actix_web/test/index.html (read 2026-12-05)