How to share reqwest clients in Actix-web server?
Asked Answered
M

1

5

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?

Mathewson answered 5/8, 2021 at 14:10 Comment(1)
can you post your solution. I'm in similar situation but the urls may differ. So I can't create the client and store it in actix's context ahead of server creation.Laktasic
T
12

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)

Thomson answered 5/8, 2021 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.