Nov 18, 20269 min read

Restaurant Online Ordering Backend: Orders, Kitchen Tickets and Status

Build the backend behind direct online ordering for a restaurant group: server-side pricing, pickup slot capacity, payment webhooks, kitchen tickets per station, order status, and auto-cancelling unpaid orders.

Illustration for Restaurant Online Ordering Backend: Orders, Kitchen Tickets and Status

Restaurant groups move to direct online ordering to stop paying marketplace commissions on every order, and the work that matters is the backend: prices that cannot be tampered with in the browser, a kitchen that gets 40 orders for the same 12:15 pickup unless something caps it, tickets that reach the grill station and not the bar, and orders that sit unpaid forever when a customer closes the payment sheet.

This guide builds that backend for a multi-location restaurant: menu pricing, pickup slot capacity, payment confirmation with webhooks, kitchen tickets routed to stations, status updates and cleanup.

Ordering backend at a glance

PartJobWhere it lives
MenuItems, modifiers, prices, availability per locationPostgres
Order APIValidate cart, price on the server, reserve slotTyped API
Pickup slotsCapacity per location per 15 minutesPostgres counters
PaymentsPayment intent at checkout, webhook confirmsPayment provider plus webhook endpoint
Kitchen ticketsOne ticket per station per paid orderPub/Sub
StatusPlaced, paid, in prep, ready, picked upPostgres plus events
CleanupRelease slots of unpaid ordersScheduled job

Design decisions that matter

Price on the server. The client sends item IDs, modifier IDs and quantities, never prices. The order API loads prices for that location and computes the total, so a modified request cannot order a burger for one cent.

Capacity is a counter, not a count. Counting existing orders for a slot and then inserting races under load; two requests both see 11 of 12 and both insert. A single UPDATE ... SET reserved = reserved + $1 WHERE reserved + $1 <= capacity is atomic, as Postgres row-level locks serialize concurrent updates to one row.

Webhooks confirm payment. The browser's redirect after payment is not proof of payment. Create a PaymentIntent at checkout with the order ID in its metadata, and mark the order paid only when a signed webhook arrives. Webhooks can arrive more than once, so the status change must be conditional.

Tickets after payment, per station. The kitchen should only see paid orders, and a combo with fries, a burger and a shake touches three stations. Split items by station and publish one ticket per station.

How do you build this with Encore?

Encore

Encore is a backend framework with built-in infrastructure. You declare the database, the Pub/Sub topics, the payment secrets and the cron job in Go, and on deploy they are provisioned in your own AWS or GCP account. encore run starts Postgres and the topics locally. Encore cron jobs run on the Encore platform in deployed environments and do not run locally or in preview environments.

Schema

-- orders/migrations/1_init.up.sql CREATE TABLE menu_items ( id TEXT NOT NULL, location_id TEXT NOT NULL, name TEXT NOT NULL, station TEXT NOT NULL, -- grill, fryer, bar price_cents INT NOT NULL, available BOOLEAN NOT NULL DEFAULT true, PRIMARY KEY (location_id, id) ); CREATE TABLE pickup_slots ( location_id TEXT NOT NULL, starts_at TIMESTAMPTZ NOT NULL, capacity INT NOT NULL, reserved INT NOT NULL DEFAULT 0, PRIMARY KEY (location_id, starts_at) ); CREATE TABLE orders ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), location_id TEXT NOT NULL, slot_starts_at TIMESTAMPTZ NOT NULL, status TEXT NOT NULL DEFAULT 'placed', -- placed, paid, in_prep, ready, picked_up, cancelled total_cents INT NOT NULL, items JSONB NOT NULL, idempotency_key TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX orders_unpaid_idx ON orders (created_at) WHERE status = 'placed';

Place an order

The API prices the cart from the database and reserves one capacity unit in the slot in the same transaction. If the slot is full, nothing is written. The client sends an idempotency key, and a retry of the same key returns the original order without reserving another slot.

