Fit for BFF layers
Learn how Axum fits the Backend for Frontend pattern with aggregation, transformation, and tailored APIs for different client types
A Backend for Frontend, or BFF, is a server that sits between your frontend application and your other backend services. Instead of having a mobile app talk directly to ten different microservices, the app talks to one BFF. The BFF then talks to those ten services, combines the results, and sends back only what that specific frontend needs.
This page explains why BFF layers exist, what problems they solve, and why Axum is a natural fit for building them. You will see complete examples of BFF routes that aggregate data, transform responses, and handle failures. Everything starts from the absolute basics.
What a BFF Layer Does
Imagine a weather app on your phone. The home screen needs three pieces of information: the current temperature, a five-day forecast, and air quality data. In a system with separate microservices, those three pieces might come from three different services, each with its own URL, authentication, and response shape.
If the phone app had to call all three services directly, it would need to:
- Know three different base URLs
- Handle three separate authentication tokens or API keys
- Parse three different JSON structures
- Wait for three network round trips, because the app may not be able to fire all requests in parallel on a constrained mobile network
- Deal with three different error formats
That is a lot of complexity for a small screen. A BFF removes that complexity. The phone app makes one request to the BFF, something like GET /home. The BFF then calls the temperature service, the forecast service, and the air quality service, combines the results into one JSON object, and returns that object to the phone.
The BFF is allowed to be opinionated. It can rename fields, drop fields the phone does not need, combine multiple calls into one, and convert errors into a single consistent format. Each frontend can have its own BFF if the needs differ. A mobile BFF might return compact JSON with short field names. A web BFF for the same product might return a larger object with extra fields for a desktop browser.
This pattern became popular as microservice architectures grew. The frontend does not care that the user profile lives in one service and the order history lives in another. It just needs a clean UserProfile object. The BFF is the translator and aggregator that makes that happen.
Why Axum Fits This Pattern
Axum is an HTTP routing and request-handling library for Rust. It does not force you into a single monolithic architecture. Instead, it gives you small, composable pieces that you can arrange however you need. That flexibility matters a lot for BFF work.
First, Axum handlers are ordinary async Rust functions. That means you can call other async services inside a handler, wait for them, and combine their results. There is no special framework thread or callback system. You write let user = fetch_user().await; and it just works.
Second, Axum uses extractors to parse incoming requests in a type-safe way. A BFF often receives query parameters, path segments, JSON bodies, and headers. With Axum, you declare what you need as function arguments, and the framework gives you exactly those values. If you ask for a path parameter as a u32 and the client sends text, the request is rejected before your handler runs.
Third, Axum integrates with the Tower middleware ecosystem. BFFs often need authentication, rate limiting, request tracing, and timeouts. You can add those as layers around your router without changing your handler code. This is especially useful when different frontends need different security rules. A public mobile BFF route might allow unauthenticated access, while a desktop BFF route requires an API key. You can apply middleware per route or per router.
Fourth, Axum's Router type supports nesting and merging. You can build small routers for each frontend concern, then combine them into one top-level router. That keeps the BFF code organized as it grows.
There is no special BFF feature inside Axum. Axum is a general-purpose web framework. But its design choices, particularly async handlers, extractors, and Tower middleware, align very well with what BFF layers need.
A First BFF Example Without External Services
Let's start with the simplest possible BFF. We will create an Axum server that exposes one route, /summary. When a client calls that route, the handler will call two mock functions that pretend to be upstream services, then combine their results.
We will not use any real HTTP client for this first example. The two mock functions will just return hard-coded data after a short delay. That keeps the example focused on the BFF logic itself.
Create a new Rust project and add the dependencies:
cargo new bff-example
cd bff-example
cargo add axum@0.8
cargo add tokio@1 --features full
cargo add serde -F derive
cargo add serde_json
Now replace src/main.rs with the following code.
use axum::{
routing::get,
Router,
Json,
};
use serde::Serialize;
use std::time::Duration;
// This struct represents the combined response we send back to the frontend.
#[derive(Serialize)]
struct Summary {
user_name: String,
active_orders: u32,
}
// Pretend this function calls a user profile service.
async fn fetch_user_name() -> String {
tokio::time::sleep(Duration::from_millis(50)).await;
"alice".to_string()
}
// Pretend this function calls an order service.
async fn fetch_active_orders() -> u32 {
tokio::time::sleep(Duration::from_millis(80)).await;
7
}
async fn summary_handler() -> Json<Summary> {
// We can run both upstream calls at the same time because they are async.
let (user_name, active_orders) = tokio::join!(
fetch_user_name(),
fetch_active_orders()
);
Json(Summary {
user_name,
active_orders,
})
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/summary", get(summary_handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("BFF listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server with cargo run and then open http://localhost:3000/summary in a browser. You should see:
{"user_name":"alice","active_orders":7}
What did this code do? The summary_handler is an async function that does two things at once. The tokio::join! macro runs both fetch_user_name and fetch_active_orders concurrently, so the total time is roughly the slower of the two, not the sum. That is a key advantage of an async BFF. If we called them one after the other, each sleep would add up. With join!, we only wait for the longest one.
The handler returns Json<Summary>. Axum automatically serializes the Summary struct to JSON because we derived Serialize. The frontend never knows that the user name came from one service and the order count came from another. It sees one clean object.
Correct asynchronous behavior:
If you run this example and see the combined JSON, your BFF is working correctly. The important detail is that both upstream calls happen concurrently. If you accidentally write let user_name = fetch_user_name().await; let active_orders = fetch_active_orders().await;, the requests will still work, but they will take longer because they run one after the other.
Adding a Real Upstream HTTP Client
Mock functions are fine for learning, but a real BFF must talk to actual HTTP services. The most common way to do that in Rust is with the reqwest crate. Axum does not include an HTTP client, but it works perfectly alongside one.
Add reqwest to your project:
cargo add reqwest -F json
We also need to store the HTTP client somewhere that all handlers can access. Axum's State extractor is the natural fit. We create one reqwest::Client, wrap it in an Arc so it can be shared cheaply, and pass it to the router with with_state.
Here is a complete example that fetches a user and their posts from two fictional services. The services are still mocked, but this time we use actual HTTP requests to local mock endpoints. To keep the example self-contained, we will create two tiny Axum servers inside the same main function, but in a real system those would be separate processes.
Replace src/main.rs with:
use axum::{
extract::State,
routing::get,
Json,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use reqwest::Client;
#[derive(Clone)]
struct AppState {
http: Client,
}
#[derive(Deserialize)]
struct User {
id: u64,
name: String,
}
#[derive(Deserialize)]
struct Post {
id: u64,
title: String,
body: String,
}
#[derive(Serialize)]
struct UserWithPosts {
user: User,
posts: Vec<Post>,
}
async fn user_with_posts_handler(
State(state): State<Arc<AppState>>,
) -> Json<UserWithPosts> {
let user_id = 1u64;
let user_url = format!("http://localhost:3001/users/{}", user_id);
let posts_url = format!("http://localhost:3002/users/{}/posts", user_id);
let user_future = state.http.get(&user_url).send();
let posts_future = state.http.get(&posts_url).send();
let (user_response, posts_response) = tokio::join!(user_future, posts_future);
let user: User = user_response.unwrap().json().await.unwrap();
let posts: Vec<Post> = posts_response.unwrap().json().await.unwrap();
Json(UserWithPosts { user, posts })
}
#[tokio::main]
async fn main() {
let http = Client::new();
let state = Arc::new(AppState { http });
let app = Router::new()
.route("/user-with-posts", get(user_with_posts_handler))
.with_state(state);
// In a real system, the mock servers would be separate processes.
// Here we start them in the same binary so the example runs easily.
tokio::spawn(async {
let app = Router::new()
.route("/users/{id}", get(|| async {
Json(User { id: 1, name: "alice".to_string() })
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tokio::spawn(async {
let app = Router::new()
.route("/users/{id}/posts", get(|| async {
Json(vec![
Post { id: 101, title: "My first post".to_string(), body: "Hello".to_string() },
Post { id: 102, title: "Rust is great".to_string(), body: "Axum rocks".to_string() },
])
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3002").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
// Wait for the mock servers to bind, then start the BFF.
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let bff_listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("BFF listening on http://localhost:3000");
axum::serve(bff_listener, app).await.unwrap();
}
This code is longer, but each part is simple. The BFF handler makes two HTTP GET requests at the same time using tokio::join!. It then parses the JSON responses into typed structs User and Vec<Post>. Finally, it combines them into a single UserWithPosts object and returns it as JSON.
The reqwest::Client is stored in AppState and shared across requests. That is important because creating a new client for every request is wasteful. The Arc allows the state to be cloned cheaply for each handler call.
Do not create a new reqwest::Client per request:
A reqwest::Client holds a connection pool internally. Creating a new client for every incoming request will create a new connection pool each time and destroy it at the end of the request. That slows everything down and can exhaust file descriptors under load. Always create one client at startup and share it through application state.
This example runs three servers on ports 3000, 3001, and 3002. In a real system, the user service and posts service would be separate processes, possibly on different machines. The BFF only knows their URLs. The frontend only knows the BFF's URL.
Tailoring Responses for Different Frontends
One of the main reasons to build a BFF is that different frontends need different data. A mobile app might only need a user's name and avatar URL. A desktop web app might need the user's full profile, including preferences and recent activity. If both frontends talk to the same generic user service, that service must return everything. The mobile app then wastes bandwidth and battery downloading fields it never uses.
A BFF can create separate routes for each client type. Each route calls the same upstream service but selects and transforms fields differently.
Let's extend the previous example with two routes: /mobile/user and /web/user. Both call the same upstream user service, but the mobile route returns a compact object, while the web route returns a larger one.
We will keep the mock user service on port 3001. Add the following structs and handlers to the previous main.rs. The full file is shown after the code explanation.
#[derive(Deserialize)]
struct FullUser {
id: u64,
name: String,
email: String,
avatar_url: String,
preferences: std::collections::HashMap<String, String>,
last_login: String,
}
#[derive(Serialize)]
struct MobileUser {
name: String,
avatar_url: String,
}
#[derive(Serialize)]
struct WebUser {
name: String,
email: String,
avatar_url: String,
preferences: std::collections::HashMap<String, String>,
}
async fn mobile_user_handler(
State(state): State<Arc<AppState>>,
) -> Json<MobileUser> {
let full_user: FullUser = state
.http
.get("http://localhost:3001/users/1")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
Json(MobileUser {
name: full_user.name,
avatar_url: full_user.avatar_url,
})
}
async fn web_user_handler(
State(state): State<Arc<AppState>>,
) -> Json<WebUser> {
let full_user: FullUser = state
.http
.get("http://localhost:3001/users/1")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
Json(WebUser {
name: full_user.name,
email: full_user.email,
avatar_url: full_user.avatar_url,
preferences: full_user.preferences,
})
}
The full main.rs now looks like this:
use axum::{
extract::State,
routing::get,
Json,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use reqwest::Client;
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
http: Client,
}
#[derive(Deserialize)]
struct FullUser {
id: u64,
name: String,
email: String,
avatar_url: String,
preferences: HashMap<String, String>,
last_login: String,
}
#[derive(Serialize)]
struct MobileUser {
name: String,
avatar_url: String,
}
#[derive(Serialize)]
struct WebUser {
name: String,
email: String,
avatar_url: String,
preferences: HashMap<String, String>,
}
async fn mobile_user_handler(
State(state): State<Arc<AppState>>,
) -> Json<MobileUser> {
let full_user: FullUser = state
.http
.get("http://localhost:3001/users/1")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
Json(MobileUser {
name: full_user.name,
avatar_url: full_user.avatar_url,
})
}
async fn web_user_handler(
State(state): State<Arc<AppState>>,
) -> Json<WebUser> {
let full_user: FullUser = state
.http
.get("http://localhost:3001/users/1")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
Json(WebUser {
name: full_user.name,
email: full_user.email,
avatar_url: full_user.avatar_url,
preferences: full_user.preferences,
})
}
#[tokio::main]
async fn main() {
let http = Client::new();
let state = Arc::new(AppState { http });
let app = Router::new()
.route("/mobile/user", get(mobile_user_handler))
.route("/web/user", get(web_user_handler))
.with_state(state);
// Mock user service on port 3001
tokio::spawn(async {
let app = Router::new()
.route("/users/{id}", get(|| async {
Json(FullUser {
id: 1,
name: "alice".to_string(),
email: "alice@example.com".to_string(),
avatar_url: "https://example.com/avatar.png".to_string(),
preferences: HashMap::from([
("theme".to_string(), "dark".to_string()),
("language".to_string(), "en".to_string()),
]),
last_login: "2026-08-30T12:00:00Z".to_string(),
})
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let bff_listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("BFF listening on http://localhost:3000");
axum::serve(bff_listener, app).await.unwrap();
}
Now if you run the server and visit http://localhost:3000/mobile/user, you get:
{"name":"alice","avatar_url":"https://example.com/avatar.png"}
If you visit http://localhost:3000/web/user, you get:
{"name":"alice","email":"alice@example.com","avatar_url":"https://example.com/avatar.png","preferences":{"theme":"dark","language":"en"}}
Both routes call the same upstream service. The BFF decides what to pass through. This is the core value of a BFF layer.
Field transformation is a BFF responsibility:
The upstream service returns last_login and id fields. The BFF drops them for both client types because neither frontend needs them in this example. In a real system, you might also rename fields, convert data types, or combine data from multiple services. The BFF is the only place that knows what a specific frontend needs.
Aggregating Multiple Upstream Calls
The previous examples fetched from one service. A more common BFF scenario is aggregating data from several services. You already saw a tiny version in the first example. Now we will do it with real HTTP calls to three different mock services.
We will create a /dashboard route that returns user info, recent orders, and unread notifications. Each piece comes from a different service. The handler fires all three requests concurrently.
The code below is a complete example. It defines three mock services (on ports 3001, 3002, 3003) and a BFF on port 3000. Replace src/main.rs with this.
use axum::{
extract::State,
routing::get,
Json,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use reqwest::Client;
#[derive(Clone)]
struct AppState {
http: Client,
}
#[derive(Deserialize, Serialize)]
struct UserInfo {
name: String,
email: String,
}
#[derive(Deserialize, Serialize)]
struct Order {
id: u64,
total_cents: u64,
status: String,
}
#[derive(Deserialize, Serialize)]
struct Notification {
id: u64,
message: String,
}
#[derive(Serialize)]
struct Dashboard {
user: UserInfo,
orders: Vec<Order>,
notifications: Vec<Notification>,
}
async fn dashboard_handler(
State(state): State<Arc<AppState>>,
) -> Json<Dashboard> {
let user_future = state.http
.get("http://localhost:3001/user")
.send();
let orders_future = state.http
.get("http://localhost:3002/orders")
.send();
let notifications_future = state.http
.get("http://localhost:3003/notifications")
.send();
let (user_resp, orders_resp, notifications_resp) = tokio::join!(
user_future,
orders_future,
notifications_future
);
let user: UserInfo = user_resp.unwrap().json().await.unwrap();
let orders: Vec<Order> = orders_resp.unwrap().json().await.unwrap();
let notifications: Vec<Notification> = notifications_resp.unwrap().json().await.unwrap();
Json(Dashboard {
user,
orders,
notifications,
})
}
#[tokio::main]
async fn main() {
let http = Client::new();
let state = Arc::new(AppState { http });
let app = Router::new()
.route("/dashboard", get(dashboard_handler))
.with_state(state);
// Mock services
tokio::spawn(async {
let app = Router::new()
.route("/user", get(|| async {
Json(UserInfo {
name: "alice".to_string(),
email: "alice@example.com".to_string(),
})
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tokio::spawn(async {
let app = Router::new()
.route("/orders", get(|| async {
Json(vec![
Order { id: 1, total_cents: 2500, status: "shipped".to_string() },
Order { id: 2, total_cents: 990, status: "processing".to_string() },
])
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3002").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tokio::spawn(async {
let app = Router::new()
.route("/notifications", get(|| async {
Json(vec![
Notification { id: 1, message: "Your order shipped".to_string() },
Notification { id: 2, message: "New sale".to_string() },
])
}));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3003").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let bff_listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("BFF listening on http://localhost:3000");
axum::serve(bff_listener, app).await.unwrap();
}
When you hit http://localhost:3000/dashboard, the BFF returns one combined JSON object containing all three pieces. The frontend makes one request, not three.
This is a classic BFF pattern. But there is a subtle issue: if any of the three upstream services is slow or fails, the entire dashboard fails. We will address that soon.
One slow upstream can stall the whole BFF response:
In this example, the handler waits for all three upstream calls to complete before returning anything. If the notifications service takes five seconds, the entire dashboard takes five seconds, even if user and orders are ready in 50 milliseconds. In a real BFF, you should consider adding timeouts per upstream call or returning partial data with warnings.
Handling Upstream Failures and Timeouts
A BFF that only works when every upstream service is healthy is fragile. Upstream services will fail, become slow, or return malformed data. A good BFF handles those situations gracefully and still returns something useful to the frontend.
The most important tool is a timeout. If an upstream service takes too long, the BFF should give up and either return an error or use a cached fallback. You can apply timeouts at the request level using tokio::time::timeout.
Here is a modified version of the dashboard handler that applies a one-second timeout to each upstream call. If any call times out, the handler returns an HTTP 504 Gateway Timeout with a clear message.
We will need to import StatusCode and IntoResponse. The handler return type changes from Json<Dashboard> to a Result<Json<Dashboard>, (StatusCode, String)>.
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Json,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
use reqwest::Client;
#[derive(Clone)]
struct AppState {
http: Client,
}
#[derive(Deserialize, Serialize)]
struct UserInfo {
name: String,
email: String,
}
#[derive(Deserialize, Serialize)]
struct Order {
id: u64,
total_cents: u64,
status: String,
}
#[derive(Deserialize, Serialize)]
struct Notification {
id: u64,
message: String,
}
#[derive(Serialize)]
struct Dashboard {
user: UserInfo,
orders: Vec<Order>,
notifications: Vec<Notification>,
}
async fn dashboard_handler(
State(state): State<Arc<AppState>>,
) -> Result<Json<Dashboard>, (StatusCode, String)> {
let timeout_duration = Duration::from_secs(1);
let user_future = state.http
.get("http://localhost:3001/user")
.send();
let orders_future = state.http
.get("http://localhost:3002/orders")
.send();
let notifications_future = state.http
.get("http://localhost:3003/notifications")
.send();
let (user_result, orders_result, notifications_result) = tokio::join!(
tokio::time::timeout(timeout_duration, user_future),
tokio::time::timeout(timeout_duration, orders_future),
tokio::time::timeout(timeout_duration, notifications_future),
);
let user_resp = user_result
.map_err(|_| (StatusCode::GATEWAY_TIMEOUT, "User service timed out".to_string()))?
.map_err(|_| (StatusCode::BAD_GATEWAY, "User service request failed".to_string()))?;
let orders_resp = orders_result
.map_err(|_| (StatusCode::GATEWAY_TIMEOUT, "Orders service timed out".to_string()))?
.map_err(|_| (StatusCode::BAD_GATEWAY, "Orders service request failed".to_string()))?;
let notifications_resp = notifications_result
.map_err(|_| (StatusCode::GATEWAY_TIMEOUT, "Notifications service timed out".to_string()))?
.map_err(|_| (StatusCode::BAD_GATEWAY, "Notifications service request failed".to_string()))?;
let user: UserInfo = user_resp.json().await
.map_err(|_| (StatusCode::BAD_GATEWAY, "Invalid user service response".to_string()))?;
let orders: Vec<Order> = orders_resp.json().await
.map_err(|_| (StatusCode::BAD_GATEWAY, "Invalid orders service response".to_string()))?;
let notifications: Vec<Notification> = notifications_resp.json().await
.map_err(|_| (StatusCode::BAD_GATEWAY, "Invalid notifications service response".to_string()))?;
Ok(Json(Dashboard {
user,
orders,
notifications,
}))
}
#[tokio::main]
async fn main() {
// Same as before, but the handler is now Result.
let http = Client::new();
let state = Arc::new(AppState { http });
let app = Router::new()
.route("/dashboard", get(dashboard_handler))
.with_state(state);
// Mock services remain unchanged (omitted for brevity).
// Start them as in the previous example.
// ... (same as previous main, but with this handler)
}
The code above shows the new handler and the necessary imports. The mock services are omitted for brevity, but they are exactly the same as in the previous example. The important changes are:
- The handler returns
Result<Json<Dashboard>, (StatusCode, String)>. - Each upstream future is wrapped in
tokio::time::timeout. map_errconverts timeout errors and request errors into a tuple(StatusCode, String).- JSON parsing errors are also converted.
If any upstream service exceeds one second, the entire handler returns 504 Gateway Timeout with a message like "User service timed out". That is a simple and predictable error model.
Never unwrap upstream results in production:
The previous examples used .unwrap() on HTTP responses and JSON parsing. That works for learning, but in production, an upstream service may return a 500, close the connection, or send invalid JSON. Calling .unwrap() on any of those will panic and abort that request's task (the client gets no response); under the default panic = "unwind" setting the process keeps serving other requests - but the request still fails, so handle errors explicitly. The Result return type forces you to think about what happens when things go wrong.
Using Tower Middleware for Cross-Cutting Concerns
BFFs often need the same behavior applied to many routes: authentication, logging, rate limiting, CORS. Instead of repeating that code in every handler, you can use Tower middleware layers.
Axum's router supports layer and route_layer methods. A layer applies to all routes in that router. A route_layer applies to all routes added before the call - the difference from layer is not which routes it covers, but when it runs: a route_layer only runs when a request actually matches one of those routes, while a layer runs for every request, including ones that end in a 404. Neither of them targets a single route; for that, use MethodRouter::layer.
Here is a small complete example that adds a request ID header to every response using a custom middleware. The middleware reuses an x-request-id header the client already sent, or generates a fresh UUID when there is none.
First, add the uuid crate:
cargo add uuid -F v4
use axum::{
extract::Request,
http::HeaderValue,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
use uuid::Uuid;
// `middleware::from_fn` is built into Axum - no extra crate is needed for it.
async fn add_request_id(mut req: Request, next: Next) -> Response {
let request_id = match req.headers().get("x-request-id") {
Some(value) => value.clone(),
None => HeaderValue::from_str(&Uuid::new_v4().to_string())
.unwrap_or(HeaderValue::from_static("invalid-request-id")),
};
req.headers_mut().insert("x-request-id", request_id.clone());
let mut response = next.run(req).await;
response.headers_mut().insert("x-request-id", request_id);
response
}
async fn hello() -> &'static str {
"Hello from the BFF!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(middleware::from_fn(add_request_id));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
The add_request_id middleware runs before every request handled by this router. It checks if the client already sent an x-request-id header; if not, it generates one. Then it lets the request continue to the handler, and finally it inserts the request ID into the response.
This middleware is completely separate from the handler logic. You can add authentication, rate limiting, tracing, and compression in the same way. Axum's use of Tower means you can pick from a huge ecosystem of existing middleware crates like tower-http.
Use MethodRouter::layer for per-route middleware:
If you want authentication only on some routes, use MethodRouter::layer - .layer(...) on a single get(...)/post(...) route - not route_layer. route_layer applies to all routes added before the call, so Router::new().route("/public", get(public_handler)).route_layer(middleware::from_fn(require_auth)) protects /public (the route added before it), and a second route added after the call is not protected at all. The order of route_layer calls matters because they wrap the routes added so far. To protect exactly one route, write it as get(private_handler).layer(middleware::from_fn(require_auth)) when you register that route.
Building a BFF from Scratch with a Stepper
Now that you have seen the core ideas, let's walk through the process of building a minimal BFF from nothing. This stepper summarizes the steps; you can follow along in a new project.
Step 1: Create the project and add dependencies
Start a new Rust project and add the crates you will need: Axum, Tokio, Serde, and Reqwest.
cargo new my-bff
cd my-bff
cargo add axum@0.8
cargo add tokio@1 --features full
cargo add serde -F derive
cargo add serde_json
cargo add reqwest -F json
The reqwest crate will be used to call upstream services. The serde crates handle JSON serialization and deserialization.
Step 2: Define your data structures
Think about what the frontend needs. Create a struct for the combined response and structs for each upstream response you expect.
#[derive(Serialize)]
struct BffResponse {
user_name: String,
recent_orders: Vec<OrderSummary>,
}
You can also derive Deserialize for the upstream response structs.
Step 3: Create a shared HTTP client state
Build a reqwest::Client at startup and wrap it in an Arc. Pass it to the router with with_state.
#[derive(Clone)]
struct AppState {
http: reqwest::Client,
}
let state = Arc::new(AppState {
http: reqwest::Client::new(),
});
Step 4: Write the aggregation handler
In your handler, extract the state, fire all upstream requests concurrently with tokio::join!, parse the results, and combine them into the response struct.
async fn bff_handler(
State(state): State<Arc<AppState>>,
) -> Json<BffResponse> {
let (user, orders) = tokio::join!(
state.http.get("http://user-service/user").send(),
state.http.get("http://order-service/orders").send()
);
// parse and combine...
Json(BffResponse { user_name: "...".into(), recent_orders: vec![] })
}
Step 5: Add middleware for cross-cutting concerns
Use Tower layers for authentication, timeouts, or request tracing. Apply them with layer or route_layer.
let app = Router::new()
.route("/bff", get(bff_handler))
.layer(middleware::from_fn(add_auth))
.with_state(state);
Step 6: Serve the BFF and test
Bind a TCP listener and pass the router to axum::serve. Test the endpoint with a browser or curl.
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Each step builds on the previous one. The result is a BFF that handles one or more frontend-specific endpoints, aggregates data, and returns a clean JSON response.
If your BFF returns the combined data, you have a working layer:
After following the stepper, start your server and call the BFF endpoint. If you see a single JSON object containing data from multiple upstream services, you have successfully built a BFF layer. The frontend now has a single, tailored endpoint instead of many scattered calls.
Common Mistakes When Building BFFs with Axum
BFFs introduce a new layer of complexity, and beginners often make the same mistakes. Here are the most important ones to avoid.
Blocking the async runtime. Axum runs on Tokio's async runtime. If you call a blocking function like std::thread::sleep or a synchronous database driver inside a handler, you block the entire worker thread and prevent other requests from making progress. Always use async alternatives (tokio::time::sleep, async database clients like sqlx). If you must run blocking code, use tokio::task::spawn_blocking.
Not setting timeouts on upstream calls. Without timeouts, a slow upstream service can hold the BFF handler open indefinitely, tying up resources and eventually causing timeouts on the frontend side. Wrap every upstream call in tokio::time::timeout or configure timeouts on the HTTP client itself.
Ignoring upstream errors. If you .unwrap() every upstream response, one failing service panics that request's handler task and the client gets no response. Always handle errors and return a meaningful status code. The previous section showed how to do that with Result and map_err.
Creating a new HTTP client for each request. As warned earlier, this kills connection reuse and performance. Store one client in application state.
Over-fetching and then passing everything through. A BFF should tailor data for the frontend. If you just call the upstream service and return its raw response unchanged, you are not adding value. Strip unused fields, combine data, and shape the response to what the frontend actually renders.
Putting too much logic in one handler. Handlers should be small and focused. If a handler does ten different things, break it into helper functions or separate handlers that call each other. Axum lets you compose handlers like any other Rust functions.
Each of these mistakes is easy to make and easy to avoid once you know about them.
Per-Route Middleware with MethodRouter::layer
The BFF in the examples above applies one middleware stack to the whole router. Often that is too broad: a public /health route should not require an API key, and a mobile route and a web route may need different rate limits. The tool for exactly one route is MethodRouter::layer - call .layer(...) on the get(...)/post(...) value itself when you register the route:
use axum::{
extract::Request,
http::{header, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
const API_KEY: &str = "secret-key";
async fn require_api_key(req: Request, next: Next) -> Response {
// Check the Authorization header; return 401 if it is missing or wrong.
let authorized = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
== Some(API_KEY);
if authorized {
next.run(req).await
} else {
(StatusCode::UNAUTHORIZED, "missing or invalid API key").into_response()
}
}
async fn public_handler() -> &'static str { "public" }
async fn private_handler() -> &'static str { "private" }
let app = Router::new()
.route("/public", get(public_handler))
.route(
"/private",
get(private_handler).layer(middleware::from_fn(require_api_key)),
);
/public has no middleware at all; /private runs require_api_key first. Contrast the three layer calls, because mixing them up is the most common BFF middleware mistake:
| Call | Applies to | Runs when |
|---|---|---|
Router::layer(...) | All routes in the router | Every request, even unmatched ones |
Router::route_layer(...) | All routes added before the call | Only when a request matches one of those routes |
MethodRouter::layer(...) (on one get/post) | Exactly that one route | When that route matches |
A useful shape for a BFF with several frontends is one nested router per frontend, each with its own layer stack, merged into a top-level router: .nest("/mobile", mobile_router).nest("/web", web_router). Each frontend's auth, rate limit, and timeout rules then live with its routes, not in a shared global stack.
The Aggregation Pattern: Parallel Calls with Partial Failure
The dashboard handler earlier in this page fires three upstream calls with tokio::join! and fails the whole response if any one of them fails or times out. That is the simple version of the BFF aggregation pattern; the production version adds one more idea - partial failure. A notifications service being down should not hide the user's orders. The pattern is: run the calls in parallel, give each its own timeout, and collect per-call results instead of short-circuiting on the first error:
use axum::{extract::State, Json};
use std::time::Duration;
// The `UserInfo`, `Order`, `Notification`, and `AppState` types come from
// the first dashboard example above.
#[derive(serde::Serialize)]
struct Dashboard {
user: Option<UserInfo>,
orders: Vec<Order>,
notifications: Vec<Notification>,
// Tell the frontend what is missing, instead of failing silently.
warnings: Vec<String>,
}
async fn dashboard_handler(
State(state): State<Arc<AppState>>,
) -> Json<Dashboard> {
let timeout = Duration::from_secs(1);
let (user, orders, notifications) = tokio::join!(
fetch_user(&state.http, timeout),
fetch_orders(&state.http, timeout),
fetch_notifications(&state.http, timeout),
);
let mut warnings = Vec::new();
let user = match user {
Ok(user) => Some(user),
Err(e) => { warnings.push(format!("user service unavailable: {e}")); None }
};
let orders = match orders {
Ok(orders) => orders,
Err(e) => { warnings.push(format!("orders service unavailable: {e}")); Vec::new() }
};
let notifications = match notifications {
Ok(notifications) => notifications,
Err(e) => { warnings.push(format!("notifications unavailable: {e}")); Vec::new() }
};
Json(Dashboard { user, orders, notifications, warnings })
}
// Each fetch wraps its request in `tokio::time::timeout` and returns a
// `Result`, so a slow upstream degrades to a warning instead of a 504
// for the whole dashboard.
async fn fetch_user(
http: &reqwest::Client,
timeout: Duration,
) -> Result<UserInfo, String> {
let response = tokio::time::timeout(timeout, http.get("http://localhost:3001/user").send())
.await
.map_err(|_| "user service timed out".to_string())?
.map_err(|e| format!("user service request failed: {e}"))?;
response
.json::<UserInfo>()
.await
.map_err(|e| format!("user service returned invalid JSON: {e}"))
}
async fn fetch_orders(
http: &reqwest::Client,
timeout: Duration,
) -> Result<Vec<Order>, String> {
let response = tokio::time::timeout(timeout, http.get("http://localhost:3002/orders").send())
.await
.map_err(|_| "orders service timed out".to_string())?
.map_err(|e| format!("orders service request failed: {e}"))?;
response
.json::<Vec<Order>>()
.await
.map_err(|e| format!("orders service returned invalid JSON: {e}"))
}
async fn fetch_notifications(
http: &reqwest::Client,
timeout: Duration,
) -> Result<Vec<Notification>, String> {
let response = tokio::time::timeout(timeout, http.get("http://localhost:3003/notifications").send())
.await
.map_err(|_| "notifications service timed out".to_string())?
.map_err(|e| format!("notifications service request failed: {e}"))?;
response
.json::<Vec<Notification>>()
.await
.map_err(|e| format!("notifications service returned invalid JSON: {e}"))
}
Three rules make this pattern work. First, fire the independent calls concurrently with tokio::join! (or tokio::try_join! when you really do want the whole thing to fail on the first error) - never await them one after another, or the latencies add up. Second, give each call its own timeout: one slow upstream must not stall the whole response, and tokio::time::timeout around a single call is cheaper and clearer than a timeout around the entire join!. Third, decide up front which pieces are required and which are optional: a missing user is probably a real error (return a 502/504 for that call alone), while missing notifications are a warning and an empty list. The frontend can then render what it has and show a small "notifications unavailable" note, instead of a blank page.
Summary
BFF layers exist to give each frontend its own tailored API. Axum fits this pattern because its async handlers, type-safe extractors, state management, and Tower middleware integration make it simple to aggregate, transform, and protect upstream data.
The core technique is concurrent aggregation with tokio::join! or tokio::try_join!, combined with error handling and timeouts. You create a shared reqwest::Client in application state, call multiple upstream services, parse their responses, and return a single combined object.
Different frontends need different BFF routes. A mobile route can return a compact subset of fields, while a web route can return a fuller object. Each route is just a handler that fetches from the same upstream service and selects what to pass through.
When building your own BFF, remember to handle failures gracefully, set timeouts, and use middleware for cross-cutting concerns like authentication and logging. The result is a clean, maintainable layer that makes frontend development much simpler.
If you have followed the examples on this page, you now have a working mental model of how Axum supports BFF layers. The next step is to apply these patterns to a real project, perhaps by building a BFF for a specific frontend you care about.