Search code examples
httprustactix-webreqwest

How to share reqwest clients in Actix-web server?


I'm building a web server with Actix-web and one of the methods uses reqwest to make HTTP requests to an external API:

#[get("/foo")]
async fn foo() -> impl Responder {
    let resp = reqwest::get("https://externalapi.com/bar").await?;
    ...
}

To improve the performance, I want to reuse the reqwest Client because it holds a connection pool according to the docs. However, I cannot use Arc to share the client because the docs also has the following statement:

You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally.

How can I share the client across the function calls? Or should I use a different library to create HTTP request inside web servers?


Solution

  • Actually suggestion in the documentation is the solution:

    You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally.

    Simply clone the client.

    Please check the Client definition from the source:

    #[derive(Clone)]
    pub struct Client {
        inner: Arc<ClientRef>,
    }
    

    You can think Client as a reference holder

    The inner type(ClientRef) has wrapped with Arc as the documentation says and Client has Clone implementation, since there is no other fields except inner: Arc<_>, cloning the client will not cause any runtime overhead comparing to wrapping it with Arc by yourself.

    Additionally Client implements Send this means clone of clients can be send across threads, since there is no explicit mutable operation over Client then Mutex is not needed in here. (I said explicit because there might be an interior mutability)