How to Use Tower for Composable Network Services in Rust

Tower enables composable network services in Rust by stacking Service and Layer traits to add features like timeouts and logging.

Tower is a library of modular, reusable components for building robust networking clients and servers in Rust by composing Service and Layer traits. You define a core service that handles requests and wrap it with layers to add cross-cutting concerns like logging, timeouts, or retries.

use tower::{ServiceBuilder, service_fn, ServiceExt};
use std::future::Future;
use std::pin::Pin;

// Define a simple service
async fn handle_request(req: String) -> Result<String, std::convert::Infallible> {
    Ok(format!("Handled: {}", req))
}

#[tokio::main]
async fn main() {
    // Build the service by composing layers
    let mut service = ServiceBuilder::new()
        .limit_concurrency(10)
        .timeout(std::time::Duration::from_secs(5))
        .service_fn(handle_request);

    // Execute the service
    let response = service
        .ready()
        .await
        .unwrap()
        .call("Hello Tower")
        .await
        .unwrap();

    println!("Response: {}", response);
}