§learn

Blocking or async?

ekbatan has two APIs over one engine: ekbatan::blocking, with plain functions, and ekbatan::aio, where every database call is awaited. They write the same rows and follow the same rules. This page says how to pick, what is the same in both, and the one mistake to avoid.

How to choose

Pick async (ekbatan::aio) when the service is already async: an axum server, or anything else on a tokio runtime, where many requests wait on the database at the same time. The REST examples, the sharded one and the saga all use it.

Pick blocking (ekbatan::blocking) when the program has no async code of its own:

The job-worker-pg and wallet-service-blocking-pg examples are blocking from top to bottom: not one async in the app’s code.

The blocking API is not a second, slower database driver. Every blocking call waits on the same async code underneath, so the queries and the transactions are the same. What differs is the waiting: a blocking call holds its thread until the database answers, while an awaited one lets the thread do other work in the meantime.

The one mistake: the blocking API inside async code

Never call the blocking API from inside an async fn.

// Wrong, inside an async fn: holds a tokio worker thread until the database answers.
let wallet = ekbatan::blocking::Repository::get_by_id(&*wallets, &id)?;

// Right: the async twin, awaited.
let wallet = ekbatan::aio::AsyncRepository::get_by_id(&*wallets, &id).await?;

What happens depends on the runtime:

Nothing checks for this at compile time, and ekbatan does not guard against it. It is the same rule as reqwest::blocking.

If async code really has to run something blocking of your own, hand it to tokio::task::spawn_blocking.

The other way round is allowed

A blocking Action, DistributedJob or EventHandler is also an async one: ekbatan implements the async trait for every blocking one. So a blocking action can be registered with an AsyncActionExecutor, and a blocking job or handler can run in a JobRegistry an async service started.

While it runs, it steps off the runtime’s thread first (tokio::task::block_in_place), so it does not stall other tasks. That needs a multi-threaded runtime: on a single-threaded one it panics too. The examples’ async tests use #[tokio::test(flavor = "multi_thread")] for that reason.

What is the same in both

What differs

blockingasync
import fromekbatan::blockingekbatan::aio
actionAction, fn performAsyncAction, async fn perform
executorActionExecutor, executor.execute::<A>(principal, params)?AsyncActionExecutor, executor.execute::<A>(principal, params).await?
repository methodsRepositoryAsyncRepository
registryregistry.primary(shard), registry.close()registry.as_async().primary(shard), registry.as_async().close().await
transactiontransaction_manager.in_transaction(...)transaction_manager.as_async().in_transaction(...).await
keyed lockKeyedLockProvider::acquire gives a Lease, released when droppedAsyncKeyedLockProvider::acquire(...).await gives an AsyncLease, lease.release().await
distributed jobDistributedJob, fn executeAsyncDistributedJob, async fn execute
event handlerEventHandler, fn handleAsyncEventHandler, async fn handle
testing an actionekbatan_test_support::blocking::ActionSpecekbatan_test_support::aio::AsyncActionSpec
migrations, starting and stopping jobsblock_on(...).await

The names follow one rule: plain in blocking, Async in front in aio. DatabaseRegistry and TransactionManager are shared types; their blocking methods are on the type itself, and .as_async() gives you the awaited ones.

A deposit, both ways:

use ekbatan::blocking::{Action, Repository};

impl Action for WalletDepositMoneyAction {
    type Params = Params;
    type Result = Wallet;

    fn perform(
        &self,
        plan: &mut ActionPlan,
        _principal: Option<&str>,
        params: &Params,
    ) -> Result<Wallet, Error> {
        let wallet = self.wallet_repository.get_by_id(&params.wallet_id)?;
        let updated = wallet.deposit(params.amount)?;
        plan.update(updated)
    }
}

let wallet = executor.execute::<WalletDepositMoneyAction>(Some("alice"), params)?;

The model, deposit, the plan and what gets written are the same. Only perform and the call around it change.

What always runs on the async engine

The async code is the engine. The blocking API is a thin layer that waits on it, on a tokio runtime of ekbatan’s own: ekbatan::blocking::runtime(), multi-threaded, started the first time something needs it. A connection pool made outside any runtime lives on it.

So even in a blocking program, some things are async underneath:

use ekbatan::blocking::block_on;

// Migrations have no blocking twin: block_on runs the async call to its end.
block_on(
    Migrator::builder()
        .with_sharding_config(sharding)
        .locations([concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")])
        .migrate(),
)?;

block_on is safe to call from inside a blocking action, job or handler: it steps off the runtime’s thread before it waits.

Where to go next