Confirmation email task - sending mail in the background after signup
Learn how a signup handler answers at once while a spawned task sends the confirmation email, what owned data the task needs, and how the simulated send works without real mail credentials
A signup form asks for a name and an email address, and the user expects a confirmation email to arrive. Sending that email takes time: the server must reach the mail service, wait for it to accept the message, and handle a slow or failing connection. The user does not need to wait for any of that. The handler can answer "welcome" at once and let a background task send the email.
Where This Fits
Earlier pages showed the shape in the abstract: spawn slow work, answer with 202, let the work finish after the response. This page applies that shape to the most common real example of it, the welcome email after signup. The pattern is the same, and the new material is the detail that makes it realistic: what data the task needs, how the send is simulated without a real mail service, and what happens when the send fails.
Think of a shop that takes your order at the counter and posts the receipt to you afterwards. The person at the counter does not wait for the postman. They hand you your bag, and the receipt travels separately. The signup handler is the counter, the email is the receipt, and the spawned task is the postman.
The Smallest Working Version
A signup route that spawns a simulated email send and answers with 201 Created at once:
use axum::{http::StatusCode, routing::post, Json, Router};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::time::sleep;
#[derive(Deserialize)]
struct Signup {
name: String,
email: String,
}
#[derive(Serialize)]
struct SignupReply {
message: String,
}
async fn send_confirmation_email(email: String, name: String) -> Result<(), String> {
sleep(Duration::from_millis(500)).await;
if email.contains('@') {
println!("sent confirmation email to {} ({})", email, name);
Ok(())
} else {
Err(format!("bad address: {}", email))
}
}
async fn signup(Json(body): Json<Signup>) -> (StatusCode, Json<SignupReply>) {
let email = body.email.clone();
let name = body.name.clone();
tokio::spawn(async move {
match send_confirmation_email(email, name).await {
Ok(()) => println!("confirmation email delivered"),
Err(error) => eprintln!("confirmation email failed: {}", error),
}
});
(
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/signup", post(signup));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The Cargo.toml file needs Axum, Tokio with the full feature set, and serde for the JSON body:
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Run the server, then sign up from a second terminal:
curl -X POST -H "content-type: application/json" -d '{"name":"Asha","email":"asha@example.com"}' http://127.0.0.1:3000/signup
The response comes back at once:
{"message":"welcome, Asha"}
Half a second later, the server terminal shows the send:
sent confirmation email to asha@example.com (Asha)
confirmation email delivered
The client got its welcome before the email was sent, and the email was still sent. That ordering is the whole page.
Working Setup:
If the response arrives at once and the sent confirmation email line appears in the server terminal half a second later, the pattern works. The signup answered without waiting for the mail.
The Send Is Simulated on Purpose
No real email is sent anywhere on this page. The send_confirmation_email function sleeps for half a second and prints a line, which stands in for the real work of talking to a mail service. The sleep mimics the network delay, and the printout mimics the delivery. The function returns Ok when the address contains an @ and Err when it does not, which mimics a mail service accepting or rejecting an address.
This is deliberate. Sending real email needs an account with a mail service, a password or an API key, and a server that is allowed to reach the outside world. None of that belongs in a learning example, and none of it is needed to learn the pattern. The shape of the code is identical either way: the handler spawns a task, the task calls a send function, and the result is logged inside the task. Swapping the simulated function for a real mail client later changes one function, not the handler.
No Mail Credentials Needed:
Nothing on this page needs an SMTP server, a mail password, or a real mail service account. The simulated send stands in for the real one, and the pattern around it - spawn, own the data, log the result - is the same with a real mail client in place of the simulation.
Understanding the Handler Line by Line
The handler has three moves: take the data out of the request, hand copies of it to the task, and answer. Each move matters for a different reason.
Reading the signup body
async fn signup(Json(body): Json<Signup>) -> (StatusCode, Json<SignupReply>) {
The Json<Signup> extractor reads the request body and parses it as JSON into a Signup struct. Signup has two fields, name and email, both String, and Deserialize lets serde fill them from the JSON keys. If the body is not valid JSON, or a field is missing, Axum rejects the request before the handler runs, with a 400 or 422 status. The handler only ever sees a complete signup.
Cloning the data for the task
let email = body.email.clone();
let name = body.name.clone();
The task must own the data it uses, because it can outlive the handler. body belongs to the handler, and the handler ends when it returns its response. Cloning the two strings gives the task its own copies, and the handler keeps the originals for its reply. This is the 'static rule from the spawn page, applied to real data: the email address and the name travel into the task as owned values, not as borrows.
The clone happens before the spawn call, in the handler, so the intent is visible: these two values are the task's inputs. When a task needs more data - a user id, a confirmation token, a language preference - each one is cloned the same way, on its own line, before the spawn.
Spawning the send and logging the result
tokio::spawn(async move {
match send_confirmation_email(email, name).await {
Ok(()) => println!("confirmation email delivered"),
Err(error) => eprintln!("confirmation email failed: {}", error),
}
});
The task awaits the send function and matches on its result. Success prints a line to standard output, and failure prints a line to standard error with the reason. Both lines go to the server terminal, where the person running the server can see them. The handle returned by spawn is dropped, because nobody needs the result of the send in the response. The response is already on its way by the time the send finishes.
Answering with 201 Created
(
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
)
The status is 201 Created, not 202 Accepted. The difference matters. Signup created a user account, and that creation is done when the response goes out. The email is a side effect of the signup, not the signup itself. A 202 would claim the signup itself was only accepted, which understates what happened. The honest split is 201 for the account that now exists, and a background task for the email that is still on its way. The format! macro builds the welcome message from the name the handler still owns, because the task took clones.
What the Task Receives and What It Does Not
A spawned email task needs exactly three things: who to write to, what to call them, and anything the email itself must contain, like a confirmation link or a token. It does not need the request, the response, or the handler's local variables. Passing the whole request body into the task would work, but it hands the task data it never uses, and it hides which fields actually matter.
The shape to aim for is a short list of owned values, one per line, cloned before the spawn call:
let email = body.email.clone();
let name = body.name.clone();
let token = confirmation_token.clone();
tokio::spawn(async move {
send_confirmation_email(email, name, token).await;
});
When the task needs shared state as well - a mail log, a counter of sent emails, a database pool - that state travels the same way, through a cloned Arc. The handler clones the Arc, moves the clone into the task, and both sides share the same underlying value. The rule never changes: the task owns everything it touches, either by owning a copy or by owning an Arc handle to shared state.
Pass Owned Values, Not the Request:
A spawned task cannot borrow the request body or any handler local. Clone the exact values the email needs - address, name, token - before the spawn call, and move those clones into the task. Cloning the whole body hides the task's real inputs and moves data the task never reads.
The Email Arrives After the Response
The ordering is worth stating plainly, because it is the part users misunderstand. The client receives {"message":"welcome, Asha"} first. The email is sent second, half a second later. If the user checks their inbox in the same second they signed up, the email is not there yet, and that is correct behaviour, not a bug.
The flow looks like this in plain text:
Client sends POST /signup with name and email
|
v
Handler parses the JSON body
|
v
Handler clones the email and the name
|
v
Handler spawns the email task
|
v
Handler returns 201 Created with a welcome message
|
v
Client receives the welcome at once
|
| (meanwhile, on a separate timeline)
v
Task waits half a second, the simulated send
|
v
Task logs the delivery, then finishes
The user sees the welcome immediately and the email a moment later. Any product that promises instant email delivery on signup is promising something this pattern cannot give. The honest promise is that the email is on its way.
When the Send Fails
The send can fail. The address can be malformed, the mail service can be down, the network can drop the connection. The simulated send fails when the address has no @, and a real mail client fails in all the same ways a network call can fail. The failure happens inside the task, after the response is gone, so the client never hears about it through the response. The task must record the failure somewhere the server operator can find it.
The smallest example already does this: the Err arm prints the failure to standard error with the address that failed. A real system would do more: write the failure to a log with a timestamp, record it in a database row for the user, or put the email on a retry queue. What it must never do is pretend the failure did not happen, because a user who never gets their confirmation email cannot confirm their account, and nobody will know unless the failure is recorded.
Try the failure path from a second terminal:
curl -X POST -H "content-type: application/json" -d '{"name":"Asha","email":"not-an-address"}' http://127.0.0.1:3000/signup
The response is still {"message":"welcome, Asha"} with a 201 status, because the signup itself succeeded. The server terminal shows the failure:
confirmation email failed: bad address: not-an-address
The client sees success and the server sees failure, and both are telling the truth about different things. The signup worked. The email did not. That split is uncomfortable, and it is the real cost of this pattern. The next section shows how to make the split less painful.
Validating the Address Before Spawning
The cheapest way to reduce email failures is to check the address before the task starts. A missing @ is a mistake the handler can catch while the client is still listening, and the handler can answer with a validation error instead of a welcome. The check belongs in the handler, not in the task, because only the handler can still talk to the client.
use axum::{http::StatusCode, routing::post, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Signup {
name: String,
email: String,
}
#[derive(Serialize)]
struct SignupReply {
message: String,
}
#[derive(Serialize)]
struct ErrorReply {
error: String,
}
async fn signup(
Json(body): Json<Signup>,
) -> Result<(StatusCode, Json<SignupReply>), (StatusCode, Json<ErrorReply>)> {
if !body.email.contains('@') {
return Err((
StatusCode::UNPROCESSABLE_ENTITY,
Json(ErrorReply { error: "email address must contain @".to_string() }),
));
}
let email = body.email.clone();
let name = body.name.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
println!("sent confirmation email to {} ({})", email, name);
});
Ok((
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
))
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/signup", post(signup));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler returns a Result, and Axum turns the Ok arm into the welcome response and the Err arm into the error response. An address without @ gets a 422 status and {"error":"email address must contain @"} while the client is still waiting, and no task is spawned at all. A well-formed address gets the welcome and the spawned send. The check is deliberately simple - a real validator would check more than one character - but the placement is the lesson: validate what you can before spawning, because after spawning, the client is gone.
Validate Before Spawning, Not Inside the Task:
Any check whose failure should change the response must run in the handler before the spawn call. A check inside the task can only log the failure, because the response is already sent. Move every client-visible validation ahead of the spawn.
Recording Sends in Shared State
Printing a line is enough for learning, but a real server needs to remember which emails were sent. Shared state gives the task somewhere to record the send, and a second route gives the operator somewhere to read it. The state holds a list of sent addresses behind a Mutex, and the task pushes the address onto the list after the simulated send.
use axum::{
extract::State,
http::StatusCode,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
#[derive(Clone)]
struct AppState {
sent_mail: Arc<Mutex<Vec<String>>>,
}
#[derive(Deserialize)]
struct Signup {
name: String,
email: String,
}
#[derive(Serialize)]
struct SignupReply {
message: String,
}
async fn send_confirmation_email(email: String, name: String) -> Result<(), String> {
sleep(Duration::from_millis(500)).await;
if email.contains('@') {
println!("sent confirmation email to {} ({})", email, name);
Ok(())
} else {
Err(format!("bad address: {}", email))
}
}
async fn signup(
State(state): State<AppState>,
Json(body): Json<Signup>,
) -> (StatusCode, Json<SignupReply>) {
let mail_log = Arc::clone(&state.sent_mail);
let email = body.email.clone();
let name = body.name.clone();
tokio::spawn(async move {
match send_confirmation_email(email, name).await {
Ok(()) => {
mail_log.lock().unwrap().push("sent".to_string());
}
Err(error) => {
eprintln!("confirmation email failed: {}", error);
}
}
});
(
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
)
}
async fn sent_count(State(state): State<AppState>) -> Json<serde_json::Value> {
let count = state.sent_mail.lock().unwrap().len();
Json(serde_json::json!({ "sent_emails": count }))
}
#[tokio::main]
async fn main() {
let state = AppState { sent_mail: Arc::new(Mutex::new(Vec::new())) };
let app = Router::new()
.route("/signup", post(signup))
.route("/admin/sent-emails", get(sent_count))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The handler clones the Arc around the mail log and moves it into the task alongside the email and the name. The task pushes a marker onto the list when the send succeeds. The count route locks the list, reads its length, and answers with it. The list is a Vec<String> holding one marker per sent email, which is enough to count sends and to see that the task really ran. A real system would store the address, the time, and the result instead of a bare marker, and it would store them in a database rather than memory, so the record survives a restart.
The Mutex here is the standard library one, and the lock is held only for the single line that pushes or reads. No await runs while the lock is held, so the handler future stays Send and the code compiles. That discipline - lock, touch the value, unlock, then await - is the same rule the earlier pages used for shared flags.
Testing the Signup Flow
A test can prove the response arrives before the email is sent by sending a signup through the router and checking two things: the status is 201, and the mail log is still empty right after the response comes back.
use axum::{
body::Body,
extract::State,
http::{Request, StatusCode},
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
use tower::ServiceExt;
#[derive(Clone)]
struct AppState {
sent_mail: Arc<Mutex<Vec<String>>>,
}
#[derive(Deserialize)]
struct Signup {
name: String,
email: String,
}
#[derive(Serialize)]
struct SignupReply {
message: String,
}
async fn signup(
State(state): State<AppState>,
Json(body): Json<Signup>,
) -> (StatusCode, Json<SignupReply>) {
let mail_log = Arc::clone(&state.sent_mail);
let email = body.email.clone();
tokio::spawn(async move {
sleep(Duration::from_millis(200)).await;
if email.contains('@') {
mail_log.lock().unwrap().push(email);
}
});
(
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
)
}
#[tokio::test]
async fn signup_answers_before_email_is_sent() {
let state = AppState { sent_mail: Arc::new(Mutex::new(Vec::new())) };
let mail_log = Arc::clone(&state.sent_mail);
let app = Router::new().route("/signup", post(signup)).with_state(state);
let response = app
.oneshot(
Request::builder()
.uri("/signup")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(r#"{"name":"Asha","email":"asha@example.com"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
assert!(mail_log.lock().unwrap().is_empty());
sleep(Duration::from_millis(400)).await;
assert_eq!(mail_log.lock().unwrap().len(), 1);
assert_eq!(mail_log.lock().unwrap()[0], "asha@example.com");
}
The test sends the signup through the router with oneshot, which runs the request without any network connection. The first assertion checks the status is 201. The second checks the mail log is still empty immediately after the response, which proves the response did not wait for the email. The test then waits 400 milliseconds, longer than the 200 millisecond simulated send, and asserts the log holds one entry with the right address, which proves the email was still sent.
The test needs tower with the util feature as a dev dependency, which provides the oneshot method:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with cargo test. The output ends with test result: ok, and the assertions together prove both halves of the behaviour: the welcome came first, and the email followed.
Common Beginner Mistakes
Awaiting the send inside the handler
// Wrong - the client waits for the mail service
async fn signup(Json(body): Json<Signup>) -> (StatusCode, Json<SignupReply>) {
send_confirmation_email(body.email.clone(), body.name.clone()).await.unwrap();
(StatusCode::CREATED, Json(SignupReply { message: "welcome".to_string() }))
}
Awaiting the send makes the client wait for the mail service, and a slow mail service makes every signup slow. Spawn the send and answer at once. The welcome does not depend on the email.
Returning 202 for a completed signup
// Wrong - the signup is done, only the email is pending
(StatusCode::ACCEPTED, Json(SignupReply { message: "welcome".to_string() }))
The account exists when the response goes out, so 202 understates what happened. Use 201 Created for the signup, and let the email be the background part. Reserve 202 for requests where the main work itself is still pending.
Borrowing the body into the task
// Wrong - the task borrows body, which is dropped when the handler returns
tokio::spawn(async {
send_confirmation_email(body.email.clone(), body.name.clone()).await;
});
The task borrows body, and the borrow fails to compile with error E0373, because the task can outlive the handler. Clone the email and the name into their own variables before the spawn call, and move those into the task.
Ignoring the send result inside the task
// Wrong - a failed send vanishes without a trace
tokio::spawn(async move {
let _ = send_confirmation_email(email, name).await;
});
Discarding the result means a failed email leaves no record anywhere. The user never gets their confirmation, and nobody knows. Match on the result and log both arms, success and failure, so the server terminal always says what happened.
Validating the address inside the task
// Wrong - the client has already gone by the time this check runs
tokio::spawn(async move {
if !email.contains('@') {
eprintln!("bad address");
}
});
A check inside the task can only log. The client cannot be told the address was bad, because the response is already sent. Run the validation in the handler before spawning, and answer with a 422 while the client is still listening.
Final Complete Example
This example pulls the page together: a signup route that validates the address, stores the user in shared state, spawns the confirmation email, and answers 201 at once, plus a route that reports how many confirmation emails were sent.
use axum::{
extract::State,
http::StatusCode,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;
#[derive(Clone)]
struct AppState {
users: Arc<Mutex<Vec<String>>>,
sent_mail: Arc<Mutex<Vec<String>>>,
}
#[derive(Deserialize)]
struct Signup {
name: String,
email: String,
}
#[derive(Serialize)]
struct SignupReply {
message: String,
}
#[derive(Serialize)]
struct ErrorReply {
error: String,
}
async fn send_confirmation_email(email: String, name: String) -> Result<(), String> {
sleep(Duration::from_millis(500)).await;
if email.contains('@') {
println!("sent confirmation email to {} ({})", email, name);
Ok(())
} else {
Err(format!("bad address: {}", email))
}
}
async fn signup(
State(state): State<AppState>,
Json(body): Json<Signup>,
) -> Result<(StatusCode, Json<SignupReply>), (StatusCode, Json<ErrorReply>)> {
if !body.email.contains('@') {
return Err((
StatusCode::UNPROCESSABLE_ENTITY,
Json(ErrorReply { error: "email address must contain @".to_string() }),
));
}
{
let mut users = state.users.lock().unwrap();
users.push(body.email.clone());
}
let mail_log = Arc::clone(&state.sent_mail);
let email = body.email.clone();
let name = body.name.clone();
tokio::spawn(async move {
match send_confirmation_email(email, name).await {
Ok(()) => {
mail_log.lock().unwrap().push("sent".to_string());
}
Err(error) => {
eprintln!("confirmation email failed: {}", error);
}
}
});
Ok((
StatusCode::CREATED,
Json(SignupReply { message: format!("welcome, {}", body.name) }),
))
}
async fn stats(State(state): State<AppState>) -> Json<serde_json::Value> {
let users = state.users.lock().unwrap().len();
let sent = state.sent_mail.lock().unwrap().len();
Json(serde_json::json!({ "users": users, "sent_emails": sent }))
}
#[tokio::main]
async fn main() {
let state = AppState {
users: Arc::new(Mutex::new(Vec::new())),
sent_mail: Arc::new(Mutex::new(Vec::new())),
};
let app = Router::new()
.route("/signup", post(signup))
.route("/admin/stats", get(stats))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The state holds two lists: the users who signed up, and the confirmation emails that were sent. The handler validates the address first, and a bad address gets a 422 before anything is stored or spawned. A good address is pushed onto the users list inside a block that drops the lock before the spawn call. The task sends the simulated email and records the send in the mail log, or logs the failure. The stats route reads both lists and reports the counts.
Try it from a second terminal:
curl -X POST -H "content-type: application/json" -d '{"name":"Asha","email":"asha@example.com"}' http://127.0.0.1:3000/signup
curl http://127.0.0.1:3000/admin/stats
The signup answers at once with {"message":"welcome, Asha"} and a 201 status. The stats call answers {"users":1,"sent_emails":0} before half a second passes, and {"users":1,"sent_emails":1} after. The user count jumps at once, because the signup is done when the response goes out. The sent count jumps later, because the email is still travelling. Those two numbers moving at different times are the pattern, visible in the open.
Summary
The signup page teaches a small decision that shows up in almost every real service: separate the work the client is waiting for from the work the client is not. The account is the first kind, so it is created in the handler and answered with 201. The email is the second kind, so it is spawned, given owned copies of the address and the name, and left to finish on its own timeline. The split only works when three things hold: the address is validated before the spawn, because the client cannot be corrected afterwards; the send result is logged inside the task, because the response cannot carry it; and the email is treated as a side effect the user can afford to receive a moment later, not as part of the signup itself. When any of those three fails, the pattern is the wrong one, and the send belongs back in the handler, awaited, with its failure in the response.