Step 0. Designing the transaction flow
Banking is a natural domain for ObzenFlow because it already thinks in journals.
An account is opened. A credit is posted. A debit is posted.
Your current balance is derived from the entries that came before it, meaning the statement you read at the end of the month is a projection of every posted entry. Deriving state from a journal of facts rather than overwriting a place that holds the latest value is the spirit of every ObzenFlow program.
Designing an ObzenFlow service follows the same flow you saw in the Getting Started tutorial:
- Understand the domain.
- Name the commands and events.
- Turn those facts into Rust types.
- Sketch the flow topology.
- Wire the types together with
placeholder!()handlers.
That sequence lets you model the shape of a real ObzenFlow program in a few dozen lines before writing the business logic. Using placeholder!() syntax means you can compile the skeleton, check the topology, and eventually replace each placeholder with real logic once the overall design is clear enough. We will use that same process here.
Understanding the domain
Event storming is a useful way to do the first pass because it asks you to name what happened before you name where it is stored. We are not going to run a full event-storming workshop in this tutorial. Credits, debits, and account openings are familiar enough that we can use the technique lightly, but on most projects, you would want to workshop the business domain itself before proceeding.
For a checking-account service, the list of facts is short enough to write from memory. Three are visible at the service boundary.
- An account is opened with an account id, an owner, and an initial balance.
- A ledger entry is submitted as a credit or a debit for an account.
- A checkbook snapshot is observed by anyone reading the account state.
A fourth fact lives entirely inside the flow.
- A posted entry exists when the framework has matched a submitted ledger entry against a known account.
The fourth fact is where the service crosses from request handling into durable accounting. LedgerEntry is the incoming command. PostedEntry is the accepted fact the rest of the flow can trust.
In ObzenFlow, your code acts as commands in event-sourcing terms, and once a command is accepted by the system, it will produce one or more events, which are facts.
Facts cannot be refuted. Every fact is written to a journal in ObzenFlow, and journal entries can be replayed to rebuild the state of a system. Your intent or command can fail, which means that it is not yet an event.
The way to think about it is this: commands can be refuted, but events cannot be refuted; they are facts. The types that you define (for instance, ledger entry, posted entry, etc.) resemble facts, whereas the code that you define in custom handlers represents intent. The fact that we processed a ledger entry from an external system is a fact. A posted entry is a different type of fact.
Now in a real system we would probably have rejected ledger entries which could feed back into a totally different type of reconciliation system. This is why modeling your domain is so critical but for a simple example like this we are assuming somewhat of a simple happy path.
Sketching domain types
With the facts in hand, the Rust types follow naturally. Here are the four types from examples/http_ingestion_piggy_bank_demo/domain.rs:
pub struct AccountOpened {
pub account: AccountId,
pub owner: String,
pub opening_balance: Balance,
}
pub enum EntryKind { Credit, Debit }
pub struct LedgerEntry {
pub account: AccountId,
pub kind: EntryKind,
pub amount: UsdCents,
pub note: Option<String>,
pub originator: Option<Originator>,
}
pub struct PostedEntry {
pub account: AccountId,
pub owner: String,
pub kind: EntryKind,
pub amount: UsdCents,
pub opening_balance: Balance,
pub note: Option<String>,
pub originator: Option<Originator>,
}
pub struct CheckbookSnapshot {
pub account: AccountId,
pub owner: String,
pub current_balance: Balance,
pub available_balance: Balance,
pub total_credits: UsdCents,
pub total_debits: UsdCents,
pub transactions: Vec<CheckbookEntry>,
}AccountId, UsdCents and Balance are small newtypes from the example’s domain.rs and money.rs. Each is written and read as text, "acct-1" and "10.00", so an identifier is never mistaken for a number and a balance is never a float. The originator is the merchant behind an ACH debit, and it is empty for an ordinary ledger entry.
Look closely at PostedEntry and you can see the merge written into the type. It carries the owner and opening_balance from AccountOpened along with the kind, amount, note and originator from LedgerEntry. The shape of the struct mirrors the shape of the join. When two streams meet, the resulting event carries fields from both inputs, and the type system records the merge as part of the contract.
Sketching the flow
With the events named, you can sketch the topology before writing any handler logic. This is the same placeholder-first workflow you saw in Getting Started and in examples/char_transform_skeleton.rs. The framework wires stages together by type, and the compiler checks every connection even while the handlers are still placeholders.
flow! {
name: "http_ingestion_piggy_bank_demo",
journals: disk_journals(PathBuf::from("target/http-ingestion-piggy-bank-demo-logs")),
stages: {
batch_accounts = source!(AccountOpened => placeholder!());
batch_tx = source!(LedgerEntry => placeholder!());
live_accounts = async_infinite_source!(AccountOpened => placeholder!());
live_tx = async_infinite_source!(LedgerEntry => placeholder!());
accounts = merge!(AccountOpened => merges::then_live);
transactions = merge!(LedgerEntry => merges::then_live);
posted = join!(
catalog accounts: AccountOpened,
LedgerEntry -> PostedEntry => placeholder!()
);
checkbook = stateful!(PostedEntry -> CheckbookSnapshot => placeholder!());
printer = sink!(CheckbookSnapshot => placeholder!());
},
topology: {
batch_accounts |> accounts;
live_accounts |> accounts;
batch_tx |> transactions;
live_tx |> transactions;
(accounts, transactions) |> posted;
posted |> checkbook;
checkbook |> printer;
}
}placeholder!() is the design-time handler for a typed stage, not a replacement for the domain types themselves. We won’t cover placeholders in depth as we covered them in the Getting Started tutorial, but I’d like to add that they shine during domain modelling as they allow shaping a topology and checking the shape before committing to implementation details. Use placeholders liberally during design!
Now three parts of that sketch are worth a closer look, because all three are new compared to char_transform.
The first is that the sources have different lifetimes. The two
batch_sources use the samesource!macro you met in Getting Started, because they read files with a fixed number of entries. Each reads its file once and then signals end of stream, which makes it finite. The twolive_sources useasync_infinite_source!, the live counterpart tosource!. New accounts and transactions arrive over HTTP endpoints that never signal end of stream, so those sources are infinite and the pipeline stays alive for as long as the service is running, draining events as they arrive.The second is the pair of merges. The
accountsmerge gives the batch and live account sources one downstream stream, andtransactionsdoes the same for ledger entries. Theirthen_livestrategy passes on every batch row before any live one.The third is the way
accountsparticipates in the join. Both merges feed the join through(accounts, transactions) |> posted, but they play different roles there. Theaccountsmerge is also named on the catalog line inside the join itself, and the framework holds the accounts there as a reference table keyed by account id. That is how stream-table joins are expressed in ObzenFlow, and the next several steps return to this idea from different angles.
We will cover these concepts in detail later in the tutorial but for now understand that you’re looking at slightly new terminology that you don’t yet need to fully understand. We already have enough implemented to see the flow’s shape.
Visualizing the sketch in ObzenFlow Studio
With this very small amount of code, We can already visualize the skeleton. ObzenFlow Studio is in development and not yet released, but this is what the sketch already looks like in it.
That’s enough to design a durable execution flow. Everything else we discuss fills in the details: implementation details, operational aspects like middleware, and debugging aspects like this.
To get a flavor of how an ObzenFlow program runs, we’ll run through the completed example. First we’ll start with the conclusion in step one. Steps 2, 3, and 4 will walk through new concepts that we didn’t cover in the getting started tutorial. Step 5 explains the operational surface area, and step 6 closes the loop on durable execution by stopping the service and resuming it from its own journals.
Step 1. Run the service end to end
The fastest way to build a mental model of the service is to run it before reading the code. If you have already cloned the framework repo from Getting Started, you can stay in that working directory. Otherwise, clone it now.
git clone https://github.com/ObzenFlow/obzenflow
cd obzenflowRun the piggy bank example:
RUST_LOG=info cargo run -p obzenflow --example http_ingestion_piggy_bank_demo --features prometheus,web-hostThe example loads examples/http_ingestion_piggy_bank_demo/obzenflow.toml at startup. That file enables the local HTTP server and metrics, and names the accounts and transactions files the service reads at startup. By default, the service listens on 127.0.0.1:9090. Leave that terminal running.
Essentially, this example demonstrates a stream-to-table join. First, the service builds a table of accounts. Second, it matches each transaction to the corresponding entry in the accounts table. Both start from files. The accounts table comes from examples/http_ingestion_piggy_bank_demo/accounts.yaml, which the service reads once at startup.
accounts:
- account: "acct-1"
owner: Alice
opening_balance: "10.00"
- account: "acct-2"
owner: Bob
opening_balance: "0.00"Alice opens with $10.00 and Bob opens with nothing. The first transactions come from examples/http_ingestion_piggy_bank_demo/transactions.csv, which posts against those accounts at about two rows a second.
account,kind,amount,note
acct-1,Credit,2.50,paycheck
acct-1,Debit,0.99,coffee
acct-2,Credit,15.00,birthday gift
acct-1,Debit,4.50,groceries
acct-2,Debit,3.00,movie tickets
acct-1,Credit,1.25,refundThe service terminal prints a fresh checkbook snapshot for the affected account after every posted transaction. When the file is drained, Alice stands at $8.26 after four entries, and Bob at $12.00 after two.
Once both files are read, the service goes live. In a second terminal, open a third account over HTTP with curl, wait for its 202, then post a credit to the new account and a debit to Alice’s. Each request carries an Idempotency-Key that names it.
curl -XPOST http://127.0.0.1:9090/api/bank/accounts/events \
-H 'content-type: application/json' \
-H 'Idempotency-Key: "acct-0003"' \
-d '{"event_type":"bank.account_opened","data":{"account":"acct-3","owner":"Carol","opening_balance":"0.00"}}'
curl -XPOST http://127.0.0.1:9090/api/bank/tx/events \
-H 'content-type: application/json' \
-H 'Idempotency-Key: "live-0001"' \
-d '{"event_type":"bank.ledger_entry","data":{"account":"acct-3","kind":"Credit","amount":"7.00","note":"first deposit"}}'
curl -XPOST http://127.0.0.1:9090/api/bank/tx/events \
-H 'content-type: application/json' \
-H 'Idempotency-Key: "live-0002"' \
-d '{"event_type":"bank.ledger_entry","data":{"account":"acct-1","kind":"Debit","amount":"0.99","note":"coffee"}}'Each endpoint answers 202 Accepted only after the submission is committed to its source’s journal, and the answer names the committed event.
{"committed":1,"duplicates":0,"rejected":0,"unknown":0,"results":[{"index":0,"outcome":"committed","event_id":"01JZ7Q3M2T8V5K9W4X6Y1N0P3R"}]}If a response goes missing, send the identical request again with the same key. The endpoint answers "outcome":"duplicate" with the original event_id, so the transaction posts once. Reusing a key with different content is refused with 422 and the code idempotency_key_conflict.
After the live transactions, Carol’s account shows a current balance of $7.00, and Alice’s shows $7.27, with her live coffee as the fifth entry after the four from the file.
Account: acct-3 (Carol)
Current: $7.00 | Available: $7.00
┌───┬────────┬────────┬────────┬───────┬─────────┬───────────────┐
│ # │ Kind │ Amount │ Credit │ Debit │ Balance │ Note │
├───┼────────┼────────┼────────┼───────┼─────────┼───────────────┤
│ 1 │ Credit │ $7.00 │ $7.00 │ │ $7.00 │ first deposit │
└───┴────────┴────────┴────────┴───────┴─────────┴───────────────┘
Credits: $7.00 | Debits: $0.00 | Tx: 1
Account: acct-1 (Alice)
Current: $7.27 | Available: $7.27
┌───┬────────┬────────┬────────┬───────┬─────────┬───────────┐
│ # │ Kind │ Amount │ Credit │ Debit │ Balance │ Note │
├───┼────────┼────────┼────────┼───────┼─────────┼───────────┤
│ 1 │ Credit │ $2.50 │ $2.50 │ │ $12.50 │ paycheck │
│ 2 │ Debit │ $0.99 │ │ $0.99 │ $11.51 │ coffee │
│ 3 │ Debit │ $4.50 │ │ $4.50 │ $7.01 │ groceries │
│ 4 │ Credit │ $1.25 │ $1.25 │ │ $8.26 │ refund │
│ 5 │ Debit │ $0.99 │ │ $0.99 │ $7.27 │ coffee │
└───┴────────┴────────┴────────┴───────┴─────────┴───────────┘
Credits: $3.75 | Debits: $6.48 | Tx: 5We call the output you’re seeing above a projection. Essentially, the stream table join matches each transaction against its account, and the stateful stage “folds” the posted entries into an account state. The account state includes a current balance. The sink in this example renders the latest projection after each transaction to the console.
Try posting a transaction for an account that does not exist:
curl -XPOST http://127.0.0.1:9090/api/bank/tx/events \
-H 'content-type: application/json' \
-H 'Idempotency-Key: "live-0003"' \
-d '{"event_type":"bank.ledger_entry","data":{"account":"acct-unknown","kind":"Credit","amount":"1.00"}}'The endpoint still answers 202 with "outcome":"committed" because the payload decoded as a LedgerEntry and its row was committed. The join drops it later, because no account named acct-unknown was ever opened.
In a real-world system you may want to signal back rejection above, but it really depends on the architecture of your system.
Many banks’ personal checking and savings account systems would not signal back rejection at the point of ingestion, because reconciliation would then be handled downstream. These are the nuances that event storming and domain modeling should be helping you to work through.
The rest of the tutorial walks through the code that produced everything you just saw, then circles back to the operational surfaces and replay archive that the framework left behind.
Step 2. Feeding the flow from files and HTTP endpoints
One of ObzenFlow’s core features is the ability to define RESTful endpoints and treat them as streaming surface areas, so that every invocation against an endpoint streams data from ObzenFlow’s perspective. By the time the flow sees the RESTful source, it looks like any other typed source (such as a file, a queue, or anything else). ObzenFlow’s sources support both streaming and batch data, and this example uses both for each input. Accounts load as a batch from a YAML file and transactions from a CSV file, and then both stream in over HTTP.
The example splits that work in two. The runner owns the HTTP surface and its lifecycle. The flow builds the file sources from the application’s own settings, and from then on sees only typed sources.
Config and hosting
Open examples/http_ingestion_piggy_bank_demo/runner.rs and look at the body of run_example:
let mut app = FlowApplication::builder()
.with_config_file(CONFIG_FILE)
.with_log_level(LogLevel::Info)
.with_presentation(presentation);
let new_accounts_source = app.http_ingress(AccountIngress, ingress_config(ACCOUNTS_BASE_PATH));
let tx_source = app.http_ingress(LedgerIngress, ingress_config(TX_BASE_PATH));
app.run_blocking(flow::build_flow(new_accounts_source, tx_source))?;Each call to app.http_ingress(...) does two things at once.
- It registers an HTTP surface with the application, which is the route, the deserialization, the readiness wiring, and the ingress telemetry.
- It returns a typed source, which is what the flow reads from. Like the file sources below, the HTTP source asks you for one method,
decode.AccountIngressandLedgerIngressinflow.rssupply it. They nameAccountOpenedandLedgerEntryas the payloads their endpoints accept, and they refuse a negative opening balance and a zero amount.
The two files are configuration, so their paths live in the config file rather than in the code. obzenflow.toml names them in the [app] table, which belongs to the application:
[app]
accounts_file = "examples/http_ingestion_piggy_bank_demo/accounts.yaml"
transactions_file = "examples/http_ingestion_piggy_bank_demo/transactions.csv"The flow reads that table as its own typed settings. In examples/http_ingestion_piggy_bank_demo/flow.rs, build_flow declares the settings type and builds both file sources from it:
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PiggyBankSettings {
accounts_file: PathBuf,
transactions_file: PathBuf,
}
pub fn build_flow(
new_accounts_source: HostedIngressSource<AccountIngress>,
tx_source: HostedIngressSource<LedgerIngress>,
) -> FlowDefinition {
FlowDefinition::materialize_with(move |_runtime_config, settings: PiggyBankSettings| {
let accounts_source = YamlSource::builder(AccountYaml)
.path(settings.accounts_file)
.selection(YamlSelection::SequenceAt("/accounts".into()))
.build()
.map_err(|error| FlowBuildError::StageResourcesFailed(error.to_string()))?;
let ledger_source = CsvSource::builder(LedgerCsv)
.path(settings.transactions_file)
.chunk_size(1)
.build()
.map_err(|error| FlowBuildError::StageResourcesFailed(error.to_string()))?;
// The join, the checkbook and the printer follow, then `flow!`.
})
}FlowDefinition::materialize_with deserializes the [app] table into PiggyBankSettings before your factory runs. A misspelled key such as acounts_file stops startup with an error that names the key and the fields the type expects, and it never prints a value. The run’s manifest records the settings the run used, so every archive shows which files it read.
YamlSource::builder(...) describes the accounts file in the same spirit as the HTTP source. Building the source checks its configuration without opening the file. The source opens the file only when a live run starts. SequenceAt("/accounts") selects the accounts list inside the document, so each entry in that list becomes one record. CsvSource::builder(...) does the same for the transactions file, where each row becomes one record, and chunk_size(1) reads one row at a time.
To start from different accounts or transactions, copy the config file, point accounts_file or transactions_file at another file, and pass the copy with --config <file>. A platform that configures processes through the environment can set OBZENFLOW_CONFIG=<file> instead. Neither the code nor the binary changes.
The result is that flow::build_flow(...) never sees HTTP routes, port numbers, or readiness primitives, and it receives both file paths as typed settings. Hosting lives in runner.rs, and the flow and its file sources live in flow.rs.
That split matters. It keeps flow! source-oriented and lets the same flow definition be hosted under any input boundary that can produce a typed ingress source. In a test, you can drive the same build_flow(...) from in-memory ingress sources, with settings that name fixture files. In production, the HTTP shell adds metrics, an /api/topology endpoint, and the rest of the operational surfaces around the same pipeline.
Decoding the accounts file
The YAML source reads and parses the file for you. It asks you for one method, decode, which turns each record into an AccountOpened fact. AccountYaml supplies that method in examples/http_ingestion_piggy_bank_demo/flow.rs:
impl YamlDecoder for AccountYaml {
type Output = AccountOpened;
fn decode(&self, record: YamlRecord<'_>) -> Result<AccountOpened, YamlDecodeError> {
let account: AccountOpened = record.deserialize()?;
if account.opening_balance.is_negative() {
return Err(YamlDecodeError::invalid_value("opening_balance"));
}
Ok(account)
}
}The method deserializes the record into the domain type, then applies one business rule. An account cannot open with a negative balance. When a record breaks that rule, or is missing a field, the source rejects only that account. It journals a diagnostic naming the entry and the field, and the remaining accounts still load. A file that cannot be read or parsed at all fails the run before any account loads.
The other decoders follow the same pattern. LedgerCsv and LedgerIngress refuse a zero amount, and AccountIngress refuses a negative opening balance. The CSV source rejects only the offending row, and an endpoint answers a rule-breaking or malformed submission with 400. Either way, the system journal records the refusal with the field it names.
In this example both inputs have a history that exists before the service starts, and both keep arriving for as long as it runs. A file matches the first shape and an HTTP endpoint matches the second. Each source carries one typed payload, which keeps every input contract explicit, and a merge gives each pair one stream. Accounts feed a join catalog and transactions feed the forward path.
Finite and infinite sources
In Getting Started, the source was a finite in-memory collection. The pipeline ran, drained, and exited. Service-shaped flows also need a different kind of source, one that stays alive, accepts events as they arrive, and never signals end of stream on its own.
The piggy bank example uses two sources of each kind:
batch_accounts = source!(AccountOpened => accounts_source);
batch_tx = source!(LedgerEntry with { rate_limit(2.0) } => ledger_source);
live_accounts = async_infinite_source!(AccountOpened => new_accounts_source);
live_tx = async_infinite_source!(
LedgerEntry with { rate_limit(50.0) } => tx_source
);The source! macro wraps a finite source. The batch sources read every entry in accounts.yaml and every row in transactions.csv once, then signal end of stream. The async_infinite_source! macro wraps an asynchronous producer that runs until the application shuts down. That is the right shape for an HTTP feed, an upstream queue consumer, or any other source that does not end on its own. The rate_limit(50.0) middleware caps live transaction ingress at 50 events per second, and rate_limit(2.0) paces the CSV at about two rows a second, so you can watch the checkbook fill in. The two account sources have no with clause, so no middleware applies to them.
Downstream of a source, transforms, accumulators, joins, and so forth don’t really care whether a source is finite, like a YAML or CSV file, or infinite, like a streaming RESTful endpoint. All they see are typed events. Essentially, when a payload is posted against a RESTful endpoint, that post is accepted and written to ObzenFlow’s journal like any other event in the flow. The same goes for each account and transaction read from a file.
The only real practical difference between a finite and an infinite source is that a finite source will eventually end naturally when ObzenFlow processes the last entry, whereas an infinite source is never-ending and only stops listening and processing when the program ends.
Merging batch and live input
Each pair of sources meets in a merge before the join.
accounts = merge!(AccountOpened => merges::then_live);
transactions = merge!(LedgerEntry => merges::then_live);A merge gives several producers of one fact type a single downstream stream. The then_live strategy passes on every row of the batch source, up to its end of stream, before any row of the live source. Every account in the file loads and every transaction in the CSV posts before the first live request reaches the join, so live input always builds on the complete history from the files. Each merge runs as its own stage with its own journal, so replay and resume reproduce that order exactly.
In this example, the two merged streams play different roles in the flow. The accounts stream feeds the reference catalog inside the join. The transactions stream is the forward path. The flow treats them differently because of how they are wired downstream, which is the subject of the next step.
Step 3. Validating transactions with stream-table joins
The posted stage is where the most important new concept in this tutorial lives. It is the first time you have seen a join! in this tutorial series, and it is the stage that turns a raw HTTP request into a trusted, enriched fact.
The join comes in two parts in examples/http_ingestion_piggy_bank_demo/flow.rs. build_flow constructs the join handler before the flow! block, and the posted stage names it:
fn post(account: AccountOpened, entry: LedgerEntry) -> PostedEntry {
PostedEntry {
account: entry.account,
owner: account.owner,
kind: entry.kind,
amount: entry.amount,
opening_balance: account.opening_balance,
note: entry.note,
originator: entry.originator,
}
}
let post_entry = joins::inner_then_live(
|account: &AccountOpened| account.account.clone(),
|entry: &LedgerEntry| entry.account.clone(),
post,
);
// Inside flow! { stages: { ... } }
posted = join!(
catalog accounts: AccountOpened,
LedgerEntry -> PostedEntry => post_entry
);Read the join in three layers.
- The
catalog accounts: AccountOpenedline declares the reference side of the join. Theaccountsmerge declared in Step 2 is held inside this join as a catalog ofAccountOpenedevents, keyed by account id. The catalog is a side input to the join stage, and it never flows forward through the pipeline. - The
LedgerEntry -> PostedEntryline declares the forward contract. The join receivesLedgerEntryevents on its stream side and emitsPostedEntryevents downstream. The(accounts, transactions) |> postedline in the topology block connects both merges to the join, with the catalog first and the transaction stream second. - The
joins::inner_then_live(...)helper builds the handler from two key closures and a merge function. The first closure extracts the join key from the catalog side, which isaccount.account, and its&AccountOpenedannotation tells Rust which type it reads. The second extracts the join key from the stream side, which isentry.accounton a&LedgerEntry. The third argument, thepostfunction, is the merge function. It runs once per matched pair and produces thePostedEntrythat downstream stages will see.
A then-live join works in two phases. First it hydrates its catalog with every account from the file and posts every transaction from the CSV against them, up to the end of both files, so a row from the file can never race its own account and miss. Then it goes live over both inputs. An account opened over HTTP joins the catalog, and a transaction posted after its account opens finds it.
In the live phase, the catalog keeps receiving updates while transactions arrive. A transaction submitted before its account exists finds no match, and transactions submitted after the account opens will match and post. That is why Step 1 opens Carol’s account and waits for its 202 before posting to it. A service with no batch history at all can use joins::inner_live, which starts in that live phase.
The “inner” half is exactly what it sounds like. Only matched pairs flow downstream. Unmatched transactions produce no posted event. That is a design choice. In a more elaborate service you might keep unmatched entries as their own RejectedEntry event and surface them on a separate sink, but the canonical example keeps the join inner so the rest of the pipeline can assume every event it sees is already validated.
The most ObzenFlow-shaped move in this example is that validation doesn’t live in an if statement. It lives in the join.
A LedgerEntry is a request from the edge, and a PostedEntry is journaled only if the join was successful. The structural fact that downstream stages only ever see PostedEntry types is what keeps the rest of the pipeline simple. Domain invariants are enforced by the type system and by the topology, not by handler code.
It is worth repeating the stages and topology code from earlier so it really makes sense how joins are wired up. Below you can see how accounts and transactions slot into the join and then how the join is wired into the flow itself.
stages: {
batch_accounts = source!(AccountOpened => placeholder!());
batch_tx = source!(LedgerEntry => placeholder!());
live_accounts = async_infinite_source!(AccountOpened => placeholder!());
live_tx = async_infinite_source!(LedgerEntry => placeholder!());
accounts = merge!(AccountOpened => merges::then_live);
transactions = merge!(LedgerEntry => merges::then_live);
posted = join!(
catalog accounts: AccountOpened,
LedgerEntry -> PostedEntry => placeholder!()
);
checkbook = stateful!(PostedEntry -> CheckbookSnapshot => placeholder!());
printer = sink!(CheckbookSnapshot => placeholder!());
},
topology: {
batch_accounts |> accounts;
live_accounts |> accounts;
batch_tx |> transactions;
live_tx |> transactions;
(accounts, transactions) |> posted;
posted |> checkbook;
checkbook |> printer;
}One of the things to pay attention to that might be a little new is that when you are reading an ObzenFlow, it is much more important to think about types.
Above, accounts are a table that is being hydrated from accounts.yaml first and from the accounts endpoint after that. Then, if you look at the topology definition, transactions flow into the posted stage, which is a join. We wire the account catalog into the catalog position of the join, then that second line of the join specifies the stream-side, which is read as input type -> output type => the handler that you will define later on.
The rest of the example is wired together very similarly to the Getting Started character transformer that we saw in the first tutorial.
Step 4. Maintaining bank balances with stateful projections
The checkbook stage is the projection, which receives every PostedEntry, folds it into per-account state, and emits a CheckbookSnapshot for downstream readers.
let checkbook_handler = stateful::group_by(
|entry: &PostedEntry| entry.account.clone(),
AccountLedger::record,
|account: &AccountId, ledger: &AccountLedger| ledger.snapshot(account),
)
.emit(emit::always)
.updated_groups();
// Inside flow! { stages: { ... } }
checkbook = stateful!(
PostedEntry -> CheckbookSnapshot => checkbook_handler
);Three details are worth expanding on.
One ledger per account with group_by
In char_transform, the stateful stage was stateful::reduce, which folds every event into one accumulator. A checkbook needs one accumulator per account, which is what stateful::group_by keeps. It takes three functions.
- The key function picks the account id out of each
PostedEntry. - The update function,
AccountLedger::record, folds one entry into that account’s ledger. - The output function turns one account’s ledger into the
CheckbookSnapshotthat downstream stages see.
Each account’s ledger starts from AccountLedger::default(), but an account’s opening balance is not zero. It arrives inside the first PostedEntry for that account, carried in the opening_balance field, so record seeds the balance from that field when the ledger has no transactions yet. The full type lives in examples/http_ingestion_piggy_bank_demo/handlers.rs, and the rest of the accumulation logic is arithmetic on exact cents through the money types:
pub fn record(&mut self, entry: &PostedEntry) {
if self.transactions.is_empty() {
self.current_balance = entry.opening_balance;
}
self.owner = entry.owner.clone();
match entry.kind {
EntryKind::Credit => {
self.total_credits = self.total_credits.plus(entry.amount);
self.current_balance = self.current_balance.credited(entry.amount);
}
EntryKind::Debit => {
self.total_debits = self.total_debits.plus(entry.amount);
self.current_balance = self.current_balance.debited(entry.amount);
}
}
// record also appends the entry to the account's transaction list.
}Choosing an emission strategy: emit::always instead of emit::on_eof
In char_transform, the reducer used .emit(emit::on_eof). It accumulated text chunks and emitted exactly one TransformedText event when the upstream source signalled end of stream. That is the right strategy for a finite batch.
A live service does not have an end of stream, and it has read-side consumers that want to see the latest state after every input. The piggy bank therefore picks a different strategy, emit::always. Every PostedEntry produces a fresh CheckbookSnapshot immediately, and a downstream sink, database table, dashboard, or another flow can subscribe to that stream and stay current with no extra plumbing.
Publishing only the account that changed
A group_by keeps many ledgers, so after .emit(...) it asks which of them each emission publishes. .updated_groups() publishes only the groups updated since the previous emission. Paired with emit::always, every posted entry produces exactly one snapshot, for the account it just moved. .all_groups() would publish every account at every emission, which suits a periodic full statement better than a live feed.
The split between accumulation and emission is identical to Getting Started. The update function describes how to change the state, and the emission strategy describes when that state becomes an output event.
The framework ships five accumulators, reduce, group_by, conflate, top_n, and top_n_by, and ObzenFlow’s Stage Vocabulary shows each one. When none of them fits, you can implement the Accumulator trait for a state and output of your own and attach an emission strategy the same way.
The sink in this example renders the snapshot to the console so you can see the shape directly. In a larger service, the same CheckbookSnapshot stream could write rows into a database, push to a queue, update a search index, or feed another flow. The projection stage is where read-side state is materialized once and reused everywhere.
Step 5. Operational surfaces, evidence, and replay
In this final section, we’ll explain a little more of the operational surface area of an ObzenFlow program, which includes all sorts of topics from journal manifests to middleware and metrics, and just simply how a program runs end-to-end, and what is included out of the box.
While the service is running, you can inspect the operational surfaces the framework gives you for free. They come from FlowApplication once the HTTP server is enabled, which provides all of the operational machinery that most programs look for, like metrics and middleware.
Below is a collection of endpoints that the example provides to you for free, excluding the endpoints that you define yourself. You can see that we expose details about metrics, the topology, and health checks. This comes wired right out of the box.
curl http://127.0.0.1:9090/metrics
curl http://127.0.0.1:9090/api/topology
curl http://127.0.0.1:9090/api/bank/accounts/health
curl http://127.0.0.1:9090/api/bank/tx/healthWhen you stop the example with Ctrl-C, ObzenFlow leaves a run archive under:
target/http-ingestion-piggy-bank-demo-logs/flows/<run-id>/Every stage has its own journal file, including the four sources, the two merges, the join, the stateful stage, and the sink. The run_manifest.json records the flow structure, stage metadata, and journal mappings for the run. That archive is the durable evidence trail for every account fact, ledger entry, posted entry, and emitted checkbook snapshot.
Replay reads the archive as input. The framework swaps all four sources for their archived journals and reruns the flow against the same historical inputs. Replay never reopens accounts.yaml or transactions.csv, so you can edit or delete either file and the replay still sees the accounts and transactions exactly as the original run read them. Both endpoints answer 503 with not_ready throughout, because a replay admits no new input. The manifest’s configuration evidence records both file paths under app, beside the framework’s own settings.
RUST_LOG=info cargo run -p obzenflow --example http_ingestion_piggy_bank_demo --features prometheus,web-host -- \
--replay-from target/http-ingestion-piggy-bank-demo-logs/flows/<run-id> --verify--verify compares the replay with the recorded run once it ends, and its exit code reports the result.
The point worth carrying forward from this tutorial is that the same journal-and-replay model from char_transform applies cleanly to a live HTTP-backed service. The input boundary moved out to files and HTTP endpoints, but every stage still produces a durable journal, and the same archive shape that the character transformer produced is what the piggy bank produces.
/metrics, /api/topology, and the /api/flow/* control plane unauthenticated for local development. To exercise the recommended API-key setup, provision OBZENFLOW_PIGGY_BANK_CONTROL_PLANE_AUTH out of band with the complete Authorization header value clients must send, then run with the obzenflow.auth.toml config bundled with the example. The ingress endpoints stay unauthenticated in this example.Step 6. Stop the service, then resume it
Replay reruns a finished archive and drains. A live service needs one more verb. When you pressed Ctrl-C earlier, the run was recorded as cancelled, and every fact it had processed was already durable in its journals. --resume-from continues that same run rather than starting a new one, and a cancelled archive is a valid resume input with no extra flags.
Point it at the same run directory you replayed in Step 5:
RUST_LOG=info cargo run -p obzenflow --example http_ingestion_piggy_bank_demo --features prometheus,web-host -- \
--resume-from target/http-ingestion-piggy-bank-demo-logs/flows/<run-id>Resume runs in two phases.
- First it catches up. The runtime re-reads the recorded journals through the same reconstruction engine that replay uses, re-folding every posted entry back into the checkbook state. The recorded snapshots render again, each marked as a replayed delivery. While catch-up runs, both endpoints return
503with aRetry-Afterheader instead of admitting fresh input, so a new command can never interleave with history. With an archive this small, that window lasts only a moment. - When catch-up reaches the end of the recorded history, the live sources cross to live and their endpoints open. From that point the run accepts new input, and the flow behaves as though it had never stopped.
Both file sources already reached their end of stream in the original run, so catch-up restores the accounts and the CSV transactions from their journals and never reopens either file. Edits to the files after the original run started do not reach the resumed run. To load changed files, start a fresh run. If a run stops before the CSV is drained, resume continues the file after its last committed row.
The same holds when you resume with a config file that names another accounts file. Before catch-up starts, the resumed run prints Configuration differs from <run-dir>: app.accounts_file, and obzenflow show of the resumed run lists the old and new paths. That report explains why the configuration and the journal disagree.
Post one more transaction for Alice.
curl -XPOST http://127.0.0.1:9090/api/bank/tx/events \
-H 'content-type: application/json' \
-H 'Idempotency-Key: "live-0004"' \
-d '{"event_type":"bank.ledger_entry","data":{"account":"acct-1","kind":"Credit","amount":"1.00","note":"back online"}}'The snapshot continues from the recorded balance. Alice’s account was at $7.27 when the service stopped, so this credit moves it to $8.27, and her transaction table now shows six entries. The state came from re-folding the recorded journals during catch-up, and the new entry extends that same history.
The proof lives in the resumed run’s archive rather than in the console output. The resumed run writes its own run_manifest.json under a new run directory, and that manifest carries a resume block recording the run’s lineage.
"resume": {
"resumed_from": "target/http-ingestion-piggy-bank-demo-logs/flows/<run-id>",
"resume_generation": 1
}The resumed journals extend the recorded history under the same run identity. That closure is the point of the design. The resumed run can itself be replayed for verification, and if it is interrupted in turn, it can be resumed again.
During catch-up the console sink re-renders the recorded snapshots. That is safe here because a console projection is idempotent, and the framework’s console sink declares itself so. A sink that wrote to a non-idempotent external destination, such as a POST to a payment processor, would be refused at resume until it declared its delivery safety or you explicitly accepted duplicate delivery. The runtime fails loud rather than silently delivering twice.
Next steps
You have now seen ObzenFlow load batch history from files, handle write-side HTTP traffic, join live events against reference data, produce a running projection from journaled facts, and resume an interrupted service from its own journals. The same pattern applies to webhook receivers, command-ingestion services, operational read models, and any workflow where facts accumulate over time.
When you are ready to keep going, Run Live AI Inference from a Real Endpoint takes the same flow model into a model-backed workload. That tutorial adds HTTP pull, an ai! stage that chunks, maps, and reduces with a model, and prompt evidence on top of the flow model you have already seen.
ObzenFlow’s architecture is worth reading once the tutorials feel natural, if you want the rationale behind why ObzenFlow is shaped this way.