• Reliability
  • Testing
  • Go

Auditing our own codebase before launch: what we found and what we changed

Fravolo was built quickly by a small team, and it worked: a real restaurant has run on it every day since October. But “it works in our kitchen” is not the same as “it is right”. Before a wider launch we stopped adding features and read every package against the rules the system claims to keep — one restaurant never sees another’s data, a bill number is never reused, a double tap never charges twice. This is what we found, grouped by the kind of mistake, and what we changed.

Fravolo Engineering · 10 min read

How we audited

We did not start from a checklist of vulnerabilities. We started from the invariants written at the top of our own design docs and asked, for every module: what would have to go wrong for this to be false? Then we looked for the code path where it could. That framing finds a different class of bug from a scanner — not “this function is unsafe” but “this retry, at this moment, breaks a promise we make to a restaurant”.

INVARIANTWHERE IT COULD BREAKWHAT WE CHANGEDA double tap never charges twiceretry minted a new keyone key per intent + pending markerA bill is always finishedprocess died mid-settleresumable settle + invoice sweeperOne bad job never stops the APIpanic in a goroutinerecover + deadline per jobOne restaurant, one scopejoins inside pipelinesstages refused + CI raw check
Each invariant was traced to the code that has to keep it. Most findings were not in the happy path but in retries, restarts and races.

Every fix landed with a test where one was possible, and the end-to-end suite — which walks a restaurant from sign-up to its end-of-day report through the real API — was run on the release branch before anything merged.

1. Retries that were not really idempotent

The API has idempotency middleware: a write carrying an idempotency key returns the stored answer if the same key arrives again. On paper, double taps and network retries were handled. In practice we found two gaps.

  • The POS made a fresh key for every call. A retry after a lost response arrived with a new key, so the middleware had nothing to match. A key that changes on retry protects nothing.
  • Two identical requests arriving together both missed the cache. The first had not finished, so there was no stored answer yet, and both ran.

The server now writes a pending marker for a key before running the handler, using an atomic set-if-absent. A duplicate that arrives while the first is still running is told so with a conflict, instead of running again. Keys are bound to the restaurant, the user, the method and the path, so a key can never replay someone else’s answer.

On the client, keys now belong to an intent, not to a call. Opening the settle sheet creates one intent; every attempt to settle from that sheet reuses its key until a final answer arrives. A network error or a server error keeps the key for the retry; a definite answer retires it.

lib/pos.ts (abridged)TypeScript
// Writes whose answer never came, by signature → the key they used.
const unanswered = new Map<string, string>();

export async function posApi<T>(path: string, init: WriteInit = {}): Promise<T> {
  const sig = `${init.method} ${path} ${JSON.stringify(init.body)}`;
  // The settle sheet passes an Intent: one key across tries, even if
  // the cashier retypes the cash between them.
  const key = init.intent?.key ?? unanswered.get(sig) ?? uuid();
  if (!init.intent) unanswered.set(sig, key);

  const res = await send(path, init, key);
  if (res.status < 500) {
    unanswered.delete(sig); // a definite answer retires the key
    init.intent?.renew();
  }                         // network error or 5xx: the retry reuses it
  return read<T>(res);
}

Two smaller relatives of the same bug: a busy flag read from a stale React closure let a fast second tap through (it is now a ref that is checked and set synchronously), and an older poll landing after a write could put the old state back on screen. Every read is now stamped, and a newer read or any write makes older answers stale.

2. Work that could die half-way

Settling a counter bill is a sequence: claim the ticket, take a bill number, record the sale, mark the ticket settled. If the process died between those steps, the ticket stayed in its intermediate state, and the cashier saw a ticket that could neither be settled nor reopened.

Settle is now resumable. When the floor is next read, a ticket stuck in its settling state is repaired: if the sale and its bill were stored, the ticket is closed on that bill and the steps that follow a settle (points, stock, the e-bill) run once; if no bill was stored, then once the claim is clearly stale the ticket goes back to the cashier as it was. A settle that is still running is left alone. Online orders got the same treatment: issuing a bill for a paid web order is a claim with an expiry, and a sweeper in the job loop finishes any whose claim lapsed, so a crash between payment and invoice no longer leaves a paid order without a bill.

Customer counters (visits, lifetime spend) and loyalty points had a related problem: a retried write could count the same order twice. Both are now keyed by the order, with a unique index under the loyalty ledger, so applying an order twice is a no-op instead of a double credit.

3. Background work that could take the process down

In Go, a panic in any goroutine ends the whole process. We had fire-and-forget goroutines for pushes, e-bills and emails, and a job loop that ran its sweeps one after another. One bad record in one sweep could have stopped the API, and one slow sweep held up all the others.

safego/safego.goGo
// Go runs fn on a new goroutine; a panic is logged with its stack
// and reported, instead of taking the API down.
func Go(name string, fn func()) {
	go func() {
		defer Recover(name)
		fn()
	}()
}

Background goroutines — jobs, WhatsApp sessions, e-bill sends, order dispatch, placement moves — now start through that helper, and a panic costs one run of one task, not the API. Each job in the minute loop runs on its own goroutine under its own deadline, and is skipped — with a warning — if its previous run has not finished, so a hung job cannot pile up copies of itself. Requests got deadlines too — with longer, named budgets for the few slow ones such as AI readers and imports, and none for the live event stream — and the database client bounds any operation that arrives without a deadline of its own, so a slow query fails loudly instead of holding a connection forever.

4. Tightening tenant isolation

Our data layer scopes every query to one restaurant, as we described in the multi-tenancy post. The audit asked where that wrapper could be stepped around, and closed three paths:

  • Aggregation stages that read or write other collections — joins, unions, graph lookups and output stages — are now refused inside scoped pipelines. A scoped pipeline reads one restaurant’s documents in one collection, and nothing else.
  • Pipeline-style updates may not touch the restaurant field at all.
  • The raw escape hatch can no longer spread quietly. A CI script fails the build if any non-test Go file outside a one-file, reviewed allow-list reaches for the raw collection.

Inside a restaurant, staff limited to some outlets could previously fetch another outlet’s record if they knew its id. By-id routes now answer “not found” for outlets outside the member’s scope, and writes are pinned to the outlet they belong to.

And the isolation suite — two real restaurants, real HTTP, a real database — now runs in CI on every push, against a database service started for the job. It had been running only before releases. Getting it green again meant fixing several stale fixtures that had drifted from the code, which is exactly why suites that only run occasionally are worth less than they look.

5. Contracts between the two halves

Our favourite finding was the smallest. During the rebrand, the API was changed to expect a renamed request header for offline bill sync; the console still sent the old one. Every offline bill would have been refused at sync time — and nothing in the type system or either half’s unit tests could see it, because the contract lived in two string literals in two languages.

The fix was one line. The lesson was the test: the offline sync test now sends exactly what the console sends. When two halves of a system agree on a string, at least one test should exercise both halves at once.

Similar small contracts turned up elsewhere: counter bills outside India stored their VAT in the bill but not on the order record that reports read, so a migration backfilled it and the settle path now records the whole tax. A new expense defaulted to the UTC date, which in India is still yesterday until half past five in the morning, and reservations were checked against a fixed clock; both now use the restaurant’s own time zone.

6. Defaults that should have been opt-in

  • Marketing consent. A new customer used to start opted in to marketing. Consent has to be given, not assumed: customers now start opted out, the new-customer form’s box starts unticked, and a guest’s “yes” on WhatsApp records when consent was given.
  • The public demo. Our demo restaurants have a published sign-in so prospects can try the product. That login could send real messages and change real settings. Demo restaurants are now read-only for anything that leaves the building or changes set-up.
  • Automatic approval. New restaurants are approved automatically only when the official registries confirm their registration and their papers agree. Anything less waits for a person.
  • Paid calls. Registry checks, document reading and AI features cost money per call. Each now has a per-restaurant daily budget, counted before the call is made, not after.

7. The edges

The rest was hygiene, and none of it is glamorous: request-body caps and server timeouts at the edge (with the streaming routes left open, because a server-sent event stream is supposed to last), access logs that drop query strings and bill-link tokens, a per-request content-security-policy nonce on every signed-in page, push notifications sent only to the known push services, a redirect parameter now decided with a real URL parser, spreadsheet exports that neutralise cells which would otherwise be read as formulas, and uploads whose decompressed size is capped before it is read.

What we would tell another team

  • Audit against your invariants, not a generic list. The worst bugs we found were all “this retry breaks that promise”. No scanner knows your promises.
  • Every multi-step write needs a story for dying half-way. Write it down: which steps are irreversible, and who finishes or undoes the rest.
  • Idempotency keys belong to intents. If your retry mints a new key, you have built a cache, not a safeguard.
  • Run the slow tests on every push. A suite that only runs before releases rots quietly, and the first person to notice is the person in a hurry.
  • Test the contract, not each side of it. Two unit-tested halves can still disagree about a string.
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, 23 November 2026.