The short version: in Ledgerline, our early-access ERP for Indian trading and retail businesses, nobody types a journal entry for normal business. Every sales invoice, receipt, credit note, goods receipt, supplier invoice, supplier payment, purchase return and stock adjustment posts its own balanced double-entry journal, tagged with the document that made it. Stock moves the same way, through a ledger that is only ever appended to. The product's tagline is also the design rule: every number, traceable to the line that made it.
Ledgerline is our own product, not a client delivery, and it is in early access. The backend runs on FastAPI, PostgreSQL and Redis Streams. The user interface is still a prototype on demo data and is not yet connected to this backend, so this article is about the backend. Near the end we list what we would build differently and the gaps that are still open.
Why a balance column is not enough
Most small-business systems start with a number that is updated in place: a customer's outstanding amount, a stock quantity, an account balance. It is fast and simple. Then a request is retried, two updates race, or someone edits last month's invoice to fix a typo, and the number drifts. The worst part is not the drift. It is that the number cannot explain itself. Nobody can say which documents made it what it is.
Double-entry bookkeeping solves half of this. The other half is engineering: entries written automatically from documents, never edited, kept out of closed months, numbered without collisions, and linked back to their source.
The architecture in one list
Ledgerline is a modular monolith: separate modules for sales, procurement, inventory, finance and reports, in one codebase. Modules do not call each other's services. When a document changes state, its module publishes a domain event, and the modules that care subscribe to it. The flow for a sales invoice looks like this:
- 1. Sales validates and commits. The invoice is created from a sales order, checked, numbered and committed in the sales module's own transaction.
- 2. Sales publishes an event.
sales.invoice_postedgoes onto a Redis stream named after the event. The tenant ID travels inside the payload, so one consumer can serve every tenant from one stream. - 3. Finance consumes it. The finance module runs its own consumer group as a separate process. Its handler for that event maps the invoice to account lines and posts one balanced journal.
- 4. Inventory consumes the stock events. Deliveries, goods receipts, returns and adjustments become rows in the stock ledger through the same pattern.
- 5. Acknowledge only on success. A message is acknowledged only after its handler has committed. If a handler fails, the message stays pending, and a live consumer reclaims it once it has been idle for 30 seconds and tries again.
We chose events because finance should not be able to block a sale, and adding a subscriber should not mean touching the sales code. The price is eventual consistency: for a moment after an invoice is committed, the ledger does not show it. For an SMB ERP that is acceptable. For a wallet that must answer "can this customer spend this money right now", it is not, and we would post in the same transaction.
The data model
Three tables carry the books:
- accounts: a code, a name, a type (asset, liability, equity, income or expense), an optional parent, three flags (contra, cost of goods, cash or bank) and a balance stored in the account's normal direction. Whether an account is a group is not stored; it is worked out on read from whether any other account names it as a parent, so it can never go stale. Posting to a group account is rejected.
- journal_entries: a gapless number, a date, a narration, a total, a status (draft or posted), a
source_type(manual, sales invoice, receipt, credit note, goods receipt, supplier invoice, supplier payment, purchase return or stock adjustment), asource_refholding the originating document's own number, and the fiscal period the entry fell into. - journal_lines: the account, a copy of the account's code and name at posting time, and a debit or a credit. A line must have one or the other, never both and never neither.
Money is stored as NUMERIC(14,2) and handled as Python Decimal from end to end; no float ever touches an amount. Contra accounts get one small rule: an account is debit-normal if its type is asset or expense, flipped if it is a contra account such as Sales Returns. The profit and loss then nets contra-revenue off revenue without any account codes hard-wired into the report logic.
Every document posts its own journal
Each event handler is a small, readable mapping from one document to account lines. These are the pairs the finance consumer posts today:
- Sales invoice: debit Accounts Receivable for the total; credit Sales (retail or trade, by the invoice's price tier) for the taxable value; credit Output GST Payable for the tax.
- Receipt: debit Cash in Hand or Bank Accounts, depending on the payment method; credit Accounts Receivable.
- Credit note: debit Sales Returns and Output GST Payable; credit Accounts Receivable.
- Goods receipt: debit Inventory and Input GST Credit; credit Goods Received Not Invoiced (GRNI).
- Supplier invoice: debit GRNI for exactly what the receipt accrued, debit Freight Inward if the order carried freight, and put any price or quantity difference on a single variance line; credit Accounts Payable.
- Supplier payment: debit Accounts Payable; credit Cash or Bank.
- Purchase return: debit Accounts Payable; credit Inventory and Input GST Credit.
- Stock adjustment: a loss debits Inventory Write-off and credits Inventory; a gain does the reverse.
Before anything is written, the posting function sums both sides. If they differ, it raises an error that says, in words, that this is a posting-logic bug. A user cannot cause an unbalanced automatic journal; only a wrong mapping can, and we want that to fail loudly in testing rather than quietly in a customer's books. The journal, its lines and the account balance updates are written in one database transaction.
Three-way match: the forty shirts
A comment in the code explains this feature as the step that "stops you paying for forty shirts when only thirty-eight arrived". Three documents are compared: the purchase order (what you ordered, at what rate), the goods receipt note (what actually arrived) and the supplier invoice (what you are being asked to pay).
The rules start at the warehouse door. Goods can only be received against an approved purchase order, never more than the quantity still open on each line, and the receipt records the damaged quantity, the delivery note number and the vehicle number. When the supplier invoice arrives, the baseline is not the order. It is the quantity received, priced at the order rate. The variance is the billed value minus that baseline. If it is zero, the invoice is marked matched. If not, it is marked as a variance.
A worked example. You order 40 shirts at ₹500 each with 5% GST. Only 38 arrive. The goods receipt debits Inventory ₹19,000 and Input GST ₹950, and credits GRNI ₹19,950. The supplier bills all 40: ₹20,000 plus ₹1,000 GST, ₹21,000 in total. The match shows a ₹1,000 variance on the goods. The journal debits GRNI ₹19,950, which clears exactly what the receipt accrued, debits ₹1,050 to the variance line (the extra goods and the extra tax), and credits Accounts Payable ₹21,000. Both sides come to ₹21,000.
Two design decisions are hidden in that example. First, the supplier invoice does not debit Input GST again. The tax was already recognised when the goods arrived; debiting it a second time would double-count it and leave GRNI with a balance that never clears. Second, the variance is flagged, not blocked. The bill can still be paid. We chose that because short shipments are often settled with a supplier credit note or a later delivery, and an ERP that refuses to record a real invoice pushes people to work outside it. The trade-off is that the control depends on someone acting on the flag. A team that wants a hard stop can add an approval step for invoices in variance status.
An append-only stock ledger
Stock follows the same rule as money. There is a current balance per item variant and location (on hand, reserved, weighted average cost and value) and a stock ledger underneath it. Every change to the on-hand quantity goes through one function that updates the balance and writes a ledger row in the same transaction. Ledger rows are never updated or deleted. Each one records the signed quantity, the unit cost, the value, the quantity after the movement, the document type, the document number and a reason. Because rows are only ever added, the quantity-after column stays a trustworthy running balance.
A few rules keep the valuation honest:
- Only a goods receipt changes the weighted average cost, because it is the only movement backed by a real purchase rate. Adjustments, returns and count differences are valued at the existing average; they never redefine it.
- A stock count never overwrites the on-hand quantity. Each counted difference becomes an adjustment posted through the ledger, which in turn posts its journal.
- Sales stock leaves only on delivery. The invoice does not move stock a second time, which avoids double-deducting an order that is both delivered and invoiced.
- Customer returns marked resellable go back on the shelf through a ledger row; damaged ones do not.
One honest trade-off: confirming a sales order reserves stock, but the reservation is bookkeeping, not a gate. Sales cannot check availability synchronously without calling the inventory module directly, which our architecture rules forbid. So a reservation informs the "available" figure but cannot block an order.
Period locks and gapless numbers
Fiscal periods are future, open or closed, and a new period is rejected if its dates overlap an existing one. Posting a manual journal, posting a draft, or posting an automatic journal into a closed period fails with a conflict. A late item has to go into an open period with its reference, rather than reopening a month that has already been reported. Periods are optional: if no period covers a date, the posting goes through unlinked, so a new tenant can start trading before setting up its calendar.
Document numbers (INV-, GRN-, JV- and the rest) come from a counter row per tenant and document type. Under GST rules an invoice series has to be sequential, so MAX + 1 or COUNT + 1 is not an option. Our first version read the counter in Python and wrote it back; a concurrency test handed two simultaneous requests the same number, and the second insert failed on the unique constraint. The fix is two single SQL statements: an INSERT ... ON CONFLICT DO NOTHING that creates the counter on first use, then UPDATE ... SET next_value = next_value + 1 ... RETURNING. The increment happens inside PostgreSQL under its row lock, and because it runs in the same transaction as the document, a document that rolls back gives its number back. The cost is that the counter row serialises document creation per tenant and document type. At SMB volumes that is invisible. At very high volumes you would split series, for example by branch.
Posted invoices are never edited
There is no endpoint that edits or deletes a posted sales invoice. A mistake is corrected with a credit note, which moves from pending approval to posted, posts its own journal and, for resellable goods, its own stock movement. The original invoice, its journal and its stock rows stay exactly as they were.
Put together, the trail runs in both directions. From a trial balance line you go to the account, to its journal lines, to the entry, whose source type and source reference name the document. From the document's number you find its stock ledger rows. Today that trail is walked through the API; the prototype interface is not wired to it yet.
What we would do differently, and what is still open
Writing these down is part of the point. These are the known gaps in the backend as it stands:
- A transactional outbox. Today a module commits its document and then publishes the event. A crash between the two would leave a document without its journal. Writing the event to an outbox table in the same transaction, and relaying it from there, closes that gap. It is the first change we would make.
- Idempotent journals. Consumers are at-least-once by design, so a handler can see the same event twice, for example if it commits and then stops before acknowledging. Journals carry their source type and reference, but nothing yet prevents a second posting for the same document. A unique key on tenant, source type and source reference would.
- Balances as a checked cache. Account balances are a running total updated in the posting transaction. With one finance consumer that is safe. Before running several, the update must become an atomic SQL increment, and a scheduled job should rebuild every balance from the journal lines and alert on any difference.
- Cost of goods at sale. No journal moves inventory to cost of goods sold when goods are sold, so the cost-of-sales line in the profit and loss only reflects purchase variances and freight. Gross margin is not meaningful yet. Fixing it means valuing each delivery at the average cost the stock ledger already holds.
- A dedicated variance account. The three-way-match variance currently lands in the cost of goods sold account. A separate purchase price variance account would be easier to review.
- Document dates on automatic journals. Automatic journals are dated when the finance consumer processes the event, not with the document's own date. Normally that is the same day. A backlog that crosses midnight at month-end would not be, so the event should carry the document date.
- Roles and approval limits. Approvals record who approved and when; role-based approval rules and amount limits are still being built, which is one reason Ledgerline is in early access. Allowing only one supplier invoice per purchase order is another current limit.
None of these changes the core rule, and each is a contained piece of work. We would rather publish them than have a reader find them.
If you are building something like this
The same rules apply to wallets, marketplace payouts, prepaid credits and billing systems: balanced entries, no edits, closed periods that stay closed, numbers that cannot collide, and a link from every figure to its source. We build these as a service; see double-entry ledger system development. If you already run a ledger and are not sure it would survive the questions above, a two-week Architecture Sprint is how we usually start: we read what exists and write down the risks and a plan. Ledgerline itself is described on the GST ERP for distributors page.