Cargo Workspaces for Axum Projects
Learn how to organize an Axum application into multiple Rust crates using Cargo workspaces, and when this structure makes sense for larger projects.
When an Axum application grows beyond a handful of files, you start looking for ways to split the code into manageable pieces. Up to this point, you have seen how to organize a single crate into modules and directories. But there comes a moment when separate crates make more sense than separate modules. That is where Cargo workspaces enter the picture.
A Cargo workspace is a collection of related Rust packages - called crates - that share one top-level Cargo.toml file and one build directory. This lets you build, test, and manage multiple crates as a single unit while keeping their code physically separated. For an Axum project, a workspace might hold one crate for the HTTP layer, another for business logic, and a third for database access.
What a Cargo Workspace Actually Is
Before workspaces, every Rust project you created was a single package: one Cargo.toml, one src directory, one output binary or library. That package is called a crate in Rust terminology. A workspace is simply a folder that contains several crates, all listed in a root Cargo.toml. The root file tells Cargo, "These subfolders are all part of the same project. Build them together, share dependencies, and put all compiled artifacts in one place."
Think of a workspace like a shopping mall. Each store is an independent business (a crate) with its own lease (its own Cargo.toml), but they all share the same building, parking lot, and utilities (the shared target directory and dependency resolution). Shoppers can walk from one store to another; in the same way, crates can use each other's public items.
The mental model that helps beginners: a workspace is not a type of crate; it is a container for crates. You do not write code in the workspace root. You write code inside the member crates, and the root Cargo.toml only points to them.
Why Axum Projects Benefit from Workspaces
A single Axum crate can hold everything - handlers, extractors, database pools, configuration. That is fine for small applications and for learning. But as the project grows, several problems appear:
- Everything recompiles together. Change one line in a utility function, and the whole app rebuilds. In a workspace, each crate compiles independently, so only the affected parts rebuild.
- No clear boundaries. With modules, every file can see every other module if you make it
pub. Workspaces force you to declare explicit dependencies between crates, creating cleaner architecture. - Reuse is hard. If you want to share a data model between your web server and a background worker, you would have to duplicate code or bend module paths. A workspace lets both binaries depend on a shared library crate.
- Testing isolation. You can run
cargo test -p my_crateto test only one part of the project, instead of the entire application.
In an Axum context, a common workspace split is:
api- the binary crate that starts the Axum server and defines routes.domain- a library crate with business logic, data models, and validation, independent of HTTP.db- a library crate that handles database connections and queries.config- a library crate that loads environment variables and configuration files.
Each of these is a separate crate with a clear responsibility. The api crate depends on domain, db, and config. The domain crate depends only on db if needed, and so on.
Your First Workspace - A Minimal Two-Crate Example
Before adding Axum, let's create a workspace with two small crates to see the mechanics. We will make a library crate called greetings that provides a function, and a binary crate called hello that calls it.
Create a new folder anywhere on your computer and call it workspace-demo. Inside it, create the root Cargo.toml:
# workspace-demo/Cargo.toml
[workspace]
members = [
"greetings",
"hello",
]
This root file has no [package] section. It only declares the workspace and lists which folders are members. Each member folder will have its own Cargo.toml.
Now create the greetings crate. Inside workspace-demo/greetings, place a Cargo.toml:
# workspace-demo/greetings/Cargo.toml
[package]
name = "greetings"
version = "0.1.0"
edition = "2021"
[dependencies]
And a source file src/lib.rs:
// workspace-demo/greetings/src/lib.rs
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
This crate is a library because it has a lib.rs. It exports one public function.
Next, the hello binary crate. Inside workspace-demo/hello, create Cargo.toml:
# workspace-demo/hello/Cargo.toml
[package]
name = "hello"
version = "0.1.0"
edition = "2021"
[dependencies]
greetings = { path = "../greetings" }
Notice the dependency declaration. Instead of pulling greetings from crates.io, we point to it using a relative path. This tells Cargo to use the local crate inside the workspace.
Now create src/main.rs:
// workspace-demo/hello/src/main.rs
use greetings::greet;
fn main() {
println!("{}", greet("World"));
}
Now go back to the workspace-demo folder and run:
cargo run -p hello
The -p hello flag tells Cargo which package to run, since there is no default package at the root. You should see:
Hello, World!
From the root, you can also build everything with cargo build, or run tests across all crates with cargo test --workspace.
This tiny example shows the three essential pieces of a workspace:
- A root
Cargo.tomlwith[workspace]andmembers. - At least two member crates, each with its own
Cargo.toml. - Path dependencies between crates when they need to use each other.
Two Ways to Create a Workspace
You can set up a workspace manually, as we just did, or let Cargo generate the structure for you. Both approaches lead to the same result, so choose whichever feels more natural.
Manually create the folders and files exactly as shown above. You have full control over the names and can start adding your own crates one by one.
Either way, the end result is the same directory layout.
Adding Axum to a Workspace
Now let's apply workspaces to a real Axum application. We will create a workspace with two crates: a library crate app-core that defines a shared data model, and a binary crate api that starts an Axum server and uses that model.
Create a new folder called axum-workspace. Inside it, the root Cargo.toml:
# axum-workspace/Cargo.toml
[workspace]
members = ["app-core", "api"]
Now create app-core. Its Cargo.toml:
# axum-workspace/app-core/Cargo.toml
[package]
name = "app-core"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
The serde crate is used for serialization, which will be needed when Axum returns the model as JSON. The src/lib.rs:
// axum-workspace/app-core/src/lib.rs
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
pub id: u64,
pub name: String,
}
pub fn get_sample_user() -> User {
User {
id: 1,
name: "Alice".to_string(),
}
}
This crate has no knowledge of HTTP or Axum. It just defines data and a function to get a sample user. That separation is a key benefit of workspaces.
Now the api crate. Its Cargo.toml:
# axum-workspace/api/Cargo.toml
[package]
name = "api"
version = "0.1.0"
edition = "2021"
[dependencies]
app-core = { path = "../app-core" }
axum = "0.8"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
Notice how api depends on app-core via a path, and it also pulls in Axum and Tokio. The src/main.rs:
// axum-workspace/api/src/main.rs
use app_core::{get_sample_user, User};
use axum::{routing::get, Json, Router};
async fn user_handler() -> Json<User> {
Json(get_sample_user())
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/user", get(user_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
From the workspace root, run:
cargo run -p api
Then open http://127.0.0.1:3000/user in a browser. You should see:
{"id":1,"name":"Alice"}
This example demonstrates the core value: app-core can be reused by other binaries later (like a CLI tool or a test runner) without duplicating the User struct. The Axum server is just one consumer of that crate.
Centralizing Dependencies with Workspace Dependencies
In the previous example, api has its own axum and tokio versions. If you later add another crate that also uses axum, you might end up with two different versions, causing duplication and potential conflicts. A workspace-level [workspace.dependencies] section solves this by defining versions once and letting member crates refer to them.
Modify the root Cargo.toml:
# axum-workspace/Cargo.toml
[workspace]
members = ["app-core", "api"]
[workspace.dependencies]
axum = "0.8"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
app-core = { path = "app-core" }
Now update app-core/Cargo.toml:
# axum-workspace/app-core/Cargo.toml
[package]
name = "app-core"
version = "0.1.0"
edition = "2021"
[dependencies]
serde.workspace = true
And api/Cargo.toml:
# axum-workspace/api/Cargo.toml
[package]
name = "api"
version = "0.1.0"
edition = "2021"
[dependencies]
app-core.workspace = true
axum.workspace = true
tokio.workspace = true
serde_json.workspace = true
Now every crate uses the exact same versions without repeating them. If you need to upgrade Axum, you change one line in the root file instead of every member's Cargo.toml.
Consistency guaranteed:
Using workspace dependencies is the recommended approach as soon as you have two or more crates that share any external crate. It prevents version skew and makes upgrades trivial.
Converting an Existing Single-Crate Axum Project into a Workspace
Suppose you already have a working Axum app in a single crate, and you want to split it into workspaces. The process is mechanical but requires care with paths and visibility.
Here is a step-by-step guide. We will assume your current project has a src/main.rs with routes, a src/models.rs, and a src/handlers.rs. We will move models and handlers into a library crate called app-core, and leave only the server startup in the binary crate api.
Step 1: Move the binary into an api subfolder
Create a folder called api. Move your existing src folder and your original Cargo.toml into that api folder. The api/Cargo.toml will become the binary crate's manifest. It should look like this after moving:
# api/Cargo.toml (was your original Cargo.toml)
[package]
name = "my-axum-app" # keep the original name
version = "0.1.0"
edition = "2021"
[dependencies]
# your existing dependencies
axum = "0.8"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
At this point, the api folder contains your entire old project, unchanged. Do this move first, because the next step replaces the Cargo.toml at the project root - the original must already be safely inside api/ by then.
Step 2: Create the workspace root
Now write a new root Cargo.toml in the folder that used to hold your project. It declares the workspace and lists the api crate as its first member:
# Cargo.toml (root, new)
[workspace]
members = ["api"]
This file has no [package] section. It only points at the member crates.
Step 3: Create the app-core library crate
Create another folder called app-core. Inside it, create Cargo.toml:
# app-core/Cargo.toml
[package]
name = "app-core"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
axum = "0.8"
The axum dependency belongs here because the moved handler file uses Axum types such as Json. A library crate needs every crate its own code imports, even if the binary crate already depends on the same crate.
Then move your models.rs and handlers.rs from api/src/ into app-core/src/. Create app-core/src/lib.rs that declares these modules so the binary crate can use them:
// app-core/src/lib.rs
pub mod models;
pub mod handlers;
In your moved models.rs and handlers.rs, paths that start with crate:: still work, because they now point at the app-core crate root instead of the old binary crate root. Only paths that named the old binary crate's own modules need updating.
Step 4: Add app-core as a dependency of api
Edit api/Cargo.toml to include a path dependency on app-core, and add "app-core" to the members list in the root Cargo.toml so workspace-wide commands cover it:
# api/Cargo.toml
[dependencies]
app-core = { path = "../app-core" }
# keep existing dependencies
# Cargo.toml (root)
[workspace]
members = ["api", "app-core"]
Update api/src/main.rs to use app_core instead of the old module paths. If you had mod models; in main.rs, remove it and instead import from the library crate. A complete main.rs after the move looks like this:
// api/src/main.rs
use app_core::handlers::user_handler;
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/user", get(user_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The package is named app-core, so the crate is imported as app_core - Rust turns the hyphen into an underscore in code. If main.rs also uses the User model directly, import it as use app_core::models::User;. Do not name the library crate core: that name collides with the standard library's own core crate and breaks macros such as #[tokio::main].
Step 5: Build and fix errors
From the workspace root, run:
cargo build
You will likely see errors about missing imports or visibility. Go through them one by one. Ensure that items you use from app-core are marked pub in the library crate. After fixing, run cargo run -p my-axum-app to start the server and verify everything works.
Visibility is the most common stumbling block:
When moving code from a single crate to a library crate, items that were previously accessible because they were in the same crate are no longer accessible unless marked pub. You must explicitly make structs, functions, and modules public in the library crate for the binary crate to use them.
A More Realistic Three-Crate Axum Workspace
Let's look at a slightly larger example that includes a database access crate. This mirrors what you might see in a production Axum application.
The workspace root Cargo.toml:
# Cargo.toml (root)
[workspace]
members = ["api", "domain", "db"]
resolver = "2"
[workspace.dependencies]
axum = "0.8"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
domain = { path = "domain" }
db = { path = "db" }
The domain crate holds the business entities. Its Cargo.toml:
# domain/Cargo.toml
[package]
name = "domain"
version = "0.1.0"
edition = "2021"
[dependencies]
serde.workspace = true
sqlx.workspace = true
And domain/src/lib.rs:
// domain/src/lib.rs
use serde::Serialize;
#[derive(Serialize, Debug, Clone, sqlx::FromRow)]
pub struct Order {
pub id: i64,
pub customer_name: String,
pub total_cents: i64,
}
The db crate handles persistence. It depends on domain and sqlx:
# db/Cargo.toml
[package]
name = "db"
version = "0.1.0"
edition = "2021"
[dependencies]
domain.workspace = true
sqlx.workspace = true
tokio.workspace = true
Its src/lib.rs shows a function to fetch an order:
// db/src/lib.rs
use domain::Order;
use sqlx::PgPool;
pub async fn get_order(pool: &PgPool, id: i64) -> Result<Order, sqlx::Error> {
let row = sqlx::query_as!(
Order,
"SELECT id, customer_name, total_cents FROM orders WHERE id = $1",
id
)
.fetch_one(pool)
.await?;
Ok(row)
}
The api crate ties it together:
# api/Cargo.toml
[package]
name = "api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum.workspace = true
tokio.workspace = true
serde_json.workspace = true
sqlx.workspace = true
domain.workspace = true
db.workspace = true
api/src/main.rs:
// api/src/main.rs
use axum::{
extract::State,
routing::get,
Router,
Json,
};
use domain::Order;
use db;
use sqlx::PgPool;
#[derive(Clone)]
struct AppState {
pool: PgPool,
}
async fn order_handler(
State(state): State<AppState>,
axum::extract::Path(id): axum::extract::Path<i64>,
) -> Result<Json<Order>, axum::http::StatusCode> {
match db::get_order(&state.pool, id).await {
Ok(order) => Ok(Json(order)),
Err(_) => Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
}
}
#[tokio::main]
async fn main() {
let pool = PgPool::connect("postgres://user:pass@localhost/db")
.await
.expect("Failed to connect to database");
let state = AppState { pool };
let app = Router::new()
.route("/orders/{id}", get(order_handler))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This structure keeps the HTTP layer (api) free of SQL queries, the database layer (db) free of HTTP concerns, and the domain layer (domain) independent of both. If you later need a CLI to generate reports from the database, it can depend on domain and db without pulling in Axum.
Building, Testing, and Running Workspace Commands
When you are inside a workspace, Cargo commands behave slightly differently because there may be multiple packages. Here are the most useful commands:
cargo build- builds all packages in the workspace.cargo build -p api- builds only theapipackage.cargo run -p api- runs theapibinary. You must specify the package if there is more than one binary.cargo test- runs tests for the current package (if you are inside a member folder) or for all packages (if run from the root, but it's clearer to usecargo test --workspace).cargo test -p domain- runs tests only for thedomaincrate.cargo check --workspace- quickly type-checks all crates without producing binaries, useful for fast feedback.cargo clippy --workspace- runs the linter across all crates.
If you are inside a member crate directory, cargo build will only build that crate and its dependencies within the workspace. To force building everything, use --workspace.
The -p flag is your friend:
Always remember -p (or --package) when you want to target a specific crate. Without it, commands run from the workspace root may fail because Cargo does not know which package you mean if there is more than one binary.
Common Mistakes and How to Avoid Them
Workspaces are simple once you understand them, but beginners often hit a few recurring problems.
Forgetting to add a crate to members
If you create a new folder with a Cargo.toml but forget to list it in the root [workspace] members, Cargo may still pick it up automatically when another member depends on it through a path dependency - path dependencies inside the workspace folder become members on their own. So a missing entry often produces no error at all, which makes it easy to miss. The entry still matters: it is what makes the crate visible to workspace-wide commands and to cargo run -p <name> when nothing depends on it yet. List every member explicitly, even when the build seems to work without it.
Wrong relative paths in dependencies
Path dependencies are relative to the Cargo.toml file that declares them, not to the workspace root. If your api/Cargo.toml has app-core = { path = "../app-core" }, that is correct because app-core is one level up from api. But if you later move the crate, you must update the path. A common error is writing path = "app-core" when the crate is at the same level as the workspace root, not inside the dependent crate's folder.
Mixing versions of the same dependency
Without workspace dependencies, two crates might use different versions of tokio or axum. Cargo will happily build both, but you will end up with duplicated code and potentially subtle incompatibilities if types from one version are passed to functions expecting the other. Use [workspace.dependencies] to enforce a single version.
Circular dependencies
Crate A cannot depend on crate B if crate B also depends on crate A. Cargo will reject this with an error about cyclic dependencies. Design your crate graph as a directed acyclic graph: lower-level crates (like domain) should not depend on higher-level crates (like api). If you find yourself needing a circular dependency, rethink the boundaries.
Inconsistent feature flags
If you centralize tokio with features = ["full"] in the workspace, every crate that uses tokio.workspace = true gets those features. If one crate needs an extra feature that another doesn't, you can still add it in that crate's Cargo.toml by adding features = [...] alongside the .workspace = true line. Features add together - the member gets the workspace features plus its own - so you cannot use this to remove a feature the workspace turns on. Keep the workspace list as the shared baseline and add per-crate extras sparingly.
Visibility errors after splitting:
After moving code from a single crate into a library crate, your binary crate will fail to compile if you forget to add pub to items you use. This is not a workspace issue per se, but it is the most common error you'll see during the conversion.
When Not to Use a Workspace
Workspaces add a layer of indirection. For a tiny Axum app with one developer and a handful of routes, a single crate with modules is perfectly fine. Introducing multiple crates too early can slow you down because you must manage path dependencies, visibility, and multiple Cargo.toml files.
A good rule of thumb: start with a single crate. When you find yourself duplicating logic across binaries, or when compile times become painful, or when you want to share code between the web server and other tools, that is the signal to introduce a workspace. Do not create a workspace just because it feels more "professional." Simplicity is a feature.
Summary
Cargo workspaces let you split an Axum application into multiple crates that share a common build system and dependency resolution. The root Cargo.toml declares the members, and each member has its own Cargo.toml and source tree. Path dependencies connect the crates, and workspace dependencies keep versions consistent.
The most important insight: a workspace does not change what your code does; it changes how the code is organized and built. You still write the same Axum handlers and extractors. The workspace simply gives you a clear boundary between different concerns - HTTP, domain logic, database, configuration - so that each part can evolve independently.
Once you are comfortable with workspaces, the next structural question you'll face is whether to go further and split your application into separate services that run in different processes. That decision is about deployment and scaling, not just code organization, and involves a different set of trade-offs. For now, mastering workspaces gives you a powerful tool for keeping a growing Rust codebase manageable.