1. Designing the Shared Web State
In Axum, shared state is managed using anAppState struct wrapped in an Arc. Since our framework’s Repository is thread-safe and designed to handle concurrent operations, you can easily share it across your web handlers:
2. Defining Request Payloads
We define simple, serializable JSON payload structs representing the input arguments for each of our HTTP operations:3. Creating Web Handlers
Our web handlers receive the sharedAppState, parse incoming JSON payloads, extract URL path parameters, and invoke the repository’s execute or load methods.
Handling Commands (The Write Path)
4. Translating Errors to HTTP Status Codes
To prevent leakage of internal system details and provide high-fidelity API responses, map typed domain errors (BankAccountError) and repository errors (RepositoryError) to application responses at the web boundary. See Error Handling and Transport Mapping for the full REST, Leptos server-function, Spin gRPC, and tracing contract.
5. Assembling the Router
Finally, we configure the Axum router, inject our state, and run the server usingtokio:
6. Real-World Architectural Advantages
By building your API around this architecture, you gain three massive production advantages:- Lightweight Requests: Endpoints do not hold heavy, database-level locking transactions. Command validation is executed inside in-memory loops, and writes are completed as simple, ultra-fast SQL appends.
- Horizontal Scaling: Since servers are completely stateless and rely on Optimistic Concurrency Control, you can scale your application servers horizontally without worrying about complex distributed locking mechanisms.
- Idempotent Retry Safety: If a client receives a
409 Conflict(concurrency collision), the client or API gateway can simply and safely retry the request instantly without risk of corrupting database state.