package orders import ( "context" "encoding/json" "time" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{Migrations: "./migrations"}) type CartItem struct { ItemID string `json:"item_id"` Quantity int `json:"quantity"` } type PlaceParams struct { IdempotencyKey string `json:"idempotency_key"` LocationID string `json:"location_id"` SlotStart time.Time `json:"slot_start"` Items []CartItem `json:"items"` } type PlaceResponse struct { OrderID string `json:"order_id"` TotalCents int `json:"total_cents"` } type lineItem struct { ItemID string `json:"item_id"` Name string `json:"name"` Station string `json:"station"` Quantity int `json:"quantity"` } //encore:api public method=POST path=/orders func Place(ctx context.Context, p *PlaceParams) (*PlaceResponse, error) { if p.IdempotencyKey == "" || len(p.Items) == 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "idempotency_key and a non-empty cart are required"} } tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext($1))`, p.IdempotencyKey); err != nil { return nil, err } var existing PlaceResponse err = tx.QueryRow(ctx, ` SELECT id, total_cents FROM orders WHERE idempotency_key = $1`, p.IdempotencyKey).Scan(&existing.OrderID, &existing.TotalCents) if err == nil { return &existing, nil } if err != sqldb.ErrNoRows { return nil, err } total := 0 lines := make([]lineItem, 0, len(p.Items)) for _, it := range p.Items { if it.Quantity < 1 || it.Quantity > 20 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "invalid quantity"} } var li lineItem var price int err := tx.QueryRow(ctx, ` SELECT name, station, price_cents FROM menu_items WHERE location_id = $1 AND id = $2 AND available`, p.LocationID, it.ItemID).Scan(&li.Name, &li.Station, &price) if err != nil { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "item unavailable: " + it.ItemID} } li.ItemID, li.Quantity = it.ItemID, it.Quantity lines = append(lines, li) total += price * it.Quantity } res, err := tx.Exec(ctx, ` UPDATE pickup_slots SET reserved = reserved + 1 WHERE location_id = $1 AND starts_at = $2 AND reserved + 1 <= capacity`, p.LocationID, p.SlotStart) if err != nil { return nil, err } if res.RowsAffected() == 0 { if qerr := db.QueryRow(ctx, ` SELECT id, total_cents FROM orders WHERE idempotency_key = $1`, p.IdempotencyKey).Scan(&existing.OrderID, &existing.TotalCents); qerr == nil { return &existing, nil } return nil, &errs.Error{Code: errs.ResourceExhausted, Message: "pickup slot is full"} } itemsJSON, err := json.Marshal(lines) if err != nil { return nil, err } var id string err = tx.QueryRow(ctx, ` INSERT INTO orders (location_id, slot_starts_at, total_cents, items, idempotency_key) VALUES ($1, $2, $3, $4, $5) RETURNING id`, p.LocationID, p.SlotStart, total, itemsJSON, p.IdempotencyKey).Scan(&id) if err != nil { if qerr := db.QueryRow(ctx, ` SELECT id, total_cents FROM orders WHERE idempotency_key = $1`, p.IdempotencyKey).Scan(&existing.OrderID, &existing.TotalCents); qerr == nil { return &existing, nil } return nil, err } if err := tx.Commit(); err != nil { return nil, err } return &PlaceResponse{OrderID: id, TotalCents: total}, nil }

The frontend then creates a PaymentIntent for total_cents through a small endpoint that calls the payment provider with the order ID in metadata, using the provider's idempotency keys keyed on the order ID so a retried checkout does not create two intents.

Confirm payment and send kitchen tickets

The webhook is a raw endpoint, since signature verification needs the exact request body. The status guard WHERE status = 'placed' makes repeated deliveries harmless.

package orders import ( "encoding/json" "io" "net/http" "encore.dev/pubsub" "github.com/stripe/stripe-go/v87" "github.com/stripe/stripe-go/v87/webhook" ) var secrets struct { StripeWebhookSecret string } type KitchenTicket struct { OrderID string `json:"order_id"` LocationID string `json:"location_id"` Station string `json:"station"` Items []lineItem `json:"items"` } var Tickets = pubsub.NewTopic[*KitchenTicket]("kitchen-tickets", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) //encore:api public raw method=POST path=/webhooks/stripe func StripeWebhook(w http.ResponseWriter, req *http.Request) { payload, err := io.ReadAll(io.LimitReader(req.Body, 1<<16)) if err != nil { http.Error(w, "bad body", http.StatusBadRequest) return } event, err := webhook.ConstructEvent(payload, req.Header.Get("Stripe-Signature"), secrets.StripeWebhookSecret) if err != nil { http.Error(w, "bad signature", http.StatusBadRequest) return } if event.Type != "payment_intent.succeeded" { w.WriteHeader(http.StatusOK) return } var pi stripe.PaymentIntent if err := json.Unmarshal(event.Data.Raw, &pi); err != nil { http.Error(w, "bad object", http.StatusBadRequest) return } ctx := req.Context() var location string var raw []byte err = db.QueryRow(ctx, ` UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'placed' RETURNING location_id, items`, pi.Metadata["order_id"]).Scan(&location, &raw) if err != nil { // Already paid (repeated webhook) or unknown order: acknowledge. w.WriteHeader(http.StatusOK) return } var items []lineItem if err := json.Unmarshal(raw, &items); err != nil { http.Error(w, "bad items", http.StatusInternalServerError) return } byStation := map[string][]lineItem{} for _, li := range items { byStation[li.Station] = append(byStation[li.Station], li) } for station, lis := range byStation { t := &KitchenTicket{OrderID: pi.Metadata["order_id"], LocationID: location, Station: station, Items: lis} if _, err := Tickets.Publish(ctx, t); err != nil { http.Error(w, "publish failed", http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) }

