• Billing
  • Correctness
  • Offline

Invoice numbers a tax inspector can trust — even when the Wi‑Fi is down

In India, and in most VAT countries, a restaurant’s bill is a tax invoice. It needs a consecutive number in a series, and a number once issued cannot be reused or quietly removed. That rule shaped more of Fravolo’s code than any feature request: the counter, the database writes, the cancel button and the offline mode all follow from it.

Fravolo Engineering · updated · 13 min read

The rule: consecutive, unique, never deleted

A bill number looks like ABC/26-27/0042: the restaurant’s short prefix and a series letter, the financial year, and a sequence. India’s rules cap the whole thing at 16 characters and require it to be consecutive within its series; a VAT authority expects the same discipline. An inspector who sees 0041 and 0043 will ask about 0042. Two different bills both numbered 0042 is worse: it looks like a second set of books.

So we hold ourselves to two properties, in this order. A number is never reused. And a number is not skipped unless something failed after it was taken — which we design to be rare and make visible.

ONE RESTAURANT · FINANCIAL YEAR 2026-27Registration · DelhiABCP/26-27/0042Counter billsABCW/26-27/0007Website ordersABCE/26-27/0013Delivery platformsABCO1/26-27/0003Offline · device 1ABCC/26-27/0002Credit notesRegistration · HaryanaABCP/26-27/0024Counter billsABCW/26-27/0049Website ordersABCE/26-27/0001Delivery platformsABCO1/26-27/0021Offline · device 1ABCC/26-27/0014Credit noteseach line is its own atomic counter · prefix + series + year + sequence ≤ 16 characters
Each kind of bill has its own series, and each series has one counter per tax registration per financial year. A restaurant with outlets registered in two states has two sets.

Series, not one big counter

Different documents are numbered separately, because accountants and returns treat them separately:

SeriesIssued byWhy it is separate
PThe POS, when a ticket is settledThe everyday counter bill
WPaid orders from the restaurant’s own websiteDifferent channel, often reconciled against the payment provider
EOrders from delivery platformsThe platform prices and, in India, collects the tax, so these bills carry none of ours
O + deviceA counter device billing offlineEach device numbers on its own, so devices never collide
CCredit notes against counter, web and platform billsCorrections are documents too, with their own sequence
none / CN / QTBack-office tax invoices, their credit notes, quotationsOffice documents keep their own counters, apart from the counter’s

Every series has one counter document per restaurant, per tax registration number, per series and per financial year. The financial year comes from the restaurant’s market: April to March in India, the calendar year elsewhere, so a Dubai bill reads …/26/0042 and a Delhi bill …/26-27/0042. The prefix length is validated when the owner sets it, and a series that would overflow 16 characters fails before any number is spent.

Taking a number

The counter is a single document incremented atomically by the database. There is no read-then-write in application code, so twenty cashiers settling at the same instant get twenty different numbers. An integration test does exactly that — twenty concurrent goroutines — and checks the result is 0001 to 0020 with nothing missing and nothing doubled.

billing/numbers.goGo
// next atomically takes the next number in a series.
// One counter per restaurant, tax registration, series and financial year.
func (s *service) next(ctx context.Context, key string) (int64, error) {
	var doc struct{ Seq int64 `bson:"seq"` }
	err := s.db.On(ctx, "counters").FindOneAndUpdate(ctx,
		bson.M{"_id": key},
		bson.M{"$inc": bson.M{"seq": 1}},
		options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After),
	).Decode(&doc)
	return doc.Seq, err
}

Atomicity gives us uniqueness. Avoiding gaps is about ordering: the number is the last thing we take. Settling a counter ticket runs in this sequence:

  1. 1Check everything that could refuse the sale: the shift is open, the restaurant is approved to issue tax invoices, the business has a tax registration and legal name, the cashier’s discount is within their limit.
  2. 2Claim the ticket with a conditional update from open to settling, so a double tap or a second tablet cannot settle it twice.
  3. 3Re-price the stored lines on the server and compute tax. The browser never sends a total.
  4. 4Check the formatted number will fit, then take the number, then record the sale.
  5. 5If anything fails before the sale is recorded, the ticket goes back to the status it had. If the number was already taken, it stays spent.
