Ekbatan
event-driven
rust
persistence
framework.

v0.0.0 · Apache 2.0 · Rust 2024

Ekbatan is a Rust persistence framework for event-driven systems. One database transaction commits your data and the domain events; the persisted events can then be drained from the events outbox table to Kafka, or handled in process, or both.

Built on sqlx and sea-query: SQL you can read, no ORM, no session, no lazy loading. Blocking or async, one engine underneath. The Rust port of Ekbatan for Java: the same tables and event JSON, so a Java service and a Rust one read each other's events.

01/The dual-write trap

Two writes. Two systems. One silent drift.

Your service inserts a row into the database, then publishes an event to Kafka. Two independent operations across two systems. If the second fails — Kafka outage, network blip, service crash — the row is committed but the event is lost. Your database and your event stream silently disagree.

Two writes

✗ broken

Crash between writes ⇒ DB and Kafka disagree.

The solution is a known pattern: the Transactional Outbox. Write the row AND the event into the same database transaction — both commit or both roll back. A separate process (a CDC tool like Debezium, a background job, or similar) drains the outbox table to Kafka, retrying until delivery succeeds.

Ekbatan makes adopting this pattern hassle-free. No boilerplate, no glue code, no outbox plumbing to maintain. There is no second table to remember, because you never write to it — so there is nothing to forget.

One write + outbox

✓ Ekbatan
app
database (one tx)
state
events
Kafka
consumer

CDC tails the outbox — events ship later, always in sync.

learn by example
01/Model

MODEL is immutable. Attaches its own events upon change.

An immutable struct that carries its own events. #[model] makes the fields private and writes the getters and the builder. deposit(amount) returns a new Wallet with a WalletMoneyDepositedEvent attached in the same builder call: state and event tied together at the source, never two writes. No events needed for a table? Use #[entity] instead: saved the same way, with no events.

model.rs
rust
1 #[model(id = ShardedId<Wallet>, state = WalletState)]
2 pub struct Wallet {
3 pub owner_id: Uuid,
4 pub currency: String,
5 pub balance: Decimal,
6 }
7
8 impl Wallet {
9 pub fn deposit(&self, amount: Decimal) -> Result<Wallet, Error> {
10 if amount <= Decimal::ZERO {
11 return Err(Error::Invalid("Deposit amount must be positive".to_owned()));
12 }
13 let new_balance = self.balance + amount;
14 self.copy()
15 .with_event(WalletMoneyDepositedEvent { amount, new_balance })
16 .balance(new_balance)
17 .build()
18 }
19 }
learn by example
02/Action

ACTION reads, mutates, PLANS the changes. The executor persists them.

A unit of business work. perform() reads from a repository, makes the new version of the model, and stages it on the plan. No transaction to manage, no direct writes. When perform() returns, the executor opens one transaction and writes everything: the domain rows and their events in the outbox table. All of it commits, or none of it. This one is blocking; AsyncAction is the same with async fn perform.

action.rs
rust
1 pub struct WalletDepositMoneyAction {
2 wallet_repository: Arc<WalletRepository>,
3 }
4
5 impl Action for WalletDepositMoneyAction {
6 type Params = Params; // { wallet_id, amount, recipient }
7 type Result = Wallet;
8
9 fn perform(
10 &self,
11 plan: &mut ActionPlan,
12 _principal: Option<&str>,
13 params: &Params,
14 ) -> Result<Wallet, Error> {
15 let wallet = self.wallet_repository.get_by_id(&params.wallet_id)?;
16 plan.update(wallet.deposit(params.amount)?)
17 }
18 }
learn by example
03/Action Executor

ACTION EXECUTOR runs the action. Wherever you call it from.

The single entry point. Call execute::<SomeAction>(principal, params) from anywhere: an axum handler (shown), a worker, a scheduled job, a command-line tool. It runs the action, the transaction and the commit, and retries when you ask it to. Notice what the handler does not mention: a transaction, a publish, or an outbox.

web.rs
rust
1 async fn deposit(
2 State(state): State<AppState>,
3 Path(id): Path<Uuid>,
4 Json(body): Json<DepositRequest>,
5 ) -> Result<Json<WalletResponse>, ApiError> {
6 let wallet = state
7 .executor
8 .execute::<WalletDepositMoneyAction>(
9 Some("rest-user"),
10 wallet_deposit_money_action::Params {
11 wallet_id: ShardedId::from_uuid(id),
12 amount: body.amount,
13 recipient: body.recipient,
14 },
15 )
16 .await?;
17 Ok(Json(WalletResponse::from(&wallet)))
18 }
learn by example
04/Repository

REPOSITORY is built on sqlx and sea-query. A thin layer on top.

You implement AbstractRepository: the mapping between a row and a model, written once in to_record and from_record, against the WalletsRecord generated from your migrations. get_by_id, add, update and the rest come with it, with optimistic locking and soft deletion. Your own queries are plain sea-query, and you pick the database: db(), readonly_db(), readonly_dbs(), so every call shows whether it may read from a replica.

repository.rs
rust
1 impl AbstractRepository for WalletRepository {
2 type Persistable = Wallet;
3 type Record = WalletsRecord; // generated from your migrations
4 fn registry(&self) -> &DatabaseRegistry { &self.registry }
5 fn from_record(record: WalletsRecord) -> Result<Wallet, Error> { /* ... */ }
6 fn to_record(wallet: &Wallet) -> WalletsRecord { /* ... */ }
7 }
8
9 impl WalletRepository {
10 pub async fn find_all_by_owner_id(&self, owner_id: Uuid) -> Result<Vec<Wallet>, Error> {
11 let select = Query::select()
12 .column(Asterisk)
13 .from(Wallets::Table)
14 .and_where(Expr::col(Wallets::OwnerId).eq(owner_id))
15 .to_owned();
16 let records = self.readonly_dbs().fetch_all::<WalletsRecord>(&select).await?;
17 records.into_iter().map(Self::from_record).collect()
18 }
19 }
ATOMIC★OUTBOX-NATIVE★RUST★SQLX · SEA-QUERY★NO ORM★MULTI-DATABASE★SHARDED★BLOCKING OR ASYNC★POSTGRES · MYSQL · MARIADB★
ATOMIC★OUTBOX-NATIVE★RUST★SQLX · SEA-QUERY★NO ORM★MULTI-DATABASE★SHARDED★BLOCKING OR ASYNC★POSTGRES · MYSQL · MARIADB★