# Application (App)
The App struct is the core component that manages state, middleware, and routing in Actix Web. While the HttpServer handles the network layer, the App defines how an HTTP request is actually processed.
##App Instances per Worker
As mentioned previously, Actix Web spins up multiple worker threads. For every worker thread, a new instance of your `App` is created. This is a critical concept to grasp!
Because an App is created multiple times, the closure you pass to HttpServer::new(|| App::new() ...) is executed multiple times. If you initialize a database connection inside that closure, you will open multiple connection pools (which is usually a bad idea).
##Shared State vs Thread Local State
To share state (like a database pool) across all workers, you must create it outside the closure and pass a cloned reference inside. Wait, how do you share it safely? By using web::Data, which is internally an Arc (Atomic Reference Counted pointer).
use actix_web::{web, App, HttpServer};
use std::sync::Mutex;
struct AppState {
counter: Mutex<i32>, // Mutex for safe mutation across threads
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Create state outside the factory closure
let data = web::Data::new(AppState {
counter: Mutex::new(0),
});
HttpServer::new(move || {
// Use .app_data() to inject the shared state into the App
App::new()
.app_data(data.clone())
// ... configure routes
})
.bind("127.0.0.1:8080")?
.run()
.await
}##App Configuration
The App instance allows you to configure several aspects of the application:
- .service(): Register routes or scopes.
- .app_data(): Register application state available via extractors.
- .wrap(): Register middleware that applies to all routes in this App.
- .default_service(): Define a fallback handler (e.g., for 404 Not Found pages).
By structuring your App correctly, you ensure a solid foundation for robust request processing.