An event-sourced, double-entry banking ledger in .NET 10. Every movement debits one account and credits another, nothing is ever updated in place, and any balance can be rebuilt from the events that produced it.
Work in progress. The domain model, the event store (PostgreSQL or SQL Server), the command and query layer and the HTTP API are in place; the transactional outbox is next.
In a lot of banking software the balance is a column that gets overwritten, and the audit trail is a separate table you hope is complete. When a number looks wrong, working out how it got there is slow and painful.
A ledger built on events turns that around. The events are the record, the balance is derived from them, and the history is the same thing as the audit. Double entry adds the rule that money never appears or disappears: for every posting, debits equal credits.
This repo is my take on how that should look in modern .NET, without a framework hiding the interesting parts.
Done:
MoneyandCurrencyvalue objects: no mixing currencies, no amounts finer than the currency settles in, banker's rounding on multiplication.Ibanwith per-country length and mod-97 check, and a strongly typedAccountId(time-ordered v7 Guid).Accountaggregate (open, freeze, unfreeze, close) built from its events on a small aggregate root with versioning.- Journal entries of two or more postings that must balance in every currency, checked with FsCheck property tests (ADR-0004).
- Business rule failures come back as
Resultwith stable error codes; exceptions are kept for bugs (ADR-0003). - Event store on a single table: optimistic concurrency per stream, and a global position that readers can follow without skipping a late commit. It runs on PostgreSQL or SQL Server and both pass the same contract tests. Positions come from an identity column that is assigned before commit, so appends take a lock first: an advisory lock on PostgreSQL,
sp_getapplockon SQL Server. - Snapshots every N events (100 by default). They are only a cache: a missing or unreadable snapshot just means a longer replay.
- Benchmarks for appends, stream reads and the SQL Server read model, with the results in docs/performance.md. One append takes about 2.4 ms on PostgreSQL and 4.3 ms on SQL Server; a 50-line statement page about 1.4 ms with compiled EF Core queries.
- Commands and queries through a small hand-written dispatcher, one handler per message (ADR-0007). Commands run through tracing, logging and validation behaviors; validation reports every error at once.
- Deposit and Withdraw with the balance kept on the account stream, so two racing withdrawals can't both pass the funds check (ADR-0006).
- Read models fed by a projection runner that follows the store's global position, with a checkpoint per projection (ADR-0012). On SQL Server, balances and statement lines are tables written with EF Core, each event committing its rows and the checkpoint together (ADR-0013).
- Rebuilding a read model without a restart:
POST /admin/projections/{name}/rebuildempties it and replays the store in the background, and a GET on the same route shows how far it has got. Off unlessAdmin:Enabledis true (ADR-0015). GET /accounts/{id}/statement: deposits and withdrawals, oldest first, with the balance after each. The cursor is the stream version, so a deposit that lands between two pages doesn't shift the next one.GET /accounts?page=2&pageSize=25: accounts ordered by IBAN with the total. This one uses page numbers instead of a cursor, because the back office shows "page 2 of 7" and there are far fewer accounts than statement lines.GET /accounts/{id}/history: every event stored for the account, oldest first, with the same version cursor. It reads the event stream itself, not a read model, so an audit view never shows something the projection made up or hasn't reached yet.- A Blazor back office (
src/LedgerCore.Admin) that reads everything through the API: the account list a page at a time, and a page per account with its balance and the event timeline. The pages render statically on the server with paging in the query string (ADR-0017), and they have bUnit tests against a fake HTTP handler, so they run without the API. Operators sign in through OpenID Connect and the pages check arolesclaim (ledger-viewerorledger-operator), so Keycloak and Entra ID work the same way (ADR-0018). - Bearer tokens on every route under
/accountsand/transfers. Services get scopes (ledger.read,ledger.write) and people get roles (ledger-viewer,ledger-operator), and three policies accept either; only an operator can rebuild a read model. The back office forwards the operator's access token and swaps it for a new one shortly before it expires, so a five-minute token doesn't turn into 401s halfway through a page (ADR-0019). A test walks every mapped route and fails if one has no policy. - Account endpoints on a minimal API. Every error is an RFC 9457 problem with a stable
codeto branch on, for example a 409 withaccount.insufficient_fundswhen a withdrawal is more than the balance (ADR-0008). - An OpenAPI 3.1 document at
/openapi/v1.jsonthat lists every status an endpoint can answer, and a Scalar UI at/scalarin development. Idempotency-Keyon every POST: a retry gets the stored response back, the same key with another body is a 422 (ADR-0009). It is an endpoint filter, so callers that run the endpoint in-process get it too (ADR-0010).- A fixed-window rate limit per client on
/accountsand/transfers, from the built-in middleware. Over the limit is a 429 problem withcoderate_limitedand aRetry-Afterheader; the limits come fromRateLimiting:PermitLimitandRateLimiting:Window(600 a minute by default). The client is the token's subject, so two services behind one proxy get their own windows and one service spread over several addresses gets one. A request with no token is counted by its remote address, which behind a proxy needs forwarded headers. Health checks are never limited. - Transfers between accounts run as a process manager over the two account streams: debit the source, credit the destination, and give the money back if the destination refuses (ADR-0011).
POST /transfersanswers 201 with the final status, or the refusing account's problem plus atransferIdto read it back fromGET /transfers/{id}. A retry with the sameIdempotency-Keygets the first answer and moves the money once. - Telemetry from
LedgerCore.ServiceDefaults: OpenTelemetry traces, metrics and logs for ASP.NET Core, HttpClient, the runtime and every command (LedgerCore.Applicationspans), sent over OTLP whenOTEL_EXPORTER_OTLP_ENDPOINTis set./healthruns every check,/aliveonly the liveness one, and neither shows up in traces. - Ledger metrics on the
LedgerCore.Applicationmeter:ledger.transferscounts transfers that reached a final status, taggedcompleted,failedorcompensated, so its rate is transfers per second;ledger.projection.lagis the time in seconds from an event occurring to a read model applying it, tagged with the projection. A rebuild records no lag, because the events it replays are old by design. - What counts as the API contract, which changes break it, and how a v2 would sit next to v1: docs/api.md.
Coming next:
- Transactional outbox (built on outbox-kit), then Azure Service Bus.
- Outbox lag next to the other metrics once events go out.
flowchart LR
client[API client] --> api[LedgerCore.Api<br/>minimal APIs]
api --> app[LedgerCore.Application<br/>commands and queries]
app --> domain[LedgerCore.Domain<br/>aggregates, value objects, events]
app --> ports{{ports}}
infra[LedgerCore.Infrastructure] -. implements .-> ports
infra --> es[(PostgreSQL or SQL Server<br/>event store + outbox)]
infra --> rm[(SQL Server<br/>read models)]
infra --> bus[[Azure Service Bus]]
The Domain project has no dependencies at all. Application talks to the outside world only through interfaces it owns, and Infrastructure implements them. Design decisions are in docs/adr, starting with why the ledger is event sourced.
sequenceDiagram
participant C as Caller
participant D as CommandDispatcher
participant B as Behaviors<br/>tracing, logging, validation
participant H as WithdrawHandler
participant R as AccountRepository
participant S as Event store
participant P as Projection
participant Q as QueryDispatcher
C->>D: Withdraw(accountId, 40.50 EUR)
D->>B: run behaviors in order
B->>H: valid command
H->>R: load account
R->>S: snapshot + later events
H->>H: Account.Withdraw (funds check)
H->>R: save
R->>S: append at expected version
H-->>C: Result with the new balance
S-->>P: events in global order
P->>P: fold into AccountSummary
C->>Q: GetAccount(accountId)
Q-->>C: summary as of the projection's checkpoint
The write side answers from the account stream, so a withdrawal never sees a stale balance. The read side catches up after the append and can lag behind it; a query returns whatever the projection has seen so far.
stateDiagram-v2
[*] --> Requested: POST /transfers
Requested --> SourceDebited: source withdrawal accepted
Requested --> Failed: source refuses
SourceDebited --> Completed: destination deposit accepted
SourceDebited --> Compensated: destination refuses, money back on the source
SourceDebited --> SourceDebited: refund refused too, stays open for a person
Completed --> [*]
Failed --> [*]
Compensated --> [*]
Each arrow is one event on the transfer's own stream, saved before the next step starts, so after a crash TransferProcessManager picks up at the last recorded state. A refused debit is Failed because no money moved. A refused credit is Compensated because the source was paid back. If the refund is refused as well, the transfer stays SourceDebited and the error is thrown rather than hidden (ADR-0011).
dotnet build
dotnet test
docker run -d -p 8080:8080 -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
-v "$PWD/src/LedgerCore.AppHost/keycloak:/opt/keycloak/data/import:ro" \
quay.io/keycloak/keycloak:26.6 start-dev --import-realm
dotnet run --project src/LedgerCore.ApiWithout a connection string the API keeps everything in memory. The Keycloak container loads the same ledger realm the AppHost uses, and in Development the API trusts it on port 8080. Every route except /health and the OpenAPI document needs a token, so get one for the local ledger-dev client first (it acts as an operator):
curl -s http://localhost:8080/realms/ledger/protocol/openid-connect/token \
-d grant_type=client_credentials -d client_id=ledger-dev -d client_secret=ledger-devThen run the requests in LedgerCore.Api.http from VS Code (REST Client) or Visual Studio. The first one fetches the token and the rest send it. They cover each endpoint, a retried deposit, the main errors and a call with no token. Scalar at http://localhost:5174/scalar still lists every endpoint, and the OpenAPI document declares the Bearer scheme they ask for.
dotnet run --project src/LedgerCore.AppHostThe AppHost starts SQL Server, the Service Bus emulator with the ledger.events topic and its audit subscription, and the API once both are up, and opens the Aspire dashboard with their logs, traces and metrics. The API gets the same ConnectionStrings:Ledger and ConnectionStrings:ServiceBus it reads without Aspire, so nothing in it knows about the AppHost. Add --Storage:Provider PostgreSql to run the event store on PostgreSQL instead. It also starts Keycloak with a local ledger realm and the Blazor back office (src/LedgerCore.Admin), which only talks to the API. Sign in at http://localhost:5175 as viewer or operator (the password is the user name); nobody has no role and lands on the no-access page.
The dashboard shows every resource the AppHost started, and one trace per request across the back office and the API. Opening an account page is one admin span with two API calls under it, the summary and then the history:
compose.yaml has SQL Server, PostgreSQL and the Azure Service Bus emulator, with local-only passwords. Start only what you need.
docker compose up -d sqlserver
docker compose exec sqlserver /opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P 'Ledger_dev_1' -Q "create database ledger"
export ConnectionStrings__Ledger='Server=localhost,14333;Database=ledger;User Id=sa;Password=Ledger_dev_1;TrustServerCertificate=true'
export Storage__Provider=SqlServer
dotnet run --project src/LedgerCore.ApiThe API creates its tables on start. Balances and statements come from SQL Server tables that survive a restart (GET /accounts/{id}/statement).
docker compose up -d postgres
export ConnectionStrings__Ledger='Host=localhost;Port=15432;Database=ledger;Username=postgres;Password=ledger'
export Storage__Provider=PostgreSql
dotnet run --project src/LedgerCore.ApiOn PostgreSQL the read model is still in memory and replays the events on start. What differs between the two engines, and why, is in ADR-0014.
docker compose up -d servicebusIt starts SQL Server too, which it uses for its own state, and creates the topic ledger.events with one subscription, audit, from deploy/servicebus/config.json. Wait for "Emulator Service is Successfully Up" in docker compose logs servicebus. The emulator is for local development only and its image tag is latest, as Microsoft publishes it.
Needs the .NET 10 SDK, and Docker for the databases, the AppHost and the PostgreSQL and SQL Server tests (Testcontainers starts them).
MIT



