- Architecture
- Go
- Next.js
The architecture in one picture: a modular monolith in Go
Fravolo runs the counter, the kitchen, the books and the WhatsApp inbox for restaurants in several countries. All of it is one Go process, one Next.js process and a MongoDB database. This post is the whole system on one page, and the reasons it looks the way it does.
Why one binary
A restaurant does not need our order service to scale separately from our billing service. It needs the bill number to be right, the order to move only forwards, and one restaurant never to see another’s data. Those are correctness problems, and correctness is far easier to hold in one process: one transaction boundary, one deploy, one log stream and a stack trace that goes all the way down.
So the API is a modular monolith. apps/api/internal/modules holds 36 modules — order, pos, billing, catalog, inventory, printing, notify, walink and so on — compiled into a single binary. There is no RPC between them and no message broker. A call from the POS into billing is a Go function call.
Microservices solve an organisational problem we do not have yet. The seams are in the code, so we can cut along them when we do.
The picture
Four kinds of client reach the system. Staff use the console in a browser or inside our Android app, which wraps the same pages in a WebView and adds what a browser cannot do: ringing alerts, background printing and kiosk mode. Guests open their bill or the restaurant’s menu from a link. A restaurant’s own website talks to a signed partner API. And print bridges on a restaurant’s LAN pull print jobs.
A Caddy edge terminates TLS, stamps a request id on everything that arrives, and routes: the few server-to-server surfaces go straight to the API, and everything else goes to Next.js. The request id travels through the console, into the API, onto every log line and trace span, and into error responses — one id ties a complaint from a cashier to the exact line in the logs.
Seams without a network
The danger of a monolith is that everything ends up calling everything. We keep two rules. First, modules are built with constructor injection: a module receives the services it depends on when it is created, and never reaches into another module’s collections. Second, imports only flow one way. pos imports order and billing; order must not import pos.
Real dependencies are not that tidy. Accepting an online order has to fire a kitchen ticket, and kitchen tickets live in pos. Billing reads order sales for tax returns, so order cannot import billing to compute tax. Where a cycle would form, the lower module declares the small interface it needs, and the wiring code binds the implementation once both exist:
// Kitchen is what order needs from the counter: fire a ticket.
// Implemented by the pos module; bound in server.go so imports stay one-way.
type Kitchen interface {
FireOrder(ctx context.Context, o *Order) error
}
// SetKitchen connects the kitchen after both services exist.
func SetKitchen(s Service, k Kitchen) {
if impl, ok := s.(*service); ok {
impl.kitchen = k
}
}All of that binding happens in one file, internal/server/server.go. It is long, and deliberately so: it is the entire dependency graph of the product, readable top to bottom. A new engineer can see in one sitting that billing is built from orders, the POS from catalog, orders and billing, and that orders learn about the kitchen, the printers, stock, delivery and alerts afterwards.
billingSvc := billing.NewService(cfg, db, orderSvc)
order.SetTax(orderSvc, orderTax{billingSvc}) // order can't import billing
order.SetInvoicer(orderSvc, orderInvoicer{billingSvc})
posSvc := pos.NewService(db, catalogSvc, orderSvc, billingSvc)
order.SetKitchen(orderSvc, posSvc) // accept → kitchen ticket
order.SetStock(orderSvc, stockSvc)
printSvc := printing.NewService(db, posSvc, catalogSvc, log)
pos.SetPrinter(posSvc, printSvc) // KOT → print queue
order.SetCounter(orderSvc, printSvc) // new web order → slip
pos.SetReceipts(posSvc, receipts{loyaltySvc, ebillSvc, invSvc}) // settle fans outThe payoff is that a module boundary is a real boundary. If we ever need to run inventory on its own, the constructor becomes a client for a remote service and the callers do not change. We have not needed to, and we do not plan to until something forces it.
Background work lives in the same process
The same binary that serves HTTP also runs the background work. A one-minute loop drives a fixed list of jobs: expire unpaid website orders, issue any web invoice whose first attempt did not finish, find printers that have stopped taking jobs, send birthday messages and the weekly and nightly reports, ring again for online orders nobody has accepted, and flag orders running late.
Each job runs on its own goroutine, under its own deadline, and is skipped — with a warning in the log — if its previous run has not finished. One slow or hung job cannot hold up the others, and cannot pile up copies of itself.
type job struct {
name string
timeout time.Duration
run func(ctx context.Context, now time.Time)
busy atomic.Bool
}
func (j *job) tick(ctx context.Context, now time.Time) {
if !j.busy.CompareAndSwap(false, true) {
log.Warn("job still running; skipped this minute", "job", j.name)
return
}
safego.Go("job:"+j.name, func() {
defer j.busy.Store(false)
ctx, cancel := context.WithTimeout(ctx, j.timeout)
defer cancel()
j.run(ctx, now)
})
}In Go, a panic in any goroutine ends the whole process, so a bad record in one sweep could once have taken the API down with it. Background goroutines — jobs, WhatsApp sessions, e-bill sends, order dispatch — start through a small safego helper that recovers the panic, logs it with its stack and reports it, and the process carries on. Requests carry deadlines too (none for the live event stream, longer ones for AI readers and imports), and the database client bounds any operation that has no deadline of its own, so a slow query fails loudly instead of holding a connection.
One instance, on purpose
The API runs as a single instance, and the code says so. The job loop, the WhatsApp sessions (each linked number is a device session in a local file, which one process must own) and the in-memory store used when Redis is absent all assume one process, and nothing leases them between instances. Most jobs still claim their work with a conditional update — “mark this order as re-rung, but only if nobody has” — so a second instance would not repeat a send. That is groundwork, not a promise: running two API instances means first moving the loop and the sessions behind a lease.
The web app is a renderer and a proxy
The Next.js 15 app serves everything with a screen: the public site, the back office, the POS, the kitchen display, the captain’s phone, 80 mm print pages, and the guest’s bill and menu pages. It holds no database credentials and no signing keys. It renders, and it forwards.
- Server components call the API directly over the private network, forwarding the session and the request id.
- Client components (the POS, the inbox, the printer screens) call a same-origin catch-all route. It refuses cross-origin writes, attaches the session as a bearer token on the server, strips anything the browser should not be able to set, and passes the request on. The token never reaches client JavaScript.
- Live screens use a separate streaming route that passes server-sent events through unbuffered — the catch-all buffers whole responses, which is exactly wrong for a stream.
One small decision in that proxy carries a lot of weight. When the API cannot be reached, it answers 502. The POS treats a 502 or worse as “we are offline” and starts billing from its local queue. The proxy is where “the internet is down” becomes a signal the counter can act on.
Optional parts, honestly labelled
Redis is optional. Our key-value interface — one-time codes, rate counters, idempotency replays, revoked tokens — has two implementations: Redis, and an in-memory store. Start the API without Redis and it logs, loudly, that you must run exactly one instance. The live event bus works the same way: in-process fan-out by default, Redis pub/sub across replicas when Redis is there.
That keeps a developer laptop to two containers, and it keeps the production failure modes few. Redis holds no business data; losing it costs some rate-limit counters and forces some reconnects, never an order.
Shipping it
- 1Every push runs
go vetand the Go tests with the race detector — including the suites that need a real database: CI starts a MongoDB service for the job, so tenant isolation, placement moves and invoice numbering are tested against the real thing on every push. A small script also fails the build if new code reaches for a raw, unscoped collection. The console runs a type check and a full production build; the Android app runs its unit tests and lint. - 2A merge to main builds the API and console images.
- 3Deploy pulls the new images, runs the migration binary, and only then swaps the containers. A failed migration stops the swap, and the old version keeps serving.
Migrations are idempotent by rule: index creation, backfills and data adoptions all check before they write, so running them twice is harmless. That lets the deploy run them unconditionally every time, which is the only way we trust a step to run at all.
What we gave up, and what we would do differently
- One host, one API instance. Simple, cheap and easy to reason about; also a single machine to lose. Our recovery path is rebuilding the box from images against a managed database. Scaling out means putting a lease in front of the job loop and the WhatsApp sessions first; we would rather do that before we need it than during an incident.
- Jobs are independent, but still on one clock. Each job has its own goroutine and deadline now, and a job that overruns is skipped rather than stacked. The one-minute tick is still coarse; nothing a kitchen needs is finer than that, but it is not a scheduler.
- Late-bound hooks fail quietly. If a
Set…call is forgotten, the feature simply does nothing, and callers carry nil checks. A wiring test that asserts every hook is bound would catch that at build time; we would add it on day one if starting again. - A 540-line constructor. It is the price of having the whole graph in one place. We would still pay it.