Guide: a banking application¶
This guide builds the core of a bank on OliviaDB end to end: customers, accounts, cards,
card payments and transfers between customers; the schema with two profiles (the bank's
core service and a support agent); the application code; and the tests that check it
against a live server. The code is Python; the calls are the same in every client
(connect an application). Everything below runs in CI as it stands
(tools/docs-snippets.py, group guide-bank).
1. Model the aggregates¶
Decide first what is read and changed together. For a retail bank that is the customer: a teller's screen, a statement, an onboarding check all read one customer with its accounts and cards, and a payment changes one account of one customer. So:
Customeris the aggregate. Its accounts, each account's entries (newest first) and its cards are children: one customer is one key range, read in one call.- The balance is a field of the account, changed in the same transaction as the entry that moves it. A statement is a range of entries; no sum over history at read time.
- Every entry has a
ref, the id of the payment or transfer that made it, unique through an index. That makes every posting idempotent: a retried payment finds its ref and stops. - A transfer between customers is an aggregate of its own. A transaction writes within
one aggregate record (see below), so a transfer is a
Transferrecord with a state, a debit posting on the payer and a credit posting on the payee, each idempotent by its ref. - Personal data is marked
piiand sealed per customer (subject id): erasing a customer destroys its key, and every copy of its data becomes unreadable (data subjects).
2. The schema and the profiles¶
schema bank version 1
aggregate Customer {
key id: string(12)
subject id // personal data sealed per customer, erasable
history 7y
1 name: string(80) pii(name)
2 tax_id: string(12) pii(tax_id)
3 branch: string(4)
child Account [number: string(20)] unique {
1 currency: string(3)
2 balance: decimal(18,2)
3 status: enum { open = "O", closed = "C" }
child Entry [posted: timestamp desc, seq: int32] {
1 amount: decimal(18,2)
2 ref: string(32) // payment or transfer id: one entry per ref
3 memo: text
}
}
child Card [pan: string(19)] unique {
1 account: ref ../Account
2 status: enum { active = "A", blocked = "B" }
}
}
aggregate Transfer {
key id: string(32)
1 from_customer: string(12)
2 from_account: string(20)
3 to_customer: string(12)
4 to_account: string(20)
5 amount: decimal(18,2)
6 state: enum { pending = "P", debited = "D", done = "C" }
}
index card_by_pan on Customer/Card(pan) unique
index entry_by_ref on Customer/Account/Entry(ref) unique
profile core for service "bank-core" {
consistency strong
get Customer/{id}/**
list Customer/{id}/Account
range Customer/{id}/Account/{n}/Entry by posted limit 100
insert Customer
insert Customer/{id}/Account
insert Customer/{id}/Account/{n}/Entry
insert Customer/{id}/Card
update Customer/{id}/Account/{n} fields(balance, status)
update Customer/{id}/Card/{pan} fields(status)
lookup card_by_pan -> Customer
lookup entry_by_ref -> Customer
get Transfer/{id}
insert Transfer
update Transfer/{id} fields(state)
}
profile support for agent "support" {
consistency strong
rows Customer where branch = $user.branch
mask Customer.tax_id partial(4)
get Customer/{id}/** except Customer/Account/Entry.memo
}
coreis the bank's own service: it opens customers, accounts and cards, posts entries and updates balances, and runs transfers. It may update onlybalanceandstatusof an account andstatusof a card.supportis an AI support agent: it reads customers of the branch of the person it acts for (rows ... where branch = $user.branch, the attribute from its credentials), sees the tax id masked to its last four characters, does not see entry memos, and writes nothing.
oliviadb profile check bank.olv confirms that every granted path is served by a key range
or an index.
3. Run it¶
A server for the bank with one key per principal (the support key carries the branch
attribute its rows rule reads):
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 365 \
-subj /CN=localhost -addext subjectAltName=DNS:localhost,IP:127.0.0.1 \
-addext basicConstraints=critical,CA:FALSE -addext extendedKeyUsage=serverAuth \
-keyout server.key -out server.pem 2>/dev/null
(umask 077; openssl rand -hex 24 > api-key-core; openssl rand -hex 24 > api-key-support)
cp api-key-core api-key
cat > config.json <<EOF2
{"listen": "127.0.0.1:8443", "native_listen": "127.0.0.1:7655", "dir": "data",
"tls": {"cert": "server.pem", "key": "server.key"}, "schema": "bank.olv",
"api_keys": [
{"sha256": "$(oliviadb-server --hash-key "$(cat api-key-core)")", "tenant": "bank",
"principal": "bank-core", "profiles": ["read", "memory"]},
{"sha256": "$(oliviadb-server --hash-key "$(cat api-key-support)")", "tenant": "bank",
"principal": "support", "profiles": ["read"], "attrs": {"branch": "B1"}}]}
EOF2
oliviadb-server --config config.json >> server.log 2>&1 &
echo $! > oliviadb.pid
until curl -fsS --cacert server.pem https://localhost:8443/readyz; do sleep 0.2; done
4. The application¶
"""A bank's core operations on OliviaDB (docs/guide-bank.md): customers, accounts, cards,
card payments and transfers between customers."""
from decimal import Decimal
from oliviadb import OliviaDbError
from oliviadb.native import NativeClient
class Refused(Exception):
"""The bank refuses the operation (card blocked, funds insufficient, ...)."""
class Bank:
def __init__(self, db: NativeClient):
self.db = db
def _write(self, method, path, body):
"""A write; an error status raises OliviaDbError (its status and problem document)."""
return self.db.write(method, path, body)[1]
def read(self, path, tree=False):
"""A node (or a tree) as JSON, with the version it was read at."""
return self.db.get(path, {"tree": "true"} if tree else {}).to_json(False)
# ---- opening ----
def open_customer(self, cid, name, tax_id, branch):
self._write("POST", f"Customer/{cid}", {"fields": {"name": name, "tax_id": tax_id, "branch": branch}})
def open_account(self, cid, number, currency):
self._write("POST", f"Customer/{cid}/Account/{number}",
{"fields": {"currency": currency, "balance": "0", "status": "open"}})
def issue_card(self, cid, pan, account):
self._write("POST", f"Customer/{cid}/Card/{pan}", {"fields": {"account": account, "status": "active"}})
# ---- posting ----
def applied(self, ref):
"""Whether an entry with this payment or transfer id exists (index entry_by_ref)."""
return len(self.db.lookup("entry_by_ref", {"key": ref}).nodes()) > 0
def post(self, cid, number, amount: Decimal, ref, memo, posted, seq=1):
"""One entry and the balance it changes, in one transaction. A debit is refused when
the balance would go below zero; the balance read is checked unchanged at commit
(412 otherwise: read again and retry). Returns False when the ref was applied before."""
acct = f"Customer/{cid}/Account/{number}"
for _ in range(5):
if self.applied(ref):
return False
node = self.read(acct)
if node["fields"]["status"] != "open":
raise Refused(f"account {number} is closed")
if Decimal(node["fields"]["balance"]) + amount < 0:
raise Refused(f"account {number}: insufficient funds")
try:
self.db.txn({"ops": [
{"op": "unchanged", "path": acct, "since": node["version"]},
{"op": "insert", "path": f"{acct}/Entry/{posted},{seq}",
"fields": {"amount": str(amount), "ref": ref, "memo": memo}},
{"op": "update", "path": acct, "add": {"balance": str(amount)}},
]})
return True
except OliviaDbError as e:
if e.status == 409 and self.applied(ref):
return False # a concurrent retry of the same payment won
if e.status != 412: # 412: the account changed since it was read
raise
raise RuntimeError(f"post {ref}: the account kept changing")
def card_payment(self, pan, amount: Decimal, ref, merchant, posted):
"""A card payment: the card found by its number, its account debited."""
hits = self.db.lookup("card_by_pan", {"key": pan}).nodes()
if not hits:
raise Refused("unknown card")
card_path = hits[0].hit # Customer/<id>/Card/<pan>
cid = card_path.split("/")[1]
card = self.read(card_path)["fields"]
if card["status"] != "active":
raise Refused("card blocked")
return self.post(cid, card["account"], -amount, ref, merchant, posted)
# ---- transfers between customers ----
def transfer(self, tid, frm, to, amount: Decimal, posted):
"""Money from one customer's account to another's. One transaction writes one
customer, so a transfer is a Transfer record and two postings, each idempotent by its
ref: run it again after any failure and it completes without posting twice."""
try:
self._write("POST", f"Transfer/{tid}", {"fields": {
"from_customer": frm[0], "from_account": frm[1], "to_customer": to[0], "to_account": to[1],
"amount": str(amount), "state": "pending"}})
except OliviaDbError as e:
if e.status != 409: # 409: the transfer exists, go on from its state
raise
t = self.read(f"Transfer/{tid}")["fields"]
if t["state"] == "pending":
self.post(frm[0], frm[1], -amount, f"{tid}-D", f"transfer {tid}", posted)
self._write("PATCH", f"Transfer/{tid}", {"fields": {"state": "debited"}})
if t["state"] in ("pending", "debited"):
self.post(to[0], to[1], amount, f"{tid}-C", f"transfer {tid}", posted)
self._write("PATCH", f"Transfer/{tid}", {"fields": {"state": "done"}})
What makes it correct:
- One transaction per posting: the entry, the balance change (
add, relative: no lost update) and a precondition that the account isunchangedsince the version the balance check read. If another payment committed in between, the server answers 412 and the posting reads again: no overdraft can slip between check and write. - Idempotency by
ref: the unique indexentry_by_refrefuses a second entry with the same ref, so a retried payment (a timeout, a crash, a 504outcome-unknown) posts at most once;appliedchecks it first. - Transfers between customers are a small saga: the
Transferrecord says how far it got, and every step is idempotent, so runningtransferagain after any failure finishes it without posting twice.
Transfers between customers¶
A transaction writes one aggregate record (txn scope aggregate, the only scope served to
services and agents today). Two customers are two records, so a transfer cannot be one
transaction; the pattern above (a record of the transfer, idempotent postings, a state) is
the standard answer, and is what the test exercises by running the transfer twice.
Transactions across records are part of the distributed engine, in development for OliviaDB
Enterprise (multi-Raft plan).
The same with typed code¶
The application above works on paths and JSON, which keeps every request visible. With code
generated for the core profile, the same payment is written against models: the account is
read as an Account, the entry is an Entry.New, and run_txn repeats the read and the
writes when another writer came first (the 412 of the unchanged precondition), which the loop
above does by hand. An operation the profile does not grant does not type-check (mypy).
"""A card payment with the code generated for profile core (docs/guide-bank.md)."""
import datetime
import os
from decimal import Decimal
from bank_core import Account, AccountStatus, Customer, Db, Entry, Index
from oliviadb.dsl import Txn
from oliviadb.native import NativeClient
class Refused(Exception):
pass
def post(db: Db, cid: str, number: str, amount: Decimal, ref: str, memo: str, posted: datetime.datetime) -> bool:
"""One entry and the balance in one transaction, once per ref, never below zero."""
if db.lookup(Index.entry_by_ref(ref)) is not None:
return False # applied before
acct = Customer.key(cid).account(number)
def work(t: Txn) -> None:
a, version = t.get(acct) # the account as a model, and the version it was read at
if a.status != AccountStatus.OPEN:
raise Refused(f"account {number} is closed")
if a.balance + amount < 0:
raise Refused(f"account {number}: insufficient funds")
t.unchanged_since(acct, version) # 412 if anyone wrote it since: run_txn runs work again
t.insert(acct.entries(), Entry.New(posted=posted, seq=1, amount=amount, ref=ref, memo=memo))
t.update(acct, Account.Patch(add_balance=amount))
db.run_txn(work)
return True
with NativeClient.connect_tls("localhost", 7655, "token", open("api-key-core").read().strip(),
ca_file=os.environ["OLIVIADB_CA_FILE"]) as native:
db = Db(native)
db.insert(Customer.all(), Customer.New(id="T1", name="Ada Lovelace", tax_id="1", branch="B1"))
db.insert(Customer.key("T1").accounts(),
Account.New(number="T1-EUR", currency="EUR", balance=Decimal("20.00"), status=AccountStatus.OPEN))
at = datetime.datetime(2026, 12, 1, 9, tzinfo=datetime.timezone.utc)
assert post(db, "T1", "T1-EUR", Decimal("-12.50"), "pay-T1-1", "coffee", at)
assert not post(db, "T1", "T1-EUR", Decimal("-12.50"), "pay-T1-1", "coffee", at) # the same ref
try:
post(db, "T1", "T1-EUR", Decimal("-50.00"), "pay-T1-2", "rent", at)
raise AssertionError("overdrawn")
except Refused:
pass
assert db.get(Customer.key("T1").account("T1-EUR")).balance == Decimal("7.50")
print("typed payment: ok")
oliviadb schema client bank.olv --lang python --profile core --out .
OLIVIADB_CA_FILE=$PWD/server.pem python3 typed_post.py
5. The tests¶
The expected balances are worked out by hand from the operations; the support agent's checks follow from its profile.
"""The bank's operations against a live server (docs/guide-bank.md). Expected balances are
worked out by hand from the operations below."""
import os
from decimal import Decimal
from oliviadb import OliviaDbError
from oliviadb.native import NativeClient
from bank_app import Bank, Refused
env = os.environ
def connect(key):
return NativeClient.connect_tls("localhost", 7655, "token", key, ca_file=env["OLIVIADB_CA_FILE"])
def balance(bank, cid, number):
return Decimal(bank.read(f"Customer/{cid}/Account/{number}")["fields"]["balance"])
with connect(open("api-key-core").read().strip()) as db:
bank = Bank(db)
bank.open_customer("C1", "Ada Lovelace", "123456789012", "B1")
bank.open_customer("C2", "Alan Turing", "987654321098", "B2")
bank.open_account("C1", "C1-EUR", "EUR")
bank.open_account("C2", "C2-EUR", "EUR")
bank.issue_card("C1", "4111111111111111", "C1-EUR")
assert bank.post("C1", "C1-EUR", Decimal("100.00"), "dep-1", "deposit", "2026-12-01T09:00:00Z")
# A card payment, then the same payment again (a retry): debited once.
assert bank.card_payment("4111111111111111", Decimal("12.50"), "auth-1", "Coffee Roasters", "2026-12-01T10:00:00Z")
assert not bank.card_payment("4111111111111111", Decimal("12.50"), "auth-1", "Coffee Roasters", "2026-12-01T10:00:00Z")
assert balance(bank, "C1", "C1-EUR") == Decimal("87.50")
# More than the balance: refused, nothing written.
try:
bank.card_payment("4111111111111111", Decimal("500.00"), "auth-2", "Bike Shop", "2026-12-01T11:00:00Z")
raise AssertionError("an overdraft went through")
except Refused:
pass
assert balance(bank, "C1", "C1-EUR") == Decimal("87.50")
# A transfer, run twice (as after a crash): applied once on each side.
bank.transfer("T1", ("C1", "C1-EUR"), ("C2", "C2-EUR"), Decimal("37.50"), "2026-12-01T12:00:00Z")
bank.transfer("T1", ("C1", "C1-EUR"), ("C2", "C2-EUR"), Decimal("37.50"), "2026-12-01T12:00:00Z")
assert balance(bank, "C1", "C1-EUR") == Decimal("50.00")
assert balance(bank, "C2", "C2-EUR") == Decimal("37.50")
assert bank.read("Transfer/T1")["fields"]["state"] == "done"
# The support agent: its branch only, the tax id masked to its last four characters, no writes.
with connect(open("api-key-support").read().strip()) as db:
ada = db.get("Customer/C1", {}).to_json(False)["fields"]
assert ada["tax_id"].endswith("9012") and "12345678" not in ada["tax_id"], ada
# 403: no grant to write; 404: a customer of another branch is not visible.
for call, want in [(lambda: db.write("POST", "Customer/C9", {"fields": {"name": "x", "tax_id": "x", "branch": "B1"}}), 403),
(lambda: db.get("Customer/C2", {}), 404)]:
try:
call()
raise AssertionError("the support agent got through")
except OliviaDbError as e:
assert e.status == want, e
print("bank: all checks passed")
OLIVIADB_CA_FILE=$PWD/server.pem python3 test_bank.py
6. Where to go from here¶
- Reads for screens:
GET Customer/C1?tree=true&each=20reads a customer with each account's newest 20 entries in one call;rangegrants page through older entries (native aggregates). - Events for other systems: the change stream gives every change of every customer,
in order, resumable (
GET /v1/changes, change stream). - Agents: the
supportprofile is enforced the same way over MCP (MCP server). - Typed code: the
coreprofile's models and queries in Rust, Java, TypeScript or Python (oliviadb schema client bank.olv --lang rust|java|ts|python --profile core, typed clients); the payment above shows the Python version.
Ask your agent
Using the oliviadb-develop skill, add standing orders to this bank: a schema change with a new child type of Account (codes pinned), a profile grant, the code that executes due orders idempotently, and tests against a local server.