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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping related writes in one transaction guarantees they all commit or none do, preventing half-finished transfers.
- 2Guarding the debit with a balance predicate lets the database enforce sufficient funds atomically instead of a racy read-then-write.
- 3Mapping every await failure to a rollback keeps money invariants intact even when a later query fails.
Related explainers
typescript
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload,
Manual RabbitMQ acks in a NestJS controller
microservices
message-queue
acknowledgement
Intermediate
8 steps
rust
use std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HttpStatus {
Converting HTTP codes with TryFrom in Rust
enums
error-handling
trait-implementation
Intermediate
8 steps
rust
use axum::{ extract::{Request, State}, http::{HeaderValue, StatusCode}, middleware::Next,
API version headers with Axum middleware
middleware
http-headers
versioning
Intermediate
8 steps
rust
use axum::{ extract::Path, http::StatusCode, routing::{get, post},
Building a REST resource in Axum
rest-api
routing
serialization
Intermediate
9 steps
rust
use chrono::NaiveDate; use serde::{Deserialize, Deserializer}; #[derive(Debug, Deserialize)]
Custom date parsing with serde in Rust
serde
deserialization
csv-parsing
Intermediate
7 steps
python
import uuid from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile
Handling multipart file uploads in FastAPI
file-upload
validation
multipart-form
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/an-atomic-money-transfer-handler-in-axum-explained-rust-34bd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.