Skip to main content

Application

The App instance and its lifecycle.

Actix 4.9+ 6 min read

# 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).

code_blocksrust
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.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{web, App, HttpResponse, HttpServer};
2
3async fn not_found() -> HttpResponse {
4 HttpResponse::NotFound().body("Oops! Page not found.")
5}
6
7#[actix_web::main]
8async fn main() -> std::io::Result<()> {
9 HttpServer::new(|| {
10 App::new()
11 .route("/", web::get().to(|| async { "Home" }))
12 .default_service(web::route().to(not_found))
13 })
14 .bind("127.0.0.1:8080")?
15 .run()
16 .await
17}
Was this page helpful?