The number is spent; a gap is better than a reused number. — a comment in the settle path

A gap can only appear if the sale cannot be stored — the insert fails, or the process dies — in the moment between taking the number and recording the sale. Unique indexes on the bill number back up the counter: even a bug elsewhere cannot write two bills with the same number in one series.

A settle that dies half-way

The claim in step 2 records when it was taken and what the ticket was before. If the request dies after that — a deploy, a crash, a lost connection — the ticket is repaired the next time anyone reads the floor. If the sale and its bill were stored, the ticket is closed on that bill and the steps that follow a settle (loyalty points, stock, the e-bill) run once. If nothing was stored and the claim is clearly stale, the ticket goes back to the cashier as it was. A settle that is still running is left alone. So a settle that got as far as storing its bill is finished on its own number rather than leaving a gap.

Retries are handled before any of this. Every write from the POS carries an idempotency key tied to the cashier’s intent — opening the settle sheet mints one, and every attempt from that sheet reuses it until a definite answer arrives. The server binds the key to the restaurant, the user, the method and the path, and marks it pending before the handler runs: a duplicate arriving while the first is still working is told so with a conflict, and one arriving afterwards gets the first answer back instead of settling again.

Web orders: claimed, then swept

A paid website order is invoiced by a claim with an expiry: the order is marked as being invoiced, the number is taken, the bill is saved. If that dies part-way, a sweeper in the one-minute job loop finds paid orders without a bill and finishes them, skipping fresh claims and recent failures. Every paid order ends up with a bill. A number taken by a request that died before saving it stays spent — the same rule as the counter — and the sweeper takes a new one. The invoicer also refuses to number an order whose recomputed total or tax disagrees with what the order recorded.

Money is an integer

Every amount in Fravolo is an int64 in minor units — paise, fils, pence, cents. Tax rates are basis points. There is no floating point anywhere money is computed, and there is one function that computes a bill’s tax. The POS, the website checkout, invoices and offline bills all go through it, or mirror it exactly.

billing/gst.go (one line’s tax)Go
// percentOf rounds half up: (amount × bp + 5000) / 10000.
func percentOf(amount, bp int64) int64 { return (amount*bp + 5000) / 10000 }

if inclusive {
	// The menu price includes tax: base = price ÷ (1 + rate), rounded.
	base := (price*10000 + (10000+rate)/2) / (10000 + rate)
	half := percentOf(base, rate/2)
	line.CGST, line.SGST = half, half
	// Any odd paisa goes to the taxable value, so the line still adds up.
	line.Taxable = price - line.CGST - line.SGST
} else {
	half := percentOf(line.Taxable, rate/2)
	line.CGST, line.SGST = half, half
}

A bill-level discount is spread over the lines by largest remainder, so the shares add up to the discount exactly. Delivery charges are never discounted. The grand total is rounded to the whole currency unit with an explicit round-off line, because that is what a printed bill shows. Outside India the same function runs with a single-tax regime: one VAT, GST or BTW line instead of the central and state split.

Corrections are documents, not deletions

There is no delete for a bill anywhere in the billing, POS or order code, and no route that would call one. Mistakes are corrected the way an accountant would:

  • Cancelling an invoice requires a reason, issues a credit note for the full amount in the current financial year, and marks the original cancelled with an entry appended to its history.
  • Voiding a counter sale is for managers and owners, needs a reason, and moves the order to cancelled. Voided in the same month, the number is reported as cancelled in the monthly return. Voided in a later month, after that return may have been filed, it gets a credit note.
  • A wrong payment is voided on the receipt, and the balance is recomputed from the receipts that remain.

Order status follows the same philosophy. Each status lists the statuses it may be reached from; an update puts the current status in the database filter, so a stale or concurrent change simply fails. The status history is append-only. Nothing moves backwards, and nothing is rewritten.

Billing with the internet down

Restaurant Wi-Fi fails at the worst moments. A counter that cannot bill is a queue at the door, so a paired counter device keeps billing without the server. The hard part is the number: the device cannot ask the server for the next one.

The answer is to give each device its own series. When a counter tablet is paired, it is assigned a device code that is never handed out again, even after the device is revoked. Its offline bills are numbered in a series that includes that code, so two tablets offline at the same time can never produce the same number.

