rust 68 lines · 9 steps

An atomic money transfer handler in Axum

An Axum handler moves money between accounts inside a single Postgres transaction so a debit and credit never drift apart.

Explained by highlit
1use axum::{extract::State, http::StatusCode, Json};
2use serde::{Deserialize, Serialize};
3use sqlx::PgPool;
4use uuid::Uuid;
5 
6#[derive(Deserialize)]
7pub struct TransferRequest {
8 from_account: Uuid,
9 to_account: Uuid,
10 amount_cents: i64,
11}
12 
13#[derive(Serialize)]
14pub struct TransferResponse {
15 transfer_id: Uuid,
16}
17 
18pub async fn transfer_funds(
19 State(pool): State<PgPool>,
20 Json(req): Json<TransferRequest>,
21) -> Result<Json<TransferResponse>, (StatusCode, String)> {
22 let mut tx = pool
23 .begin()
24 .await
25 .map_err(internal_error)?;
26 
27 let debited = sqlx::query!(
28 "UPDATE accounts SET balance_cents = balance_cents - $1 \
29 WHERE id = $2 AND balance_cents >= $1",
30 req.amount_cents,
31 req.from_account,
32 )
33 .execute(&mut *tx)
34 .await
35 .map_err(internal_error)?;
36 
37 if debited.rows_affected() == 0 {
38 return Err((StatusCode::UNPROCESSABLE_ENTITY, "insufficient funds".into()));
39 }
40 
41 sqlx::query!(
42 "UPDATE accounts SET balance_cents = balance_cents + $1 WHERE id = $2",
43 req.amount_cents,
44 req.to_account,
45 )
46 .execute(&mut *tx)
47 .await
48 .map_err(internal_error)?;
49 
50 let transfer_id: Uuid = sqlx::query_scalar!(
51 "INSERT INTO transfers (from_account, to_account, amount_cents) \
52 VALUES ($1, $2, $3) RETURNING id",
53 req.from_account,
54 req.to_account,
55 req.amount_cents,
56 )
57 .fetch_one(&mut *tx)
58 .await
59 .map_err(internal_error)?;
60 
61 tx.commit().await.map_err(internal_error)?;
62 
63 Ok(Json(TransferResponse { transfer_id }))
64}
65 
66fn internal_error<E: std::fmt::Display>(err: E) -> (StatusCode, String) {
67 (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
68}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping related writes in one transaction guarantees they all commit or none do, preventing half-finished transfers.
  2. 2Guarding the debit with a balance predicate lets the database enforce sufficient funds atomically instead of a racy read-then-write.
  3. 3Mapping every await failure to a rollback keeps money invariants intact even when a later query fails.

Related explainers

Share this explainer

Here's the card — post it anywhere.

An atomic money transfer handler in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code