Refactoring FinLedger's Entire Lending Subsystem: What I Broke and How I Fixed It

When you build a personal finance app, you start with the features you think will be hardest:

  • Room database encryption with SQLCipher.
  • On-device machine learning classifiers.
  • Multi-threaded SMS regex pipelines.

You assume that tracking loans to friends will be the easiest feature in the entire project. After all, it's just basic arithmetic: $\text{lent} - \text{repaid} = \text{balance}$.

I could not have been more wrong.

Over the development journey of FinLedger—from early v1.0 prototypes to our comprehensive v2.1 architectural audit (docs/audit/FINLEDGER_FEATURE_AUDIT_MASTER.md)—the Lending and Borrowing Subsystem underwent more complete rewrites and structural refactorings than almost any other module in the codebase.

Here are the three major architectural mistakes I made, how each one corrupted data, and the lessons learned from refactoring personal debt tracking into a hardened, lifecycle-driven system.

Mistake 1: Mutating the Original Principal on Repayment

In our v1.0 schema, a loan record looked like this:

// The Flawed v1.0 Model data class LegacyLoan( val id: String, val personName: String, var remainingBalance: Double, // Mutated directly on every payment! val date: Long ) 

Whenever a friend paid back Rs. 500 on a Rs. 2,000 loan, the code simply subtracted 500 from remainingBalance:

flowchart TD subgraph MutatingMistake["The Destructive In-Place Mutation"] Lend["Lend Rs. 2,000 on Jan 1"] --> Mutate["Repay Rs. 500 on Jan 15: remainingBalance = 1,500.00"] Mutate --> DataLoss["Irreversible Data Loss: 1. Original agreement of Rs. 2,000 is permanently erased! 2. Payment date of Jan 15 is not recorded anywhere. 3. Looks like you lent Rs. 1,500 from the very beginning."] end

By mutating the row in place:

  1. We destroyed the original legal agreement. There was no way to prove whether the loan started at Rs. 2,000 or Rs. 1,500.
  2. Partial repayments had no timestamps, no payment channels, and no audit trail.
  3. If an edit mistake occurred, there was no history from which to calculate a rollback.

The Fix: Immutable Principal + Repayment Stream

In the refactored architecture (LendingEntity and LendingRepaymentEntity), the loan's principal is strictly immutable.

Repayments are modeled as an append-only stream of independent events. The current balance is never an editable number in SQLite; it is a dynamically derived computation:
$$\text{Outstanding} = \text{Original Principal} - \sum \text{Repayments}$$

This preserves the complete chronological history of every rupee that moved.

Mistake 2: Contacts as Unindexed Strings

In early releases, contacts were simply a text field: person_name TEXT.

We quickly ran into chaos:

  • Typos and case variations created duplicate person cards ("Rahul", "rahul", "Rahul Patil").
  • When the Split Expenses Engine was built, it used its own contact strings, making it impossible to see a combined balance sheet for a friend.
  • If a user wanted to correct a typo in a friend's name, they had to manually locate and edit 15 historical transactions one by one!

The Fix: The Unified Persons Directory (Room Migration 19)

We decoupled human identity from transaction records by creating a centralized persons table.

Every contact is assigned an immutable UUID. Lending records, repayments, and split expense shares reference this person_id foreign key. Updating a contact's display name or phone number is a single-row update that instantly cascades across the entire app.

Mistake 3: Conflating Settlement with Deletion

When a loan was paid off in early builds, the UI offered only one obvious action: Delete.

Users naturally tapped Delete to clear settled debts from their screen. But deleting the entity triggered cascading deletions that broke bank reconciliation statements and destroyed proof of past repayments.

The Fix: Active vs Past Lifecycle States

We realized that a balance reaching zero is a state transition, not a deletion event.

We introduced the isFullySettled domain flag:

  • When a loan is paid in full, it transitions automatically to Past Records.
  • The main active feed stays clean and clutter-free.
  • The permanent historical record remains accessible in an immutable archive.

How 1,500 Unit Tests Saved the Refactor

Undertaking a massive architectural refactoring of this scale—replacing database tables, creating foreign keys, and overhauling domain calculations—would have been terrifying without a safety net.

What gave me the confidence to rewrite the lending engine was our comprehensive automated test suite in LendingPersonLifecycleTest.kt.

The test suite systematically asserts against 23 distinct real-world edge cases (from zero-amount repayments to multi-loan aggregation). Whenever a refactored query or ViewModel broke an accounting invariant, the test runner caught it in milliseconds before any code touched production.

Key Takeaway

Simplicity is not the absence of structure; it is the result of getting the domain boundaries right.

Tracking loans to friends is not simple arithmetic. It is a multi-legged financial relationship requiring immutable agreements, append-only repayment streams, relational contact identities, and formal lifecycle states. Investing the time to refactor these foundations turned FinLedger's debt tracker from a source of bugs into one of the most reliable features in the app.

FinLedger is a privacy-first, offline-first personal finance application for Android that models bank accounts, credit cards, and cash without double-counting.

Explore FinLedger on Google Play: https://play.google.com/store/apps/details?id=com.devanshufinance.app