COUNTER TABLET · OFFLINEAPI · WHEN REACHABLEPrice from the loaded menuTake a number in its own seriessaved before it is shownPrint the slipQueue in local storageSeen this client id? return itRe-price every lineKeep number & time; note mismatchesMove the counter up, never downWi-Fi downproxy says 502sync, in order
The device prices from its loaded menu, numbers in its own series, prints, and queues. When the API is reachable again, the server re-prices each bill and books it with the device’s number and time.

The console’s proxy answers 502 when the API is unreachable; a 502 or worse, no answer at all, or the browser’s own offline event flips the POS into offline mode. The device takes the next number and writes it to local storage before returning it, so a crash between printing and saving cannot hand out the same number twice. When the server sends its own view of the counter, the device keeps whichever is higher; the number never goes backwards. And the offline sheet guards its button with a ref, so a double tap cannot take two numbers.

lib/offline-bills.ts (abridged)TypeScript
/** Takes the next number in the series and remembers it's used. */
export function takeNumber(s: OfflineSeries, m: OfflineMarket, at = new Date()) {
  // Offline across the year end: the new year's series starts at 1.
  const fy = fyOf(at, m); // the market's clock and year start, as the API's
  if (fy !== s.fy) s = { ...s, fy, next: 1 };
  const seq = s.next;
  const next = { ...s, next: seq + 1 };
  write(SERIES, next); // persisted before the number is shown or printed
  return { seq, number: `${s.series}/${s.fy}/${String(seq).padStart(4, '0')}`, series: next };
}

/** The server's view of the series, merged so it never goes backwards. */
export function mergeSeries(server: OfflineSeries | null) {
  const local = read<OfflineSeries | null>(SERIES, null);
  if (!server) return local;
  if (!local || local.series !== server.series || local.fy !== server.fy) {
    write(SERIES, server);
    return server;
  }
  const merged = { ...server, next: Math.max(server.next, local.next) };
  write(SERIES, merged);
  return merged;
}

Syncing: the server re-prices, but keeps the number

Each offline bill carries a client-generated id. The sync endpoint is idempotent on it: syncing the same bill twice books it once, and if two syncs race, a unique index decides and the loser returns the winner’s result. Then the server does what it always does: it prices every line again from the current menu and computes the tax itself.

  • The bill keeps the device’s number and time. That is what the guest has in their hand.
  • If the prices disagree — the menu changed while the tablet was offline, say — the bill is booked at the menu price and a note records what was printed, what was paid and what the menu said, for a manager to review.
  • If the number has somehow been used already (a device whose storage was cleared), the bill is booked under the next free number and the note says what was printed.
  • Bills that are too old, from a month whose return may already be filed, or implausibly far ahead of the counter are refused and shown to a manager rather than booked silently.
  • Finally the counter is moved up to the highest number used, never down.

The sync itself runs as a server action, so the device’s credential travels from the console’s server to the API and never through browser JavaScript. A refusal marks the bill for a manager; a network error or a server error leaves it queued for the next attempt, in order.

Trade-offs and what we would change

  • No multi-document transactions. Taking the number and writing the bill are two writes. We chose ordering plus unique indexes over a transaction on every sale; the cost is that a failed write after the increment leaves a gap. We would like the monthly document summary to flag such a gap automatically, rather than relying on a log line.
  • Mismatches are booked, not rejected. Refusing a bill the guest has already paid for helps nobody. Booking it at the menu price with a note is the honest record, but it means the books can differ from the slip until a manager reviews it.
  • A reload during an outage loses the page. Queued bills survive in local storage, but the POS is server-rendered and our service worker does not cache pages, so the tablet must keep the tab open. Caching the POS shell for offline start is on our list.
  • Offline billing mirrors the server by hand. The offline bill follows the market’s regime (India’s CGST + SGST halves, one tax line elsewhere) and its series year (April–March in India, the calendar year elsewhere, on the restaurant’s clock) by copying the server’s rules into TypeScript. Two copies of one rule can drift; a shared test vector both sides run would catch it sooner than a mismatch note.
Code in this post is adapted from Fravolo’s codebase and simplified for reading: names are generic and error handling is trimmed. Written by Fravolo Engineering, 19 November 2026; checked against the code again on 23 November 2026.