I’m new to rust & axum and trying to wrap my head around setting up a scalable and clean architecture. When running locally, I sometimes notice a lag before the reponse comes in. This could have many reasons, but one thing I’m investigating is how I’m sharing my connection pool.
This is the main.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn error::Error>> {
let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = PgPool::connect(&db_url).await.expect("Failed to connect to database");
let repository_organization = PostgresRepositoryOrganization::new(pool.clone());
let service_organization = OrganizationService::new(Arc::new(repository_organization));
let app = Router::new()
.nest(
"/organizations",
Router::new()
.route("/", post(controller_organization::create_organization))
.layer(from_fn(authenticated_user::auth_middleware)),
)
.layer(Extension(service_organization))
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
Ok(())
}
In my production app, I would have many controllers and services. I often see shared ownership handled with an Arc
or Mutex
smart pointer but am not sure if that is appropriate.
Is there someone here able to tell me if this approach is ok or introduces side effects unknown to me?