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?
Assuming your PgPool
is from sqlx, it says:
impl<DB> Clone for Pool<DB> where DB: Database
Returns a new Pool tied to the same shared connection pool.
So there should be no issue with it: the public Pool
object is a wrapper around an Arc
to the actual pool of connections:
pub struct Pool<DB: Database>(pub(crate) Arc<PoolInner<DB>>);
One possibility might be that you don't have a minimum number of connections in the pool (I don't know how sqlx defaults), so the pool waits until the first request to actually connect to the database, which causes some lag for the first client.
Although do you also compile in release
mode? Compiling in debug is faster, but the program can be much slower, and that can well account for the lag you're seeing.