Is it safe to use a Mutex for an SMTP client connection?
⚓ Rust 📅 2025-12-07 👤 surdeus 👁️ 1Hello!
For my Actix-Web server, there is a request handler send_verification_code that sends a verification code to a user and then redirects them to another page where they'll need to enter said code.
Initially, I made it such that during each request, an SMTP client connection would be made, and then I would work on sending the email. However, I noticed that the total time for both creating the connection and then sending an email was pretty long, so there would have been a delay in redirecting the user.
As a result, I placed that connection into the application's data wrapper as an Arc<Mutex<>>, and I would then call it as a parameter in send_verification_code - thankfully, that did split the time by half, since the time taken to make the connection would have already been offloaded when the server was starting up:
// Me calling the SMTP client connection
state.smtp_client.lock().await.send(message_builder).await
But then I started to worry about something.
From what I understand so far, the lock method may delay a process until the wrapped resource is available. Consequently, although Kubernetes may help with scaling up and stuff, there could be cases where some threads are trying to access that connection, but due to another currently using it (which could probably be exacerbated if there is a user at the other side of the world), things could get pretty slow real quick.
I'm not sure if my concern is valid (ChatGPT said it was, but I was still skeptical), but I thought one way of getting around this was to first redirect the user to the other page and then send them the verification code. (I would then no longer place the connection in the application's data wrapper, and thus direct that waiting time once the user is already redirected)
Any insights would be appreciated, thanks.
3 posts - 3 participants
🏷️ Rust_feed