Layer-based split in Axum
Learn how to organize a growing Axum application by separating code into layers such as routing, handlers, models, state, and errors, with complete examples and step-by-step guidance for beginners.
A web application does many different jobs at once. It receives HTTP requests, decides which piece of code should handle each request, reads and writes data, and sends responses back. When you first start an Axum project, putting all of that inside main.rs works fine. But as the application grows, that single file becomes hard to read, hard to change, and hard to test.
Layer-based splitting is a way to organize your code by separating those jobs into distinct folders and modules. Instead of one file that does everything, you create one folder for routing, another for handler functions, another for your data structures, and so on. Each folder becomes a layer of your application.
This page explains what layer-based splitting is, why it helps, and how to apply it to an Axum project step by step. You will start with a minimal example, then build up to a realistic structure with multiple layers and modules.
What a layer is in a backend application
Think of a restaurant. A customer gives an order to a waiter. The waiter writes it down and passes it to the kitchen. The kitchen prepares the food using ingredients from storage. The waiter brings the finished dish back to the customer. Each role has one clear responsibility.
A backend application works in a similar way:
- The router listens for incoming HTTP requests and matches them to the right handler. It is the waiter who takes the order.
- The handler contains the logic for one specific endpoint. It decides what to do with the request and what to send back.
- The model defines the shape of the data the application works with, such as a
Useror anOrder. - The state holds data that must be shared between requests, like a database connection pool, a small object that keeps a few ready-made database connections on hand so handlers do not open a new one for every request.
- The error type describes everything that can go wrong and how to turn those failures into HTTP responses.
Each of these responsibilities is a layer. When you put all routing code in one folder, all handlers in another, and all models in a third, you have a layer-based split.
This is different from keeping everything about one feature together. For example, in a feature-based split you might have a users folder that contains the user routes, user handlers, user models, and user errors all in one place. Layer-based split does the opposite: it groups all route definitions together, all handler functions together, and so on, regardless of which feature they belong to.
Why split an Axum project into layers
The single biggest reason is findability. When a project has twenty routes, a new developer who wants to change one handler should not have to search through one enormous main.rs. They should be able to open the handlers folder and find the relevant file quickly.
Layer-based splitting also makes responsibility boundaries clear. A handler should only contain request‑specific logic. It should not contain the details of how data is stored. By putting models in their own layer, you make it obvious that a handler should use those models instead of defining structs inline.
Another practical benefit is fewer merge conflicts. When several developers work on the same project, they rarely touch the same layer at the same time. One person might add a new route, another might modify a model. With layer‑separated files, those changes live in different files, so version control merges them cleanly.
Finally, a layer‑based structure is easier to test. You can import a handler or a model from its layer without starting the whole server. You can test a piece of logic in isolation because it does not depend on the router being set up.
What about very small projects?:
If your application has fewer than five routes, layer‑based splitting can feel like extra work. That is normal. This structure becomes valuable only when the project starts to grow. You can always start with a single file and split later, as shown later on this page.
The starting point: a single-file Axum app
To understand layer‑based splitting, it helps to first see the problem it solves. Here is a tiny Axum application written entirely inside src/main.rs. It has two routes that return hard‑coded strings.
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
"Welcome to the home page"
}
async fn about() -> &'static str {
"This is the about page"
}
This code works, and for a learning project it is perfect. But imagine adding ten more handlers, a few shared models, an error type, and application state. The file quickly becomes hundreds of lines long. Searching for a specific function becomes difficult. Changing one part risks accidentally affecting another.
The rest of this page shows how to move this code into layers.
The first layer split: routes, handlers, models, state, errors
A common layer‑based structure for a medium‑sized Axum project looks like this:
src/
├── main.rs
├── lib.rs
├── routes/
│ ├── mod.rs
│ └── home.rs
├── handlers/
│ ├── mod.rs
│ └── home.rs
├── models/
│ ├── mod.rs
│ └── user.rs
├── state.rs
└── error.rs
At the top, main.rs is thin: it just calls a function from lib.rs that builds the router. The actual route definitions live in routes/, handler functions in handlers/, data structures in models/, shared state in state.rs, and error handling in error.rs.
What these folders and files are:
The directories routes/, handlers/, and models/ are plain folders that hold Rust modules, and state.rs and error.rs are plain files that hold one module each. Each directory has a mod.rs that declares its submodules.
Let's rebuild the two‑route example using this structure. We will start with empty placeholder content and then fill each layer.
Creating the directory and file structure
Use your file manager or terminal to create the following folders and files inside the src/ directory of your Axum project:
src/
├── main.rs
├── lib.rs
├── routes/
│ ├── mod.rs
│ └── home.rs
├── handlers/
│ ├── mod.rs
│ └── home.rs
├── models/
│ ├── mod.rs
│ └── user.rs
├── state.rs
└── error.rs
If you prefer using the command line, these commands create the structure:
mkdir -p src/routes src/handlers src/models
touch src/lib.rs src/routes/mod.rs src/routes/home.rs src/handlers/mod.rs src/handlers/home.rs src/models/mod.rs src/models/user.rs src/state.rs src/error.rs
For now, models/user.rs, state.rs, and error.rs can be left empty or with minimal placeholder content. The important layers for this example are routes/ and handlers/.
Writing the thin main.rs
The entry point should only start the server. It should not know how to build the router. That responsibility belongs to a function in lib.rs.
// src/main.rs
use axum_layered_split::app;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app()).await.unwrap();
}
The crate name axum_layered_split is just an example. Replace it with your own crate name from Cargo.toml.
Building the router in lib.rs
The lib.rs file declares all the modules and exposes a public app() function that assembles the router from its layers.
// src/lib.rs
pub mod error;
pub mod handlers;
pub mod models;
pub mod routes;
pub mod state;
pub fn app() -> axum::Router {
routes::create_router()
}
Here we declare the modules error, handlers, models, routes, and state. Only routes is used to build the router; the other modules are declared so they are part of the crate and can be referenced later.
Defining routes in the routes layer
The routes/mod.rs file is the main entry point for the routing layer. It defines a function that returns a Router and connects paths to handlers.
// src/routes/mod.rs
use axum::{routing::get, Router};
use crate::handlers;
pub fn create_router() -> Router {
Router::new()
.route("/", get(handlers::home::home))
.route("/about", get(handlers::home::about))
}
Notice the import use crate::handlers;. The routing layer depends on the handlers layer but not the other way around. That is a key property of layer‑based splitting: dependencies flow in one direction, from the outer layers (routing) to the inner layers (handlers, state, models).
The file routes/home.rs is currently unused in this minimal example, and it is not declared in any mod.rs yet, so the compiler ignores it for now. It only becomes part of the crate when a later split declares it. In a larger project, you might split routes by feature inside the routes layer, but still keep all route definitions together. For now, you can leave it empty or include a comment:
// src/routes/home.rs
// This file can hold additional home-related routes if needed.
Writing handlers in the handlers layer
The handlers layer contains the functions that actually process requests. Each handler is a plain async fn that returns something Axum can convert into an HTTP response.
// src/handlers/mod.rs
pub mod home;
// src/handlers/home.rs
pub async fn home() -> &'static str {
"Welcome to the home page"
}
pub async fn about() -> &'static str {
"This is the about page"
}
The handlers/mod.rs file declares the home submodule, making handlers::home::home and handlers::home::about available to the rest of the crate.
This is the complete working example. If you run cargo run, the application behaves exactly like the single‑file version, but the code is now separated into layers.
Everything is working:
Run cargo run and open http://localhost:3000 in a browser. You should see "Welcome to the home page". Visit http://localhost:3000/about and you should see "This is the about page". If both responses appear, your layer split is correct.
What your Cargo.toml needs
The examples from here on use three crates beyond the standard library, so make sure your Cargo.toml lists them before you copy any code:
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
Axum is the web framework. Tokio is the async runtime that runs it, and the full feature set includes the pieces these examples use: net for TcpListener, sync for Mutex, and macros for #[tokio::main]. Serde with the derive feature provides the Serialize and Deserialize derives the models use to turn structs into JSON and back.
Adding more layers: models, state, and errors
The previous example only split routes and handlers. Real applications also need models, shared state, and proper error handling. Let's extend the structure by filling in those layers.
The models layer
Models define the data structures your application uses. Suppose your application handles users. Create a User struct in models/user.rs.
// src/models/user.rs
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct User {
pub id: u64,
pub name: String,
pub email: String,
}
The models/mod.rs file declares this submodule:
// src/models/mod.rs
pub mod user;
Now any handler can import crate::models::user::User to work with user data.
The state layer
Application state is data that must outlive a single request. A common example is a shared in‑memory store or a database connection, a live link your program opens to a database so it can send queries. The state.rs file defines a struct that holds such data.
// src/state.rs
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Clone)]
pub struct AppState {
pub users: Arc<Mutex<Vec<crate::models::user::User>>>,
}
impl AppState {
pub fn new() -> Self {
Self {
users: Arc::new(Mutex::new(Vec::new())),
}
}
}
Two standard library tools make this sharing safe. Arc is a reference-counted pointer that lets several owners share one value; cloning an Arc is cheap because it only bumps a counter instead of copying the data. Mutex is a lock that lets only one piece of code touch the value at a time: a handler calls .lock().await, works with the list, and the lock releases automatically when the guard goes out of scope. Together they let many handlers share one user list without stepping on each other, and #[derive(Clone)] on the struct keeps working because cloning an Arc is always allowed.
This state layer holds a thread‑safe vector of users. Handlers that need to access the state will accept it as an extractor, a piece of Axum that pulls a value out of the request or the shared state and hands it to the handler as a function argument.
The error layer
Error handling in Axum usually involves defining a custom error type that implements IntoResponse. The error.rs file can contain that type.
// src/error.rs
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
pub enum ApiError {
NotFound,
InternalServerError,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
match self {
ApiError::NotFound => StatusCode::NOT_FOUND.into_response(),
ApiError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
}
Now handlers can return Result<T, ApiError> and Axum will automatically convert errors into HTTP responses.
Layer dependencies:
The state.rs file imports from the models layer (crate::models::user::User). That is fine because the dependency runs one way: state uses models, and models never use state. The error layer does not depend on any other layer except Axum's own types. Keeping dependencies one‑directional avoids circular imports - Rust itself allows modules in the same crate to reference each other in a cycle, so nothing in the compiler will stop you; one‑directional dependencies are a design discipline, not a language rule.
Updating the router to use state
Now that the state and models layers exist, we can modify the router to pass the state to handlers that need it. In this example, we keep it simple: the home handler does not need state, but we can add a route that lists users.
First, update routes/mod.rs:
// src/routes/mod.rs
use axum::{routing::get, Router};
use crate::handlers;
use crate::state::AppState;
pub fn create_router() -> Router {
let state = AppState::new();
Router::new()
.route("/", get(handlers::home::home))
.route("/about", get(handlers::home::about))
.route("/users", get(handlers::user::list_users))
.with_state(state)
}
We have added a new route /users that points to handlers::user::list_users, and we use with_state to attach the AppState to the router.
Next, add a user submodule to the handlers layer. Create src/handlers/user.rs:
// src/handlers/user.rs
use axum::extract::State;
use axum::Json;
use crate::state::AppState;
pub async fn list_users(
State(state): State<AppState>,
) -> Result<Json<Vec<crate::models::user::User>>, crate::error::ApiError> {
let users = state.users.lock().await.clone();
Ok(Json(users))
}
This handler extracts the state using Axum's State extractor, locks the shared vector, clones it, and returns it as JSON. It returns a Result so that any future error can be handled by the error layer.
Finally, declare the new handler module in src/handlers/mod.rs:
// src/handlers/mod.rs
pub mod home;
pub mod user;
Run cargo run again. You can now visit http://localhost:3000/users and see an empty JSON array [], because no users have been added yet.
State must be passed to the router:
If you forget .with_state(state) in routes/mod.rs, any handler that expects State<AppState> will fail at compile time. Axum requires that the router knows about the state type before it can pass it to handlers. The compiler error will be long, but it usually points to the router definition.
Breaking the routing layer into multiple files
The routing layer can grow quickly. Instead of one routes/mod.rs with every route, you can split routes by feature while still keeping them in the routing layer. For example, you might have routes/home.rs and routes/user.rs.
Here is how that works.
Create src/routes/home.rs:
// src/routes/home.rs
use axum::{routing::get, Router};
use crate::state::AppState;
pub fn home_routes() -> Router<AppState> {
Router::new()
.route("/", get(crate::handlers::home::home))
.route("/about", get(crate::handlers::home::about))
}
Create src/routes/user.rs:
// src/routes/user.rs
use axum::{routing::get, Router};
use crate::state::AppState;
pub fn user_routes() -> Router<AppState> {
Router::new()
.route("/users", get(crate::handlers::user::list_users))
}
Both functions return Router<AppState> instead of a plain Router, and that return type is load-bearing. A router's state type follows its handlers: list_users needs State<AppState>, so the router built around it becomes a Router<AppState>. home_routes takes the same type even though its handlers need no state, because merge only combines routers that share one state type. If either function declared a plain Router return type, the code would fail to compile with a type mismatch.
Now routes/mod.rs can combine these sub‑routers:
// src/routes/mod.rs
use axum::Router;
use crate::state::AppState;
mod home;
mod user;
pub fn create_router() -> Router {
let state = AppState::new();
Router::new()
.merge(home::home_routes())
.merge(user::user_routes())
.with_state(state)
}
The merge method combines routers that each define their own full paths. This keeps the routing layer organized even as the number of routes grows. Notice that create_router itself still returns a plain Router: .with_state(state) takes a Router<AppState> and hands back a router whose state type is whatever the caller needs, which here is the plain Router that axum::serve accepts. Only a Router<()> implements the Service trait the server needs, so with_state is what bridges the stateful router you build to the stateless router you serve.
Do not use nest for full paths:
If you used nest("/", home::home_routes()), it would panic at startup - Axum 0.8 does not support nesting at the root path ("Nesting at the root is no longer supported. Use merge instead."). nest is designed to add a prefix path. Merging is the correct choice when the sub‑routers already contain their full paths. Using nest incorrectly can lead to double slashes or missing routes.
Step-by-step: converting an existing flat project to layers
If you already have a single‑file Axum application and want to move to a layer‑based structure, follow these steps. The process is sequential: each step must be completed before the next one can succeed.
Step 1: Create the directory structure
Create the folders and files described earlier: routes/, handlers/, models/, state.rs, error.rs, and a lib.rs. Leave the files empty for now.
Step 2: Move handler functions
Cut each async fn handler from main.rs and paste it into the appropriate file under handlers/. For example, a home handler goes into handlers/home.rs. Remember to add the necessary imports. Group multiple related handlers in the same file.
Step 3: Move route definitions
Remove the Router::new() chain from main.rs. Create functions that return routers in the routes/ files. Each route should reference the handler you moved in the previous step using crate::handlers::....
Step 4: Create a public app function in lib.rs
Create lib.rs that declares all modules and provides a pub fn app() -> Router that calls the router‑building function from routes. Import any state or error types as needed.
Step 5: Simplify main.rs
Replace the body of main.rs with just the server startup code that binds a listener and calls axum::serve(listener, app()), with app imported from the library crate. Remove all other logic.
Step 6: Update mod.rs files
Fill each mod.rs with pub mod declarations for its submodules. For example, routes/mod.rs declares mod home; mod user;, and handlers/mod.rs declares pub mod home; pub mod user;.
Step 7: Run cargo check and cargo run
Run cargo check to see if there are any missing imports or module errors. Fix them one by one. Then run cargo run and test your endpoints. If everything works, the conversion is complete.
Conversion complete:
After finishing these steps, your application should behave exactly as before, but the code is now organized by layers. This is the moment to commit your changes so you have a clean baseline for future work.
Choosing between nested modules and separate directories
Rust gives you two main ways to organize layers: separate directories with mod.rs files, as shown above, or nested modules inside a single file. Both approaches produce the same runtime behavior; the difference is how you navigate the source code.
The directory approach is better when you expect many files. For example, a handlers/ folder with ten handler files is easier to browse than one handlers.rs file with ten modules inside it.
The single‑file approach can be convenient for small projects. You might have a handlers.rs that contains:
// src/handlers.rs
pub mod home;
pub mod user;
Then each handlers/home.rs and handlers/user.rs are separate files, but the module declaration is centralized.
Alternatively, you can put everything in one file using inline modules:
// src/handlers.rs
pub mod home {
pub async fn home() -> &'static str {
"Welcome to the home page"
}
}
This avoids extra files but becomes unreadable as the number of handlers grows. For a layer‑based split meant to scale, the directory approach is usually the better choice.
Which one should you pick?:
If your project already uses separate directories, continue with that structure. Consistency matters more than the specific choice. Do not mix the two styles in the same project unless you have a strong reason.
Common mistakes beginners make with layer‑based splitting
Layer‑based splitting is straightforward, but a few errors come up repeatedly.
Creating too many layers too early. Adding a services/ layer, a repositories/ layer, and a utils/ layer before you have more than a handful of routes leads to many nearly empty files. Start with the layers you actually need: routes, handlers, models, state, and errors. Add more layers only when a handler becomes so complex that its logic clearly belongs elsewhere.
Putting business logic inside handlers. The handler should extract data from the request, call a function that does the real work, and return the result. If you find yourself writing loops, database queries, or complex conditional logic inside a handler, that logic should move to a lower layer, such as a service module or a model method. Layer‑based splitting is not just about folders; it is about keeping each layer's responsibility narrow.
Circular dependencies between layers. The models layer should not import from handlers, and the handlers layer should not import from routes. Dependencies should flow from outer layers to inner layers: routes → handlers → state → models, with the error layer standing on its own. Handlers depend on state and models, and state depends on models, so models sit at the innermost end. Rust's module system will not catch circular imports - modules in the same crate may reference each other in a cycle and still compile - so you have to avoid them by planning ahead.
Forgetting to declare modules in mod.rs. After creating a new file inside a layer folder, you must add a pub mod filename; line to the corresponding mod.rs. Otherwise the file is silently ignored, and any code that tries to use it fails with an unresolved import error (E0432).
The most common mistake:
The most frequent error is missing with_state when a handler expects State<AppState>. The compiler error is long and can be confusing. Always check that your router includes .with_state(...) and that the state type matches exactly what the handler expects.
A realistic layer‑based project example
Let's bring everything together with a slightly larger example. This application has a home page, a user list, and a route to create a new user. It uses all the layers we have discussed. Every file below was built piece by piece in the sections above, including the Router<AppState> return types on the route builders and the Cargo.toml dependencies; this is the same code assembled in one place so you can compare it with your own project.
Here is the final structure:
src/
├── main.rs
├── lib.rs
├── routes/
│ ├── mod.rs
│ ├── home.rs
│ └── user.rs
├── handlers/
│ ├── mod.rs
│ ├── home.rs
│ └── user.rs
├── models/
│ ├── mod.rs
│ └── user.rs
├── state.rs
└── error.rs
src/main.rs
// src/main.rs
use axum_layered_split::app;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app()).await.unwrap();
}
src/lib.rs
// src/lib.rs
pub mod error;
pub mod handlers;
pub mod models;
pub mod routes;
pub mod state;
pub fn app() -> axum::Router {
routes::create_router()
}
src/routes/mod.rs
// src/routes/mod.rs
use axum::Router;
use crate::state::AppState;
mod home;
mod user;
pub fn create_router() -> Router {
let state = AppState::new();
Router::new()
.merge(home::home_routes())
.merge(user::user_routes())
.with_state(state)
}
src/routes/home.rs
// src/routes/home.rs
use axum::{routing::get, Router};
use crate::state::AppState;
pub fn home_routes() -> Router<AppState> {
Router::new()
.route("/", get(crate::handlers::home::home))
.route("/about", get(crate::handlers::home::about))
}
src/routes/user.rs
// src/routes/user.rs
use axum::{routing::{get, post}, Router};
use crate::state::AppState;
pub fn user_routes() -> Router<AppState> {
Router::new()
.route("/users", get(crate::handlers::user::list_users))
.route("/users", post(crate::handlers::user::create_user))
}
src/handlers/mod.rs
// src/handlers/mod.rs
pub mod home;
pub mod user;
src/handlers/home.rs
// src/handlers/home.rs
pub async fn home() -> &'static str {
"Welcome to the home page"
}
pub async fn about() -> &'static str {
"This is the about page"
}
src/handlers/user.rs
// src/handlers/user.rs
use axum::{extract::State, Json};
use crate::error::ApiError;
use crate::models::user::{CreateUser, User};
use crate::state::AppState;
pub async fn list_users(
State(state): State<AppState>,
) -> Result<Json<Vec<User>>, ApiError> {
let users = state.users.lock().await.clone();
Ok(Json(users))
}
pub async fn create_user(
State(state): State<AppState>,
Json(input): Json<CreateUser>,
) -> Result<Json<User>, ApiError> {
let mut users = state.users.lock().await;
let new_user = User {
id: (users.len() as u64) + 1,
name: input.name,
email: input.email,
};
users.push(new_user.clone());
Ok(Json(new_user))
}
src/models/mod.rs
// src/models/mod.rs
pub mod user;
src/models/user.rs
// src/models/user.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,
}
src/state.rs
// src/state.rs
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::models::user::User;
#[derive(Clone)]
pub struct AppState {
pub users: Arc<Mutex<Vec<User>>>,
}
impl AppState {
pub fn new() -> Self {
Self {
users: Arc::new(Mutex::new(Vec::new())),
}
}
}
src/error.rs
// src/error.rs
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
pub enum ApiError {
NotFound,
InternalServerError,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
match self {
ApiError::NotFound => StatusCode::NOT_FOUND.into_response(),
ApiError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
}
Run cargo run and test these endpoints:
GET /→ "Welcome to the home page"GET /about→ "This is the about page"GET /users→[]POST /userswith JSON body{"name": "Alice", "email": "alice@example.com"}→ returns the new user with an ID, and subsequentGET /usersshows the user in the list.
This structure scales:
Adding a new feature, such as orders, would involve adding routes/order.rs, handlers/order.rs, and maybe models/order.rs. All existing layers remain untouched except for adding the new submodule to each mod.rs. That is the real value of layer‑based splitting.
When layer-based split is not the right choice
Layer‑based splitting is a convention, not a law. For very small projects, it can add more files than necessary. If you are building a tiny tool or a prototype that will be thrown away, keeping everything in main.rs is perfectly fine.
There is also a competing convention called feature‑based split, where you group all code related to one feature (users, orders, products) into one folder. The choice between layer‑based and feature‑based often comes down to team preference and how the project is expected to grow. This page focuses on layer‑based because it is a natural extension of the conventional layout: the folders you already have are layers, so the split is a small step from where the project already stands.
Do not mix the two styles carelessly:
Mixing layer‑based and feature‑based splits within the same project can confuse developers. If you choose layer‑based, keep all routes in one folder, all handlers in another, and so on, even if some files are large. If you later decide feature‑based is better, convert the whole project consistently.
Summary
Layer‑based splitting is a way to organize an Axum project by technical responsibility. Routing code goes in a routes/ folder, handler functions in handlers/, data structures in models/, shared state in state.rs, and error types in error.rs. Each layer depends only on layers below it, which keeps the codebase modular and easier to navigate.
The most important insight from this page is that the split is not about file count; it is about making each piece of code easy to find, easy to change, and easy to test. Start with the layers you need, add more only when complexity demands it, and keep dependencies flowing in one direction.
This structure directly supports the next steps in scaling an Axum application: once you have a clean layer‑based foundation, you can decide whether a feature‑based split or domain folders better suit your project as it continues to grow.