If a publish fails after the status change, Stripe retries the webhook, but the guard now skips it, so tickets would be lost. When that matters, write the tickets to an outbox table in the same transaction as the status change and publish from there, as the transactional outbox guide shows. A kitchen display service subscribes to kitchen-tickets and filters by location and station, and its bump action moves the order to in_prep and ready.

Release unpaid orders

When customers abandon checkout, a cron job cancels orders that stayed unpaid for 20 minutes and gives their slot capacity back.

package orders import ( "context" "encore.dev/cron" ) var _ = cron.NewJob("cancel-unpaid", cron.JobConfig{ Title: "Cancel unpaid orders and release slots", Every: 5 * cron.Minute, Endpoint: CancelUnpaid, }) //encore:api private func CancelUnpaid(ctx context.Context) error { _, err := db.Exec(ctx, ` WITH cancelled AS ( UPDATE orders SET status = 'cancelled' WHERE status = 'placed' AND created_at < now() - interval '20 minutes' RETURNING location_id, slot_starts_at ), counts AS ( SELECT location_id, slot_starts_at, count(*) AS n FROM cancelled GROUP BY 1, 2 ) UPDATE pickup_slots s SET reserved = s.reserved - c.n FROM counts c WHERE s.location_id = c.location_id AND s.starts_at = c.slot_starts_at`) return err }

Encore cron jobs run on the Encore platform in deployed environments and do not run locally or in preview environments, so call CancelUnpaid directly from a test while developing. Payments that succeed after cancellation still trigger a webhook; the status guard ignores them, so refund those through the provider or let a support flow handle them.

When an agent adds a feature such as delivery zones or a new station, the topics, database tables and secrets it touches are declared in the Go code in the same pull request, so the infrastructure change is reviewed with the feature before it reaches your cloud.

Best fit: restaurant groups and ordering platforms building direct ordering on their own AWS or GCP account, with pricing, capacity and payment logic in code they control.

Build or buy

Hosted ordering products get a single location online in a day, and that is the right call for many restaurants. Building pays off for groups with many locations, a loyalty or catering flow the hosted tools do not fit, or integration with their own POS and data. The parts that matter most are the ones above: server-side prices, slot capacity, webhook-confirmed payment and paid-only kitchen tickets.

Frequently asked questions

What does a restaurant online ordering backend need?

A menu with server-side prices and modifiers, an order API that validates items and computes totals, pickup or delivery slot capacity so the kitchen is not overbooked, payment confirmation through the payment provider's webhooks, kitchen tickets routed to the right station, order status for the customer, and cleanup of orders that were never paid.

How do you stop a kitchen from getting too many online orders at once?

Give each location fixed time slots, for example 15 minutes, with a capacity in orders or prep units, and reserve capacity with a single conditional UPDATE that only succeeds while there is room. When the slot is full, the API offers the next slot instead of accepting the order.

Should kitchen tickets be sent when the order is placed or when it is paid?

Send them when it is paid. Sending tickets at checkout means the kitchen cooks orders whose payment later fails. Publish the kitchen event from the payment webhook handler after the order moves to paid, and use a status guard so a repeated webhook does not print a second ticket.

Can I build a restaurant ordering backend with Encore?

Yes. Encore gives you typed APIs for the menu and orders, Postgres for orders and slots, Pub/Sub for kitchen tickets and status events, secrets for the payment provider keys, and cron jobs for cleanup, all declared in Go and deployed to your own AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders