ArchitectureNo. 14
Double-entry bookkeeping for developers: a ledger that cannot lie
Accounting as a data model: entries that balance exactly, posting, reversal instead of editing, balances you derive, and the trial balance as a test, with real code from FinyX-ERP.


In this article
- A sale moves value twice, so it is written twice
- The model is two tables and a chart of accounts
- An entry balances exactly, or it is not written
- Posting turns a document into an entry, once
- Correct a mistake with a second entry, never an edit
- Never store a balance you can derive
- The trial balance is a test, and it is not enough
- The mistakes developers make, and what they cost
- The checklist for a ledger
Until October 2026, my accounting system would post a journal entry that was up to 0.01 out of balance. Closing a financial year accepted a gap of 0.0001. And an entry, once written, is never edited.
Put those three rules side by side. One entry off by 0.01, written on any day of the year, would keep that year from ever closing. No later entry could repair it, because the close checks every entry on its own. An accounting audit found the gap between the two numbers, and the fix was to make posting demand exactly what closing demands.
That is how ledger bugs behave. They rarely crash anything. They sit inside a rule until the day the books have to add up, and on that day they cannot be argued with.
FinyX-ERP is the Arabic accounting and point-of-sale system I build and sell. This article is double-entry bookkeeping as a developer meets it: a small data model with a few rules that must never bend. By the end you will have the schema for a ledger, the rules that keep it honest, the code that enforces them in FinyX, the tests that prove them, and the mistakes developers make most often in their first ledger.
In short
- A ledger is two tables, entries and their lines. Every entry's debits equal its credits exactly, and a rounding difference gets an account of its own.
- Nothing posted is edited. A mistake is corrected by a reversing entry, dated the day it is found, and both stay in the books.
- Balances are derived from the lines, never stored. The trial balance proves the arithmetic, and tests must also prove that each account ends where it should.
0.01
the gap posting used to accept
0.0001
the gap posting and closing accept today
10
accounts a manual entry may not touch
531
automated tests in FinyX today
A sale moves value twice, so it is written twice
Every business event moves value from somewhere to somewhere. A sale for cash brings money into the drawer and earns revenue. The goods leave the shelf, and their cost becomes an expense. Double-entry bookkeeping records both sides of each movement, in the same entry, at the same moment.
Debit and credit are not good and bad. They are the left and right columns of a line. Each account has a normal side. For assets and expenses, a debit increases the balance. For liabilities, equity and revenue, a credit does. FinyX numbers its chart of accounts the common way: codes starting with 1 are assets, 2 liabilities, 3 equity, 4 revenue and 5 expenses.
Here is a cash sale of 100 for goods that cost 60, written the way FinyX writes it: one entry, four lines.
| Account | Debit | Credit |
|---|---|---|
| 1110 Cash | 100.00 | |
| 4100 Sales revenue | 100.00 | |
| 5110 Cost of goods sold | 60.00 | |
| 1410 Inventory | 60.00 | |
| Total | 160.00 | 160.00 |
The two totals are the point. A single list of sales can be wrong in a hundred ways that nobody notices. In double entry, any amount that arrives on one side without its other side becomes a difference that cannot hide.
- The documenta sales invoice, saved with its lines
- Postingone journal entry, debits equal to credits
- The ledgerevery line added to its account
- The trial balanceall debits equal all credits
The model is two tables and a chart of accounts
Strip away the screens and a ledger is small. These are FinyX's three entities, trimmed to the fields that carry the accounting:
public class LedgerAccount
{
public string Code { get; set; } = string.Empty; // 1110, 4100 …
public string AccountType { get; set; } = string.Empty; // Asset, Liability, Equity, Revenue, Expense
public string NormalBalanceSide { get; set; } = string.Empty; // Debit or Credit
public int? ParentAccountId { get; set; } // header accounts only add up their children
}
public class JournalEntry
{
public DateTime EntryDate { get; set; }
public string SourceType { get; set; } = string.Empty; // "SaleInvoice", "ManualJournal" …
public int SourceId { get; set; } // the document that produced it
public int? ReversalOfJournalEntryId { get; set; } // set on a reversing entry
public decimal TotalDebit { get; set; }
public decimal TotalCredit { get; set; }
public ICollection<JournalLine> Lines { get; set; } = new List<JournalLine>();
}
public class JournalLine
{
public string AccountCode { get; set; } = string.Empty;
public decimal Debit { get; set; }
public decimal Credit { get; set; }
public string Memo { get; set; } = string.Empty;
}Four decisions hide in those few fields.
Amounts are decimal. A binary floating-point number cannot hold 0.1 exactly, and a ledger adds thousands of such values. I will give money its own article.
A line is a debit or a credit, never both, and never negative. A negative debit is a credit written on the wrong side. FinyX's manual entry screen refuses a line that carries both, and refuses a negative amount with a message that tells the accountant to move it to the other column.
Lines post to leaf accounts. A header account such as 5000, all expenses, only adds up the accounts below it. Posting to it directly would create a balance that belongs to none of its children.
An entry knows where it came from. SourceType and SourceId name the document. That link is what lets a report open the invoice behind a number, and it is what makes posting safe to repeat, as you will see below.
An entry balances exactly, or it is not written
Almost every entry FinyX writes passes through one private method, AddEntryAsync. This is its gate, trimmed:
// A negative amount is a mistake at its source, not a line to drop.
if (allLines.Any(line => line.Debit < 0m || line.Credit < 0m))
{
throw new InvalidOperationException($"قيدٌ بمبلغٍ سالب لا يُقيَّد: {referenceNumber}");
}
var normalizedLines = allLines.Where(line => line.Debit > 0 || line.Credit > 0).ToList();
var totalDebit = normalizedLines.Sum(line => line.Debit);
var totalCredit = normalizedLines.Sum(line => line.Credit);
// Exact, not approximate: the period close demands the same 0.0001.
if (Math.Abs(totalDebit - totalCredit) > BalanceTolerance)
{
throw new InvalidOperationException(
$"القيد غير متوازن: {referenceNumber} (مدين {totalDebit:0.####}، دائن {totalCredit:0.####}).");
}The messages are Arabic because the product is. The first says an entry with a negative amount is not posted. The second says the entry is unbalanced and prints both totals, so whoever reads it can see the gap without opening a database.
The first check is as new as the second. Before it, the filter on the second line simply dropped negative lines. An entry could lose a movement and still balance, or an expense typed with a minus sign could be saved with no entry at all. A silent filter on money is a bug that hides its own evidence.
The tolerance is a constant, BalanceTolerance, set to 0.0001, the same number the year-end close uses. That is the fix from the opening. Posting can no longer accept what closing will later refuse.
What about real rounding? An invoice in Saudi riyals posted to books kept in another currency has a total and its parts, each converted and rounded on its own, and they can disagree by a fraction. FinyX does not hide that fraction inside the revenue line, and it does not relax the check. It posts the difference on a line of its own, to a currency rounding account, 4190 for gains or 5190 for losses, when the chart has one. The entry balances to the last digit, and the difference has a name.
Tip
Never make the balance check approximate to absorb rounding. Rounding is not a reason for an unbalanced entry. It is a line, on an account built for it.
Posting turns a document into an entry, once
A document and its entry are different things. An invoice can exist, be printed and be paid before it reaches the ledger. Posting is the step that writes its entry. In FinyX it is a deliberate accounting decision, usually a button at the end of the day, and the invoice, its stock movements and its entry are saved in one database transaction.
Posting must be safe to repeat. A screen can be clicked twice, a background repair can run on start-up, and two tills can post at once. FinyX answers that twice. Before it builds a sale's entry, the service returns early if an entry for that invoice already exists. Under that check, the database holds the rule that cannot be raced:
builder.HasIndex(entry => new { entry.SourceType, entry.SourceId }).IsUnique();One document, one entry. A second posting fails on the index even if two requests pass the first check together.
Once posted, an entry is history. The application's save gate refuses edits and deletes of journal entries and lines, and on SQLite a trigger refuses them as well, so a database tool cannot quietly do what the app will not:
CREATE TRIGGER IF NOT EXISTS TRG_JournalLines_AppendOnly_Update
BEFORE UPDATE ON JournalLines
BEGIN
SELECT RAISE(ABORT, 'Posted journal lines are append-only');
END;I wrote about that save gate, and about the audit trail that notices edits made behind its back, in 372 tests passed. No sale could reach the ledger. Here the point is narrower. If entries cannot change, a mistake needs another way out.
Correct a mistake with a second entry, never an edit
An accountant who posts 150 to the wrong account does not erase it. They post a reversing entry: the same lines with the sides swapped, so the two cancel, and then the correct entry. Every number that was ever reported can still be explained.
This is FinyX's reversal of a manual journal entry, trimmed:
// A reversal is never reversed itself: post a new, correct entry instead.
if (original.ReversalOfJournalEntryId.HasValue)
{
throw new InvalidOperationException("هذا قيدٌ عكسي؛ لا يُعكس العكس — سجّل قيداً جديداً بالصحيح.");
}
// Dated today, not on the original's date: that period may be closed and its numbers handed over.
var today = DateTime.Today;
await FinancialPeriodGuard.EnsureOpenAsync(unitOfWork, today);
var lines = original.Lines.Select(line => new JournalLine
{
AccountCode = line.AccountCode,
AccountName = line.AccountName,
Debit = line.Credit, // the sides swap
Credit = line.Debit,
Memo = $"عكس: {line.Memo}",
}).ToList();
await _journalService.RecordManualEntryAsync(
unitOfWork, SourceType, number, today, reference,
$"عكس {original.ReferenceNumber}: {normalizedReason}", lines,
reversalOfJournalEntryId: original.Id,
reversalReason: normalizedReason,
reversedBy: _authorizationContext.CurrentUserKey);The rules around it matter as much as the swap. A reason is required, and it stays with the entry. An entry can be reversed once; a second attempt is refused with a message that names the entry. A reversal cannot itself be reversed, because that is how a ledger fills with entries that undo undos. And the reversal is dated today, inside an open period, because the original's month may already be closed and its numbers handed to someone who signed them.
The test does what an accountant would. It posts 150 against the bank, reverses it with the reason "recorded in the wrong quarter", checks that both accounts are back to zero, then tries to reverse the entry again and to reverse the reversal, and expects both refusals. The list of manual entries then shows the original as reversed by its reversal.
Documents follow the same principle. A posted invoice is corrected with a new document, a return, rather than by rewriting the sale.
Never store a balance you can derive
The most tempting column in any ledger is Balance. FinyX's customers and suppliers still carry one, and the comment above the function that replaced it says what it is now: a cached figure that the reporting paths ignore.
The reason is in the same comment. The customer screen once computed a customer's opening balance on its own, while the credit limit and the printed statement left it out. A customer who came into the system owing 50,000, with a credit limit of 10,000, could keep buying on credit as if he owed nothing, and his printed statement disagreed with his screen. Three places, three copies of one rule.
Now there is one calculation, PartyBalanceLedger, and the screen, the credit limit, the statement and the receipt voucher all read it. A voucher printed at the counter and a statement printed from reports cannot disagree about what a customer owes.
That function adds one deliberate subtlety. A customer's balance counts invoices that are not posted yet, because goods that left the shop this morning are owed this morning, and the credit limit has to see them. So the customer balance can run ahead of the ledger by exactly what has not been posted. The screen shows that difference openly, so nobody takes it for an error.
The same idea protects control accounts. Account 1210, customer receivables, is one number in the ledger. Behind it sits a subsidiary ledger, a statement for every customer, and the sum of the statements must equal 1210. A manual entry straight to 1210 would change the account and no statement. So FinyX refuses manual entries on ten such accounts, and each refusal names the screen that moves both sides together:
// Accounts whose balance is the sum of documents in a subsidiary ledger.
private static readonly IReadOnlyDictionary<string, string> SubLedgerAccounts = new Dictionary<string, string>
{
["1110"] = "النقدية تتحرك بسندات القبض والصرف وتحويلات الصناديق، فتدخل دفتر الدرج.",
["1210"] = "رصيد العميل يتحرك بعمليات «له/عليه» من شاشة العملاء، فيظهر في كشفه.",
["1410"] = "قيمة المخزون تتحرك بالأصناف: الشراء والبيع والجرد وتعديل التكلفة.",
["2110"] = "رصيد المورد يتحرك بعمليات «له/عليه» من شاشة الموردين، فيظهر في كشفه.",
// … cash in transit, cheques received and bounced, employee advances, cheques issued, the income summary
};Cash moves through receipt and payment vouchers. A customer's balance moves from the customers screen, so it appears on his statement. Inventory moves only with goods: purchases, sales, counts and cost changes. An audit test ties it together: after a cash sale, a credit sale and a cheque, the receivables in the summary must equal account 1210, to the halala.
The trial balance is a test, and it is not enough
A trial balance lists every account with its total debits and credits. If posting is right, the two columns are equal. FinyX builds it from the posted lines every time, never from stored figures, and its test treats the page as a check on all posting:
// A shift opens on 1,000 and closes on 900: a shortage of 100 is posted.
var shift = shifts.OpenCashShiftAsync(1_000m, "وردية العجز", main.Id).GetAwaiter().GetResult();
shifts.CloseCashShiftAsync(shift.Id, 900m, "نقص عند العدّ").GetAwaiter().GetResult();
var rows = accounting.GetTrialBalanceAsync().GetAwaiter().GetResult();
// It balances: a check on posting as a whole, not on this page.
var debit = rows.Sum(row => row.Debit);
var credit = rows.Sum(row => row.Credit);
Require(debit == credit, $"The trial balance does not balance: debit {debit} against credit {credit}.");
// The shortage is its own account, an expense, of exactly 100.
var shortage = rows.SingleOrDefault(row => row.Code == "5220");
Require(shortage!.Balance == 100m, $"The shortage reads {shortage.Balance} instead of 100.");Now the uncomfortable part. A ledger can balance perfectly and still be wrong, because double entry checks that each movement has two sides, not that they are the right two. The October audit found two good examples.
The first float of a new cash drawer was posted as a cash overage, which is revenue. Dr cash, Cr revenue: balanced, and wrong. The day's profit rose by the whole float, though the owner had only moved his own money into a drawer. It is now an opening balance, Dr cash, Cr opening balances, and a test checks that opening a drawer produces no revenue.
The second was a purchase discount that never reached the cost of the goods. The ledger balanced. But sell every unit you bought, and the inventory account should be empty, and it was not. The test now says so in plain numbers:
// 100 units bought at 10, with a discount of 100 on the invoice.
Require(cost == 9m, $"After 100 @10 with a discount of 100 the unit cost is {cost}; IAS 2.11 makes it 9.");
var sale = CashSale(fixture, warehouseId, (productId, 100m, 12m));
Post(fixture, sale.Id);
var inventory = Balance(fixture, "1410");
Require(inventory == 0m, $"Selling every unit bought left the inventory account at {inventory}; it must be 0.");That is the test worth copying: an account that must end at zero, checked at zero. A balanced trial balance says the arithmetic holds. Tests like this say the accounts mean what their names say.
- Each entry balancesrefused at posting, and again at the close
- Each line hits an account that existschecked before a period closes
- All debits equal all creditsthe trial balance
- Control accounts equal their subledgers1210 equals the customer statements
- Each account ends where it mustinventory at zero once everything is sold
FinyX also runs a full business day through its own services on a copy of a real database: cash and credit sales, a return, a discounted purchase, an expense, a manual entry and its reversal, a shift close, then the period close. It checks the ledger before the day, after it and after the close.
The mistakes developers make, and what they cost
| Mistake | What it costs | Instead |
|---|---|---|
A Balance column updated by each screen |
Two numbers for one debt | Derive it from the lines, in one function |
| Editing or deleting a posted entry | History changes under figures already signed | A reversal, dated the day it is found |
| "Close enough" balance checks | An entry that blocks its year's close | Exact balance; rounding on its own account |
| Dropping negative or empty lines silently | A balanced entry with a movement missing | Refuse it, and say why |
| Manual entries on control accounts | The account and its statements disagree | Move both from the document's own screen |
| Testing only that the books balance | Wrong accounts that still balance | Test where each account must end |
Money in double or float |
Totals off by fractions | decimal in code, numeric in PostgreSQL |
The checklist for a ledger
- Model accounts with a type and a normal side, and entries with lines that point at leaf accounts.
- Make each line a positive debit or a positive credit, never both.
- Require two lines at least, and an exact balance. Give posting and closing the same tolerance.
- Post rounding differences to an account made for them.
- Link every entry to its source document, and let a unique index allow only one.
- Make posted entries append-only in the code and in the database.
- Correct with reversals: dated today, with a reason, once, and never reversed themselves.
- Derive balances from lines in one function that every screen, limit and printout reads.
- Move control accounts only through the documents that also move their subledger.
- Test the trial balance, and test the end state of the accounts that matter.
A ledger does not need to be clever. It needs a few rules that never bend, written where every write has to pass, and tests that would notice the day one did.
It is the same discipline behind FinyX-ERP and the business systems I build for clients.
Share







