Implementing Rust outbox pattern boilerplate
Created a single Rust file with axum, sqlx (Postgres), tokio, and rdkafka demonstrating the outbox pattern: a POST /users endpoint inserting user and outbox event in one transaction, plus a background worker publishing outbox entries to Kafka and marking them as processed atomically.
Below is a self‑contained example main.rs illustrating a small Axum + SQLx web service that uses the outbox pattern. When a record is saved, an outbox event is inserted in the same transaction. A background worker reads unprocessed outbox records and publishes them to Kafka, then marks them as processed.
Note: You’ll need to set up your own database/schema migrations and configure Kafka. This is just a boilerplate to show the approach.
// Cargo.toml (add these to your dependencies)
// [dependencies]
// axum = "0.6"
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
// tokio = { version = "1", features = ["full"] }
// uuid = { version = "1", features = ["v4"] }
// sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "json"] }
// rdkafka = { version = "0.28", features = ["cmake-build"] }
// tracing = "0.1"
// tracing-subscriber = "0.3"
use axum::{
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use sqlx::{postgres::PgPoolOptions, PgPool, Postgres, Transaction};
use std::{net::SocketAddr, time::Duration};
use tokio::time::sleep;
use tracing::{error, info};
use uuid::Uuid;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Initialize tracing/logging
tracing_subscriber::fmt::init();
// Database pool
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set, e.g. postgres://user:pass@localhost/db");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
// Spawn outbox worker
let pool_clone = pool.clone();
tokio::spawn(async move {
if let Err(e) = run_outbox_worker(pool_clone).await {
error!("Outbox worker crashed: {:?}", e);
}
});
// Build router
let app = Router::new()
.route("/", get(|| async { "OK" }))
.route("/users", post(create_user))
.with_state(pool);
// Start server
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
info!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?;
Ok(())
}
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
#[derive(Serialize, Deserialize)]
struct User {
id: Uuid,
name: String,
email: String,
}
#[derive(Serialize, Deserialize)]
struct OutboxEvent {
id: Uuid,
event_type: String,
payload: serde_json::Value,
}
/// Web handler: create a new user and outbox event in a single DB transaction.
async fn create_user(
axum::extract::State(pool): axum::extract::State<PgPool>,
Json(payload): Json<CreateUserRequest>,
) -> Result<Json<User>, axum::http::StatusCode> {
let mut tx = pool
.begin()
.await
.map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
let user_id = Uuid::new_v4();
let outbox_id = Uuid::new_v4();
// Insert user
sqlx::query!(
r#"
INSERT INTO users (id, name, email)
VALUES ($1, $2, $3)
"#,
user_id,
payload.name,
payload.email
)
.execute(&mut tx)
.await
.map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
// Insert outbox event for "UserCreated"
let event_payload = serde_json::json!({
"id": user_id,
"name": payload.name,
"email": payload.email,
});
sqlx::query!(
r#"
INSERT INTO outbox (id, event_type, payload, processed)
VALUES ($1, $2, $3, false)
"#,
outbox_id,
"UserCreated",
event_payload
)
.execute(&mut tx)
.await
.map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
// Commit transaction
tx.commit()
.await
.map_err(|_| axum::http::StatusCode::INTERNAL_SERVER_ERROR)?;
let user = User {
id: user_id,
name: payload.name,
email: payload.email,
};
Ok(Json(user))
}
/// Background loop that reads pending outbox events, sends to Kafka, marks them processed.
async fn run_outbox_worker(pool: PgPool) -> anyhow::Result<()> {
// Build Kafka producer config (customize as needed)
use rdkafka::config::ClientConfig;
use rdkafka::producer::{BaseRecord, ThreadedProducer};
let producer: ThreadedProducer<_> = ClientConfig::new()
.set("bootstrap.servers", &std::env::var("KAFKA_BOOTSTRAP").unwrap_or_else(|_| "localhost:9092".into()))
.set("message.timeout.ms", "5000")
.create()
.expect("producer creation error");
loop {
// Sleep briefly to avoid hammering the DB
sleep(Duration::from_millis(500)).await;
// Fetch unprocessed outbox entries in a short transaction
let mut tx = match pool.begin().await {
Ok(tx) => tx,
Err(e) => {
error!("Failed to start transaction: {:?}", e);
continue;
}
};
// Use FOR UPDATE SKIP LOCKED to avoid conflicts if multiple workers exist
let events = sqlx::query!(
r#"
SELECT id, event_type, payload
FROM outbox
WHERE processed = false
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 10
"#
)
.fetch_all(&mut tx)
.await?;
if events.is_empty() {
// Nothing to do, commit and continue
tx.commit().await?;
continue;
}
for ev in events {
// Try to publish to Kafka
let topic = "user_events";
let payload_str = ev
.payload
.as_ref()
.map(|v| v.get())
.unwrap_or("")
.to_string();
let publish_res = producer.send(
BaseRecord::to(topic)
.key(&ev.event_type)
.payload(&payload_str),
);
match publish_res {
Ok(_) => {
info!("Published outbox event {} -> Kafka", ev.id);
// Mark event as processed
sqlx::query!(
"UPDATE outbox SET processed = true, processed_at = now() WHERE id = $1",
ev.id
)
.execute(&mut tx)
.await?;
}
Err((e, _owned_msg)) => {
error!("Kafka publish error for event {}: {:?}", ev.id, e);
// Don’t mark it processed; it will be retried later
}
}
}
// Commit the updates to processed flags
tx.commit().await?;
}
}
/*
Example schema for PostgreSQL:
CREATE TABLE users (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE outbox (
id UUID PRIMARY KEY,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
processed BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
processed_at TIMESTAMP WITH TIME ZONE
);
*/
How it works:
- The
/users endpoint starts a database transaction.
- It inserts the
users row and then an outbox row in the same transaction.
- The transaction commits, ensuring both record and outbox entry are saved atomically.
- A background worker (
run_outbox_worker) periodically fetches unprocessed outbox rows (locking them) and attempts to publish them to Kafka. On success, it marks them as processed in the same transaction. If publishing fails, it leaves the row untouched so it will be retried.