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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.