Skip to main content

Your First Server

Running the HttpServer.

Actix 4.9+ 5 min read

# Building Your First Server

To run a web application in Actix Web, you need an HttpServer. The HttpServer is responsible for accepting TCP connections, parsing HTTP requests, and passing them on to your application logic.

##The HttpServer Concept

The HttpServer expects an application factory rather than a single application instance. This is because Actix Web is built around a multi-threaded architecture. By default, the server spins up an operating system thread for each CPU core available on your machine. For each of these worker threads, it calls the factory closure you provide to create a separate instance of your App.

This means that your application state, if any, is not shared between threads by default. This is a very conscious design choice to avoid lock contention and ensure high performance!

code_blocksrust
use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Welcome to the multi-threaded server!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // The closure passed to HttpServer::new is the application factory
    HttpServer::new(|| {
        App::new().route("/", web::get().to(index))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

##Binding to Ports

The .bind() method accepts a socket address. Often this is a tuple like ("127.0.0.1", 8080), meaning it will bind to localhost on port 8080. If you want the server to be accessible from other devices on your network or the internet, you should bind to "0.0.0.1" (or "0.0.0.0" for IPv4).

##Running

The .run() method returns a Server instance which implements Future. You must .await it. When you await it, the server will block the async runtime and continuously process requests until it receives a shutdown signal (like Ctrl+C).

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, HttpServer, Responder};
2
3async fn health_check() -> impl Responder {
4 "OK"
5}
6
7#[actix_web::main]
8async fn main() -> std::io::Result<()> {
9 HttpServer::new(|| {
10 App::new()
11 .route("/health", web::get().to(health_check))
12 })
13 .workers(4) // Explicitly set 4 workers instead of defaulting to CPU count
14 .bind("127.0.0.1:8080")?
15 .run()
16 .await
17}
Was this page helpful?