Feature-based split in Axum projects
Learn how to organize a growing Rust backend by feature modules, understand why grouping related code together reduces complexity, and build practical feature folders with complete examples.
Why layer-based organization gets harder as projects grow
In smaller Axum applications, arranging files by technical purpose works well. You place all handlers in one directory, all models in another, and all route definitions in a third. When a project has only a few endpoints, you can find things quickly because there are not many files in each folder.
The difficulty starts when the same project grows to include several distinct business areas. A typical backend might handle user accounts, product listings, order processing, analytics, and internal admin tools. Each of those areas has its own handlers, its own data structures, its own route logic, and often its own dedicated state or configuration. With a layer-based layout, the handlers for all five areas live side by side, as do the models and the route definitions. To add a new endpoint to the product area, you need to touch a routes file, a handlers file, and a models file - possibly plus a state file - all in different directories.
Feature-based organization flips that model. Instead of grouping by what files are (all handlers together), it groups by what the application does (all user-related code together). This page explains the split, walks through complete examples, and shows the decision points that matter most for beginners.
What a feature-based split actually means
A feature-based split organizes source code around business capabilities rather than around technical layers. A "feature" here means a self-contained area of the application's behavior: user authentication, product search, order checkout, health reporting, or anything else the system does. Each feature gets its own folder, and inside that folder you place every file the feature needs - its route definitions, its handler functions, its request and response structures, its internal helpers, and any state or service connections unique to that feature.
The phrase "feature-based split" describes a project layout where the top-level module names answer the question "what does this application do?" rather than the question "what kind of code is this?" A directory named users/ tells you the feature. A directory named handlers/ tells you the technical role of every file inside it, but it does not tell you which parts of the application those handlers belong to until you open each file.
The mental model that helps most is thinking of a feature folder as a miniature application. Each feature has a small public surface - usually a function that returns a configured Router - and a private interior full of details that other features never need to see. The public surface is like a storefront counter: outsiders interact only through it. The private interior is the back room with all the specific machinery. This boundary keeps one feature's internal changes from leaking into every other part of the codebase.
Same assembly, different folders:
A feature-based split keeps the same thin main.rs, a lib.rs that declares modules, and a pub fn app that assembles the final router. The feature split changes where you put the modules that lib.rs declares - the modules live under feature folders instead of being flat files at the crate root or grouped under routes/ and handlers/.
Starting point - a small single-feature example
Begin with the smallest possible feature folder before adding complexity. Assume the project already contains a working app() function that returns a Router, and you now want to move a health check endpoint into its own feature folder.
Here is the folder layout before the split:
src/
lib.rs
main.rs
routes/
mod.rs
health.rs
handlers/
mod.rs
health.rs
The routes/health.rs file defines a router for the health endpoint, and the handlers/health.rs file contains the handler function itself. In a feature-based layout, those two responsibilities collapse into one folder:
src/
lib.rs
main.rs
features/
health/
mod.rs
The mod.rs inside the health feature can hold both the route definition and the handler. A complete example looks like this:
// src/features/health/mod.rs
use axum::{routing::get, Router};
pub fn router() -> Router {
Router::new().route("/health", get(health_check))
}
async fn health_check() -> &'static str {
"ok"
}
The public item here is router(). Everything else remains private to the module. The name router is a common convention, but routes or health_router work equally well - the important part is that it is the single public entry point for the feature.
Now lib.rs must declare the new module and include the feature router in the application:
// src/lib.rs
mod features;
use axum::Router;
pub fn app() -> Router {
Router::new().merge(features::health::router())
}
And features/mod.rs declares each feature submodule:
// src/features/mod.rs
pub mod health;
A small feature like this feels almost trivial, but the structure already demonstrates the core idea: the health check owns its route, its handler, and its module file all in one place. To change how the health check responds, you edit exactly one file and nothing else.
Checkpoint:
If you can run the application after this change and GET /health still returns ok, the feature split is working. The external HTTP behavior should be identical - only the internal file organization changed.
Comparing the two layouts before adding more features
Before a project reaches a certain size, layer-based organization feels natural. A handler is a handler. Grouping similar handlers together seems tidy, and for five or six endpoints it genuinely is. The problem appears when you need to trace a single request through the system. To understand how POST /products works, you open a routes file to see the route registration, then a handlers file to see the logic, then a models file to see the request shape, and possibly a state file to see what the handler can access. Each of those files also contains code for other endpoints, so you are scrolling past unrelated material at every step.
Feature-based organization keeps the entire path for one request in one folder. When someone asks how product creation works, you open features/products/ and read the small set of files inside. The route, handler, models, and any product-specific helpers are adjacent. This locality reduces the mental effort of understanding a feature, especially in codebases you are seeing for the first time.
A layer-based layout also makes it harder to see which features actually exist. A directory listing of handlers/ with forty files tells you there are forty handler functions, but it does not tell you how many business capabilities the application implements. A directory listing of features/ with eight subfolders answers that question immediately.
This is not a claim that feature-based is universally better. For very small projects, it introduces folders that hold only one or two tiny files, and the layer-based approach is simpler to start with. The decision point comes when you notice that adding a new endpoint requires touching files in three or more separate directories. That friction is the signal that grouping by feature will pay off.
A richer feature - user accounts with local state
Move beyond a single-file feature to one with multiple files and shared state inside the feature. A user feature typically has routes for listing users and creating users, handler functions for both operations, a model representing a user, and some local state to hold the user list during development.
Create the feature folder with separate files for clarity:
src/
features/
users/
mod.rs
routes.rs
handlers.rs
model.rs
state.rs
The model.rs file defines what a user looks like:
// src/features/users/model.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: u64,
pub name: String,
pub email: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CreateUser {
pub name: String,
pub email: String,
}
Two structs serve different purposes. User is the full representation returned to clients, while CreateUser is the shape expected in a request body when creating a new user. Both are pub within the feature because handlers.rs and routes.rs need them, but model.rs itself does not need to be public outside the feature - only the router function needs to be.
The state.rs file holds the shared in-memory data for this feature:
// src/features/users/state.rs
use std::sync::{Arc, Mutex};
use super::model::User;
#[derive(Clone, Default)]
pub struct UserState {
pub users: Arc<Mutex<Vec<User>>>,
}
impl UserState {
pub fn new() -> Self {
Self {
users: Arc::new(Mutex::new(Vec::new())),
}
}
}
Wrapping the list in Arc<Mutex<...>> is necessary because multiple incoming requests may access the data concurrently, and Axum handlers are async. The Mutex ensures only one thread modifies the vector at a time. The super::model::User import references the parent module's model file - a common pattern inside feature folders when one feature file needs types from a sibling file.
The handlers.rs file contains the HTTP-facing functions:
// src/features/users/handlers.rs
use axum::{
extract::State,
http::StatusCode,
Json,
};
use super::{model::CreateUser, state::UserState};
pub async fn list_users(State(state): State<UserState>) -> Json<Vec<super::model::User>> {
let users = state.users.lock().unwrap();
Json(users.clone())
}
pub async fn create_user(
State(state): State<UserState>,
Json(payload): Json<CreateUser>,
) -> (StatusCode, Json<super::model::User>) {
let mut users = state.users.lock().unwrap();
let next_id = users.len() as u64 + 1;
let user = super::model::User {
id: next_id,
name: payload.name,
email: payload.email,
};
users.push(user.clone());
(StatusCode::CREATED, Json(user))
}
Each handler receives the feature-local UserState as an extractor. Axum knows how to provide it because the route definition associates the state with the router. The .lock().unwrap() call is acceptable here because if the mutex becomes poisoned - meaning a thread panicked while holding the lock - there is no clean recovery path in a small example; production code might handle it more carefully.
The routes.rs file wires the handlers to paths:
// src/features/users/routes.rs
use axum::routing::get;
use axum::Router;
use super::handlers;
use super::state::UserState;
pub fn router(state: UserState) -> Router {
Router::new()
.route("/", get(handlers::list_users).post(handlers::create_user))
.with_state(state)
}
Finally, the feature's mod.rs ties everything together and exposes the single public function that other parts of the application call:
// src/features/users/mod.rs
mod handlers;
mod model;
mod routes;
mod state;
pub use routes::router;
pub use state::UserState;
Only two items become public from this feature: the router function and the UserState type. The model structs, handlers, and route details remain private. Other features cannot accidentally depend on user handler functions directly; they can only compose the user router into the application.
State ownership belongs to the feature:
A common beginner mistake is creating UserState inside routes::router and never giving the caller access to it. The feature's mod.rs must re-export the state type so the application assembly code can create an instance and pass it in. If routes::router instead constructs its own state internally, you lose the ability to share that state with middleware, other features, or test harnesses that need to pre-seed data.
The application assembly in lib.rs now creates the feature state explicitly:
// src/lib.rs
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new().merge(features::users::router(user_state))
}
Multiple features - products alongside users
A feature-based layout becomes more compelling when a second feature appears. Add a simple product feature that manages a static product catalog, without shared state for now:
src/
features/
users/
mod.rs
routes.rs
handlers.rs
model.rs
state.rs
products/
mod.rs
routes.rs
handlers.rs
model.rs
The product model might look like this:
// src/features/products/model.rs
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Product {
pub id: u64,
pub name: String,
pub price_cents: u64,
}
The handler returns a small hardcoded catalog:
// src/features/products/handlers.rs
use axum::{extract::Path, http::StatusCode, Json};
use super::model::Product;
pub async fn list_products() -> Json<Vec<Product>> {
let products = vec![
Product {
id: 1,
name: "Desk Lamp".to_string(),
price_cents: 2499,
},
Product {
id: 2,
name: "Notebook Set".to_string(),
price_cents: 899,
},
];
Json(products)
}
pub async fn get_product(Path(id): Path<u64>) -> Result<Json<Product>, StatusCode> {
let products = vec![
Product {
id: 1,
name: "Desk Lamp".to_string(),
price_cents: 2499,
},
Product {
id: 2,
name: "Notebook Set".to_string(),
price_cents: 899,
},
];
products
.into_iter()
.find(|p| p.id == id)
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
}
The get_product handler returns a Result. When the product is found, it returns Ok(Json(product)). When not found, it returns Err(StatusCode::NOT_FOUND). Axum understands this pattern and converts the error variant into an HTTP 404 response. This is the idiomatic way to handle "item not found" in Axum handlers.
The routes file:
// src/features/products/routes.rs
use axum::routing::get;
use axum::Router;
use super::handlers;
pub fn router() -> Router {
Router::new()
.route("/", get(handlers::list_products))
.route("/{id}", get(handlers::get_product))
}
And the feature's mod.rs:
// src/features/products/mod.rs
mod handlers;
mod model;
mod routes;
pub use routes::router;
Now features/mod.rs declares both features:
// src/features/mod.rs
pub mod products;
pub mod users;
A first attempt might merge both routers directly, since each router works on its own:
// src/lib.rs
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new()
.merge(features::users::router(user_state))
.merge(features::products::router())
}
That attempt fails. Both routers define a route at /, so merging them panics at startup - Axum rejects overlapping method routes with Overlapping method route. Handler for GET / already exists. The merge only works once the two features own different paths, which is why, in a real application, you add prefixes using nest:
// src/lib.rs
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new()
.nest("/users", features::users::router(user_state))
.nest("/products", features::products::router())
}
With nest, the user router's / route becomes /users, and the product router's /{id} route becomes /products/{id}. The feature folders internally use relative paths, and the application assembly decides where each feature lives in the URL space. Note the missing trailing slash: a nested router's / route is served at the prefix itself, so GET /users works but GET /users/ returns 404.
Path prefix decisions belong at assembly time:
A feature that internally registers routes at / is more reusable than one that hardcodes /users or /products internally. If the feature hardcodes its own prefix, moving the feature to a different URL path requires editing the feature's route definitions. By using relative paths inside the feature and applying nest at the assembly point, the same feature can be mounted at /api/users, /v2/users, or any other prefix without internal changes.
Organizing shared code that spans multiple features
So far each feature has been self-contained. But real applications have code that multiple features need: a common error type, a database connection pool, authentication helpers, or shared response formats. Where does that code go in a feature-based layout?
The most common answer is a common or shared folder that sits alongside the feature folders. This folder is not a feature itself - it has no routes, no handlers, no business logic tied to a single capability. It provides shared infrastructure that features import:
src/
features/
users/
mod.rs
...
products/
mod.rs
...
common/
mod.rs
error.rs
The common/error.rs might define an application-wide error type that all features use in their Result types:
// src/common/error.rs
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub struct AppError {
status: StatusCode,
message: String,
}
impl AppError {
pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
Self {
status,
message: message.into(),
}
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::new(StatusCode::NOT_FOUND, message)
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(self.status, self.message).into_response()
}
}
The common/mod.rs exposes these modules:
// src/common/mod.rs
pub mod error;
lib.rs must also declare the new common module, or the path crate::common does not exist and the import in the feature fails to compile:
// src/lib.rs
mod common;
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new()
.nest("/users", features::users::router(user_state))
.nest("/products", features::products::router())
}
When the project gains a database, add a db.rs file to common/ the same way and declare it in common/mod.rs.
A feature that wants to use the shared error type imports it through the crate path:
// src/features/products/handlers.rs
use axum::{extract::Path, Json};
use crate::common::error::AppError;
use super::model::Product;
pub async fn get_product(Path(id): Path<u64>) -> Result<Json<Product>, AppError> {
let products = vec![
Product {
id: 1,
name: "Desk Lamp".to_string(),
price_cents: 2499,
},
Product {
id: 2,
name: "Notebook Set".to_string(),
price_cents: 899,
},
];
products
.into_iter()
.find(|p| p.id == id)
.map(Json)
.ok_or_else(|| AppError::not_found(format!("No product with id {id}")))
}
The key distinction: common/ is a technical grouping, not a feature grouping. This is not a betrayal of the feature-based principle - it recognizes that some concerns genuinely cut across all features. The difference from a layer-based layout is that common/ stays small and focused on genuinely shared infrastructure, while the bulk of the application lives in feature folders. If you find yourself adding business logic to common/, that is a signal it belongs in a feature folder instead.
Avoid a 'common' dumping ground:
The common folder can silently grow into a second handlers/ or models/ directory if you are not careful. If a piece of code is only used by one feature, even if it is technically general-purpose today, keep it inside that feature folder. Promote code to common/ only when a second feature genuinely needs it. This keeps the shared surface small and makes feature boundaries honest.
Handling cross-feature communication
Occasionally one feature needs data or behavior from another feature. A user-facing profile endpoint might include a list of the user's recent orders, where orders are a separate feature. How do features talk to each other?
The cleanest approach for beginners is to keep cross-feature communication at the assembly level, not inside feature files. The app() function in lib.rs wires features together by passing explicit dependencies. When a feature needs access to another feature's service or state, that dependency is created in app() and passed in as a parameter.
Say an orders feature needs to list orders per user, so its handlers must read the user list. The orders feature takes the user feature's state as a parameter, exactly like the users feature already does. Its handler reads the shared user list and builds one line per user:
// src/features/orders/handlers.rs
use axum::{extract::State, Json};
use crate::features::users::UserState;
pub async fn list_orders(State(state): State<UserState>) -> Json<Vec<String>> {
let users = state.users.lock().unwrap();
Json(
users
.iter()
.map(|user| format!("Orders for {}", user.name))
.collect(),
)
}
The handler takes State<UserState> as its extractor, which is how Axum hands shared data to a handler. It locks the same user list the users feature writes to, so an order listing always reflects the users created so far. The crate::features::users::UserState path works because the users feature re-exports its state type from its mod.rs; the orders feature never reaches into the users feature's private files.
The routes file passes the state into the router:
// src/features/orders/routes.rs
use axum::routing::get;
use axum::Router;
use super::handlers;
use crate::features::users::UserState;
pub fn router(state: UserState) -> Router {
Router::new()
.route("/", get(handlers::list_orders))
.with_state(state)
}
Do not skip with_state:
The .with_state(state) call is load-bearing. The handler uses State<UserState>, so before that call the router has the type Router<UserState>, and a function declared to return plain Router will not compile - the compiler reports mismatched types on the route registration. Only after .with_state does the router become a plain Router that app() can nest. Every feature router whose handlers take state must end with .with_state.
The feature's mod.rs follows the same pattern as the other features:
// src/features/orders/mod.rs
mod handlers;
mod routes;
pub use routes::router;
features/mod.rs declares the new feature alongside the others:
// src/features/mod.rs
pub mod health;
pub mod orders;
pub mod products;
pub mod users;
And app() builds the UserState once and hands it to both features that need it:
// src/lib.rs
mod common;
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new()
.nest("/users", features::users::router(user_state.clone()))
.nest("/products", features::products::router())
.nest("/orders", features::orders::router(user_state))
}
The .clone() here does not copy the user list. UserState holds its list inside an Arc, a shared-ownership pointer, so cloning the state only copies the pointer and both features keep looking at the same list. Creating a user through /users and then listing /orders shows that user immediately. The dependency direction stays explicit: app() builds UserState once and hands it to whichever features need it, and no feature imports another feature's private modules.
An alternative is to define public service functions inside each feature and call them directly from another feature's handlers. This creates a direct compile-time dependency between the two features, which is sometimes the pragmatic choice for small projects. For beginners, the assembly-level wiring is easier to reason about because the dependency graph is visible in one place (lib.rs), and features remain decoupled from each other's implementation details.
Circular dependencies tangle the design:
If feature A imports from feature B and feature B imports from feature A, Rust will still compile the crate - modules in the same crate may reference each other in a cycle. The failure is architectural, not a compile error: the two features become impossible to understand, test, or reuse separately. Feature-based organization makes this mistake easy to spot because the circular import is visible in the module graph. If you encounter this, the usual fix is to extract the shared piece into common/ or to pass the dependency through app() instead of importing directly.
A feature with its own middleware
Some features need middleware that applies only to their routes. For example, an admin feature might require an authorization check on every endpoint. A feature-based layout lets you attach middleware inside the feature's router:
// src/features/admin/routes.rs
use axum::middleware;
use axum::routing::get;
use axum::Router;
use super::{handlers, middleware::require_admin};
pub fn router() -> Router {
Router::new()
.route("/dashboard", get(handlers::dashboard))
.layer(middleware::from_fn(require_admin))
}
The middleware function lives inside the feature's middleware.rs:
// src/features/admin/middleware.rs
use axum::{
extract::Request,
http::StatusCode,
middleware::Next,
response::Response,
};
pub async fn require_admin(request: Request, next: Next) -> Result<Response, StatusCode> {
let is_admin = request
.headers()
.get("x-admin-token")
.and_then(|v| v.to_str().ok())
.map(|v| v == "secret-token")
.unwrap_or(false);
if is_admin {
Ok(next.run(request).await)
} else {
Err(StatusCode::FORBIDDEN)
}
}
The handler itself is a small function in the feature's handlers.rs:
// src/features/admin/handlers.rs
pub async fn dashboard() -> &'static str {
"Admin dashboard"
}
A request without the header never reaches this handler: the middleware runs first and returns 403 Forbidden. A request with the header x-admin-token: secret-token passes through and receives Admin dashboard. The token check here is only a teaching stand-in - a real application would check a session or a signed credential, not compare against a fixed string in source code.
The middleware is private to the admin feature. Other features do not see it, and it does not affect them. If the admin feature disappears from the application, its middleware disappears with it. In a layer-based layout, admin middleware might live in a global middleware/ directory where its feature ownership is unclear.
The admin mod.rs follows the same pattern:
// src/features/admin/mod.rs
mod handlers;
mod middleware;
mod routes;
pub use routes::router;
features/mod.rs declares the admin feature alongside the others:
// src/features/mod.rs
pub mod admin;
pub mod health;
pub mod orders;
pub mod products;
pub mod users;
And the assembly in lib.rs grows by two lines - the admin feature nested under /admin, and the health feature merged at the root, since its router already registers the full /health path:
// src/lib.rs
mod common;
mod features;
use axum::Router;
use features::users::UserState;
pub fn app() -> Router {
let user_state = UserState::new();
Router::new()
.merge(features::health::router())
.nest("/users", features::users::router(user_state.clone()))
.nest("/products", features::products::router())
.nest("/orders", features::orders::router(user_state))
.nest("/admin", features::admin::router())
}
Migrating from a layer-based layout step by step
If you already have an Axum project organized by layers and want to move to feature folders, the migration does not need to happen all at once. A gradual approach is safer and easier to reason about.
Step 1: Create the features folder and mod file
Create a src/features/ directory and a mod.rs inside it. Do not move any code yet - just declare the module as empty:
// src/features/mod.rs
// Feature modules will be declared here.
In lib.rs, add mod features; alongside the existing mod routes;, mod handlers;, and mod models; declarations. The project still compiles because features is empty.
Step 2: Pick one feature and move its handler plus route together
Choose the smallest feature first - often something like health. Find its handler function in handlers/, its route registration in routes/, and any model types in models/ that belong only to it. Copy those into a new features/health/ folder, adapting the imports and module declarations. Wire the feature router into app() using merge or nest.
Run cargo check after each feature migration. The old layer files can remain in place temporarily; as long as they do not cause name conflicts, the project will compile with both old and new code present.
Step 3: Delete the old code for the migrated feature
Once the new feature folder works and the old handlers/routes are no longer referenced, delete them from the layer directories. Removing dead code is necessary before moving to the next feature, otherwise you end up with two copies of the same logic that can drift apart.
Step 4: Repeat for remaining features
Continue with the next feature - user accounts, then products, then whatever remains. The order does not matter much, but starting with small, self-contained features builds confidence before tackling a large feature with many cross-cutting dependencies.
Step 5: Remove empty layer directories
After all features have been migrated, the routes/, handlers/, and models/ directories should be empty or contain only shared code. Move genuinely shared code into common/, then delete the empty layer directories and their mod.rs files. Update lib.rs to remove the corresponding mod declarations.
A gradual migration avoids the situation of a large codebase being broken for hours while you move hundreds of files. Each step leaves the application in a working state, and cargo check confirms it after every feature.
Name collisions during migration:
While both old and new code exist, the same function name might appear in two places (e.g., handlers::health::health_check and features::health::handlers::health_check). If both are publicly accessible and imported into the same scope, Rust will report a name conflict. Keep the old layer modules as pub(crate) or avoid importing both at the same time by removing old references as you go.
Feature folders inside larger Rust modules
The examples so far have placed feature folders under src/features/, but nothing about the technique requires that exact name. Some projects use src/domain/ or place features directly under src/. The organizational principle matters more than the folder name: group related code by business capability, expose only a router function from each group, and keep shared infrastructure separate.
For a project using src/features/, the features/mod.rs file grows with each new feature:
// src/features/mod.rs
pub mod admin;
pub mod health;
pub mod orders;
pub mod products;
pub mod users;
This file is the table of contents for the application. Reading it tells you every business capability the system implements. A new developer joining the project can open this one file and immediately understand the application's scope. That is the core benefit of feature-based organization.
Common mistakes when splitting by feature
Several mistakes appear repeatedly in beginner projects that adopt feature-based organization.
Making every file in a feature public. Only the router function and the state type need to be pub outside the feature. If handlers, models, and routes are all pub, other features will start importing them directly, and the clean boundary dissolves. Use mod handlers; (not pub mod handlers;) inside the feature's mod.rs, then pub use routes::router; to expose only what outsiders need.
Creating a features/ folder but continuing to put new code in layer directories. A feature split only works if the convention is followed consistently. If you add a new endpoint directly to handlers/ and routes/ because it is "too small" to deserve a feature folder, the project now has two organizational systems, and the feature folders become stale. Every new feature should follow the feature pattern, even if it starts as a single small file.
Over-engineering feature boundaries too early. A feature folder that contains one handler and one route is completely fine. What is not fine is creating submodules for model.rs, handlers.rs, routes.rs, state.rs, and middleware.rs when the feature has three endpoints total. Start with a single mod.rs per feature. Split it into multiple files only when the single file becomes long enough that scrolling through it is painful.
Mixing feature code with shared code in the same folder. If you create features/common/ as if common were a feature, you have reintroduced a layer-based directory inside your feature tree. Shared infrastructure should live in a clearly named shared folder at the same level as features/, not as a pseudo-feature inside it.
Signs the split is working:
When the split is working well, adding a new endpoint to an existing feature requires editing files only inside that feature's folder. Removing a feature means deleting one folder and one pub mod line from features/mod.rs. Adding a new feature means creating one folder and adding one pub mod line. If changes consistently require touching files across multiple top-level directories, the feature boundaries probably need adjustment.
When a feature is too large - splitting into submodules
Sometimes a single feature grows large enough that a flat mod.rs becomes unwieldy. A user feature might include authentication, profile management, password reset, and notifications - all under the same users/ folder. At that point, the feature itself can be split internally.
The natural split is often into subfeatures within the feature:
src/
features/
users/
mod.rs
auth/
mod.rs
profile/
mod.rs
model.rs
state.rs
Each subfeature starts as a single mod.rs, the same way a small feature does. The auth subfeature owns the login route:
// src/features/users/auth/mod.rs
use axum::{routing::get, Router};
use super::UserState;
pub fn router(state: UserState) -> Router {
Router::new()
.route("/login", get(login))
.with_state(state)
}
async fn login() -> &'static str {
"Login page"
}
The profile subfeature owns the route that shows the current users, reading the same shared state:
// src/features/users/profile/mod.rs
use axum::{extract::State, routing::get, Json, Router};
use super::{model::User, UserState};
pub fn router(state: UserState) -> Router {
Router::new()
.route("/me", get(my_profile))
.with_state(state)
}
async fn my_profile(State(state): State<UserState>) -> Json<Vec<User>> {
let users = state.users.lock().unwrap();
Json(users.clone())
}
Both files use super:: paths to reach the parent feature's items: super::UserState for the shared state and super::model::User for the model. That works because a child module can see its parent's private items. The same path written from outside the users feature, as crate::features::users::model::User, would fail to compile, because model is private to the users feature - only the re-exported UserState and router are visible from outside.
The users/mod.rs file composes the subfeature routers:
// src/features/users/mod.rs
mod auth;
mod model;
mod profile;
mod state;
use axum::Router;
pub use state::UserState;
pub fn router(state: UserState) -> Router {
Router::new()
.nest("/auth", auth::router(state.clone()))
.nest("/profile", profile::router(state))
}
The login route becomes /users/auth/login and the profile route becomes /users/profile/me once the parent assembly nests the users feature under /users. Each subfeature has its own routes and handlers, and the parent feature provides the unified public surface. The model and state are shared within the user feature, while subfeatures remain private implementation details.
Do not merge subfeatures that share a path:
Merging the two subfeature routers with .merge instead of nesting them would panic at startup if both defined a route at /, with the same overlapping-route panic as merging two features at the root. Nesting gives each subfeature its own prefix, which is what makes the split safe: the subfeatures can each use short relative paths internally without ever colliding.
This internal split is the same idea applied recursively: group by capability (authentication vs. profile) rather than by layer (all user handlers vs. all user routes). The principle is self-similar at every scale.
Feature-based split and the rest of the project
A feature-based layout does not exist in isolation. The main.rs file remains thin - it starts the Tokio runtime and calls the app() function. lib.rs remains the assembly point. What changes is where the modules declared in lib.rs physically live and how their internal code is organized.
The final picture for a modest Axum project using feature-based organization looks like this:
src/
main.rs
lib.rs
common/
mod.rs
error.rs
features/
mod.rs
health/
mod.rs
users/
mod.rs
routes.rs
handlers.rs
model.rs
state.rs
products/
mod.rs
routes.rs
handlers.rs
model.rs
orders/
mod.rs
routes.rs
handlers.rs
admin/
mod.rs
routes.rs
handlers.rs
middleware.rs
main.rs does not know the features exist. lib.rs knows about the features, but only through their router functions and their public state types. Each feature knows about itself and possibly about common/. The dependency graph is shallow and predictable.
This structure supports the long-term maintainability of the project without imposing rigid rules. If a feature is small, it gets a single mod.rs. If it is large, it gets internal subfolders. The organizing question is always the same: what does the application do? The answer determines the top-level folders.
Choosing between layer-based and feature-based organization
The choice between the two approaches depends on the project's current and expected size. For a learning project or a small microservice with under a dozen endpoints, layer-based organization is simpler. The directories stay small, and the extra ceremony of feature folders adds no benefit.
For applications that implement multiple distinct business capabilities, feature-based organization is usually worth the initial investment. The benefits compound as the codebase grows: easier navigation, clearer ownership, safer refactoring, and a more honest picture of what the system does.
The decision is not permanent. A project can start layer-based and migrate to feature-based when friction appears. The migration steps described earlier are incremental and low-risk. What matters is recognizing the point where layer-based organization stops serving the project, rather than continuing with a structure that fights against the codebase's actual shape.
Summary
Feature-based organization is ultimately about optimizing for the question you most often ask when working in a codebase: "where is the code that does X?" With a layer-based layout, the answer requires searching through several directories and reconstructing relationships in your head. With a feature-based layout, the answer is usually a folder name. This shift in navigation efficiency is the real payoff, and it matters more than any specific file-naming convention.
The pattern also creates natural ownership boundaries. A feature that can be deleted by removing one folder is a feature that the codebase fully understands. The single public router function per feature is the contract that makes this possible. Everything behind that function is detail that can change freely without affecting the rest of the system.
The next step after organizing by feature is often thinking about whether some features are large enough to become separate crates - a topic that builds directly on the module boundaries established here. For now, the feature folders are sufficient: they scale from a single-file health check to a multi-module user system, and they keep the project comprehensible at every stage along the way.