Skip to content

About

Event-sourced double-entry banking ledger for .NET 10: CQRS, outbox, Aspire, OpenTelemetry

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

LedgerCore

ci license

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.

Why

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.

Features

Done:

  • Money and Currency value objects: no mixing currencies, no amounts finer than the currency settles in, banker's rounding on multiplication.
  • Iban with per-country length and mod-97 check, and a strongly typed AccountId (time-ordered v7 Guid).
  • Account aggregate (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 Result with 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_getapplock on 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}/rebuild empties it and replays the store in the background, and a GET on the same route shows how far it has got. Off unless Admin:Enabled is 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.
  • Account endpoints on a minimal API. Every error is an RFC 9457 problem with a stable code to branch on, for example a 409 with account.insufficient_funds when a withdrawal is more than the balance (ADR-0008).
  • An OpenAPI 3.1 document at /openapi/v1.json that lists every status an endpoint can answer, and a Scalar UI at /scalar in development.
  • Idempotency-Key on 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).
  • 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 /transfers answers 201 with the final status, or the refusing account's problem plus a transferId to read it back from GET /transfers/{id}. A retry with the same Idempotency-Key gets 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.Application spans), sent over OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set. /health runs every check, /alive only the liveness one, and neither shows up in traces.
  • Ledger metrics on the LedgerCore.Application meter: ledger.transfers counts transfers that reached a final status, tagged completed, failed or compensated, so its rate is transfers per second; ledger.projection.lag is 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, and a Blazor back office.

Architecture

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]]
Loading

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.

How a command and a query flow

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
Loading

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.

How a transfer runs

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 --> [*]
Loading

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).

Quickstart

dotnet build
dotnet test
dotnet run --project src/LedgerCore.Api

Without a connection string the API keeps everything in memory. Open http://localhost:5174/scalar to open an account, post deposits and withdrawals and move money between accounts, or run the requests in LedgerCore.Api.http from VS Code (REST Client) or Visual Studio. They cover each endpoint, a retried deposit, and the main errors.

Everything with .NET Aspire

dotnet run --project src/LedgerCore.AppHost

The 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.

With Docker Compose

compose.yaml has SQL Server, PostgreSQL and the Azure Service Bus emulator, with local-only passwords. Start only what you need.

On SQL Server

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.Api

The API creates its tables on start. Balances and statements come from SQL Server tables that survive a restart (GET /accounts/{id}/statement).

On PostgreSQL

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.Api

On 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.

Service Bus emulator

docker compose up -d servicebus

It 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).

License

MIT

About

Event-sourced double-entry banking ledger for .NET 10: CQRS, outbox, Aspire, OpenTelemetry

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages