Iden Tumuhirwe
All writing

November 15, 2026 · 11 min read

Designing a back-office app, part 2: something else already owns the money

Software Design · Architecture · Kotlin · PostgreSQL · Integration

Part 1 was about the frontend of a business system: rules in one place, a registry that generates the app, a fake API that doubles as the spec. This part is about the backend, and it starts with the thing that reshaped my thinking about these systems more than anything else.

Find out what already calculates money

Almost every organisation that needs a new operational system already has something that bills. An accounting package, a billing engine, an ERP module, a spreadsheet that Finance guards. It is almost always right about more than you expect, because it has been reconciled against a bank for years.

If your new system also calculates invoices, you now have two sources of truth for money. The tax authority will accept the invoice from the system it's integrated with. Finance will reconcile against the ledger the payments post into. Yours loses every argument, and the disagreements will be subtle and found months later.

So the first design question for the backend is not "what's the data model". It's "which system is right when two disagree", asked for every category of data. I write the answer down as a table near the top of the design:

  • The new system owns customers, identity verification, agreements, locations, subscriptions, and the order that says "start billing this from this date".
  • The billing engine owns rated charges, invoices, receivables and dunning.
  • The existing ticketing system owns tickets.
  • The monitoring platform owns resources and alarms.

The new system keeps references to things in other systems. It keeps a copy only when it must show the data to users or apply a rule to it, and that copy is labelled a mirror with an "as of" time. It never keeps a copy that could compete with the source. Corrections arrive as new records from the source, never as edits to the mirror.

This is obvious. It is also the rule most such systems break within a year, usually because someone needs a report and adding a column is easier than asking the other system. The table at the top of the document is there to make breaking it a visible decision rather than a quiet one.

Once the billing engine owns the money, the new system's billing module stops being an engine and becomes an orchestrator and a mirror. It sends orders and usage out. It reads invoices and open balances back. It shows them to customers. That removes a great deal of code, and I've learned to be relieved rather than defensive when that happens.

The rule nobody can override

Every business system has one rule the owners care about more than any other. In the ones I've worked on it's usually some version of: if a customer owes money, they get nothing new. Not a bigger plan, not a new location, not a move. And no member of staff can override it, including administrators.

That rule has to survive four facts:

  1. The due date comes from another system.
  2. That system may be unreachable when someone clicks the button.
  3. The rule applies identically to actions from staff, the self-service portal, a bulk import, a scheduled job and an integration callback.
  4. The UI hiding a button is a convenience, not a control.

So it's a domain policy object in the backend, called from the application layer, with no UI involvement.

class NewWorkPolicy(private val receivables: ReceivablesMirror) {
    fun check(customer: CustomerId, what: String) {
        val open = receivables.openItems(customer)
        if (open.overdue.isNotEmpty()) throw Refused("$what can start once the account shows paid.")
    }
}

It reads the receivables mirror. If the mirror is stale because the upstream system is down, it uses the last snapshot and the UI shows the snapshot's age. A customer who paid in the last hour might be blocked slightly longer than they should be. That's the correct direction to fail. Letting a non-payer through because an integration hiccupped is the wrong one, and the owners agreed before I wrote a line.

I keep this as the first worked example in any design document, because it's the shape of every other rule: one place, every entry point, fails safe.

A monolith with walls

The standard answer for "it has to scale" is microservices. For a business system with a connected domain I think that's usually the wrong answer, and I've stopped being shy about saying so.

A single onboarding touches customers, identity verification, locations, catalogue, agreements and billing in one operation. Spread across services that's a distributed transaction, with every failure mode that implies and no gain in throughput. Throughput in these systems comes from stateless replication and the data tier, not from the number of deployables. And a small number of components is far easier for the owning organisation to run after you've gone, which is a requirement whether or not anyone writes it down.

So: one codebase, strict module boundaries enforced in CI, a few runtime roles.

customers/
  api/            REST controllers, DTOs
  application/    use cases, transactions, authorisation
  domain/         entities, state machines, rules like NewWorkPolicy
  infrastructure/ repositories, outbound adapters
  events/         published event types, the module's public contract

Other modules may call a module's api facade or subscribe to its events. Nothing else. Each module writes to its own database schema. No cycles. A test fails the build if any of this is violated. Spring Modulith does this for the Kotlin and Spring stack. The equivalent exists for most ecosystems, and if it doesn't, an architecture test over package imports gets you most of the way.

Scale comes from running the same binary in roles: API instances, worker instances for scheduled jobs and ingest, an integration role hosting the adapters. All stateless. Add instances to add capacity. If one module later needs its own release cadence or scaling profile, its package and schema move out and its API and events don't change. You get the option of services without paying for them on day one.

Two smaller choices that follow from the same thinking. Type-safe generated SQL instead of an ORM, because at scale I want to see the queries, use partitions and row-level security directly, and never discover an N+1 in production. And money as integer minor units with a currency code, never floating point, because every system I've seen that used decimals for money has a reconciliation story that ends in a spreadsheet.

Every external system is a plug-in

Business systems accumulate integrations. The billing engine, a ticketing tool, directory services, a mail server, an SMS gateway, a tax authority, a company registry, a payment gateway, bank statement files, a data warehouse, a security log. Twenty is normal. The core cannot know about any of them individually or it will never stop changing.

Each module defines a port in its own vocabulary. A plug-in implements that port against one vendor.

interface BillingEngine {
    fun ensureCustomer(c: CustomerSnapshot): ExternalRef
    fun ensureAccount(c: ExternalRef, currency: Currency): ExternalRef
    fun subscribe(s: ExternalRef, o: OfferingRef, qty: Capacity, from: LocalDate): ExternalRef
    fun invoicesSince(cursor: Cursor): Page<InvoiceRecord>
    fun openItems(account: ExternalRef): List<OpenItem>
}

interface Plugin {
    val id: String
    val contractVersion: String
    fun health(): HealthStatus
    fun capabilities(): Set<Capability>
}

The second interface is the one people skip. Every plug-in reports its health, the version of the far-end contract it was tested against, and what it can currently do. The framework around it supplies configuration with an audit trail, credentials from a vault, a timeout, retries with backoff, a circuit breaker, a dead-letter queue with a replay action, metrics, and contract tests against a stub.

The capability set is what makes the system survive its dependencies. If a plug-in is switched off or unhealthy, the core doesn't break. It consults the capability and uses a fallback. For outbound provisioning the fallback I've found most useful is "manual mode": the call becomes a pre-filled work item for a person, and a nightly reconciliation checks that the work got done. This matters because the vendor API you're counting on is frequently not yet available, not in the agreed interface list, or waiting on a change request measured in months. The system has to work on day one without it.

Pinning the contract version matters for a duller reason. Vendor releases change. The quoted version goes out of support. When the far end moves, exactly one adapter changes and its contract tests tell you what broke. The core never finds out.

Automations that cannot send twice

A business system runs a lot of scheduled jobs. Payment reminders on set days around the due date. Escalation of old debt. Nags about missing documents, unsigned agreements, pending acceptances. Warnings before an agreement expires. Scheduled reports. Each one must do its thing exactly once across several worker instances, when a worker can crash mid-run and a queue can deliver a message twice.

The design is unglamorous and I'm fond of it. A scheduler takes a lock in the database so one instance owns the run. It selects due items in keyset batches and publishes one message per item to a partitioned topic, keyed by customer. Workers consume in parallel. Before each action a worker re-reads current state, because the customer may have paid since the batch was selected. Then it inserts a row with a natural key under a unique constraint:

reminder:{invoiceId}:{rule}

If the insert fails, someone already sent it. Retry, redelivery, a second scheduler by accident, none of it can produce a second email. The early in-memory version of this is a .some() over an array. Same idea, worse performance, and the point is that the idea was there from the start.

There's a second-order problem when two systems both talk to customers. If the billing engine sends a formal overdue notice every ninety days and your system sends softer reminders in between, both can fire in the same week and the customer gets contradictory messages from one organisation. So the reminder job reads the other system's notice calendar and stays quiet within a few days of it, and your schedule simply doesn't have a step where theirs already does. That's a configuration entry with a comment explaining why the list stops at sixty days.

Tenancy, twice

Any system with a customer-facing part has a tenancy problem, and the prototype version of it is always wrong in the same way: the client sends a customer id and the server believes it.

The real design has two layers. The customer-facing frontend talks to a backend-for-frontend that holds the session. No tokens in the browser, only an httpOnly cookie. The session carries the tenant. Every query the customer API makes runs under a database role with row-level security keyed on that tenant, so if a bug in the application layer forgets a filter, the database returns nothing it shouldn't.

Two layers, because one layer is one bug away from a customer seeing another customer's invoices. I've never regretted the cost of the second one.

What carries over from the prototype

Almost everything above the data layer. The module list maps one to one onto backend modules. Permission names are the same strings. The stage machine is the same filter over the same list. The theme and components become a shared package. The query layer stays, with server-pushed invalidations replacing the blunt "refresh everything" from part 1.

The in-memory API becomes, approximately, the OpenAPI document. I'd generate the client from the real spec rather than keep handwritten functions, but the function names and the error messages are the brief for what the spec should say.

What gets thrown out is everything that calculated money. It moves to "the engine does this; we read it".

The questions I keep

A design document's most useful pages are the risks table and the open questions. Mine always include some version of these:

  • An integration designed against an interface I've invented, because the real product isn't confirmed. The anti-corruption layer should absorb the difference. "Should" is doing work in that sentence.
  • A payment term in my rules that might not match the configuration of the system that owns due dates. The design says read due dates only from the source, which is right, and means my reminder schedule is wrong until someone checks.
  • An upstream dependency with a lower availability target than mine. My system keeps working from mirrors with their "as of" stamps and queues outbound changes for replay. That's the best available answer for a dependency you don't control, and it's never a comfortable one.

If I had to compress both posts into one sentence: before you design anything that calculates money, find out what already does, and design your system to stand in front of it rather than replace it.