Performance concerns with cloning an AppState with a DB Pool #2254
-
Hi, my application has some controllers to setup Routers. The only solution I found to share my "global" app state between them is by cloning. Here's the snippet: #[derive(Clone)]
pub struct AppState {
pool: Pool<Postgres>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// ...
let pool = db::db_pool().await?;
let app_state = AppState { pool };
let app = Router::new()
.nest("/users", user_routes(app_state.clone()))
.nest("/dummies", dummy_routes(app_state.clone()));
// ...
}
pub fn user_routes(state: AppState) -> Router {
Router::new()
.route("/", get(get_users))
.with_state(state)
}
pub async fn get_users(state: State<AppState>) -> Result<Json<Vec<User>>, axum::http::StatusCode> {
// ...
}
pub fn dummy_routes(state: AppState) -> Router {
Router::new()
.route("/dummy1", get(dummy))
.with_state(state)
}
pub async fn dummy(state: State<AppState>) -> Result<Json<Vec<User>>, axum::http::StatusCode> {
// ...
} Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Oct 6, 2023
Replies: 1 comment 1 reply
-
You probably don’t need to worry. Cloning a connection pool is usually just bumping a reference count. But I’d recommend you benchmark things if you wanna know more of what the impact is. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
matx64
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You probably don’t need to worry. Cloning a connection pool is usually just bumping a reference count.
But I’d recommend you benchmark things if you wanna know more of what the impact is.