System Design Academy

Saving…

Lesson 3 of 7 in Module 50 of 45 lessons complete

Restaurant Kitchen Order Router — Part B: Build

Module 5, lesson 3Case study15 min

Definitions

Fan-out

In plain English
Fan-out means one producer distributing work to several consumers.
Think of it like
It is like a head chef calling tickets out to several stations.

The brief

Build kitchen-router with independent workers, safe counts and two ready subscribers. Then make desserts wait for mains.

What it must do

  • Accept orders from dine-in tablets and delivery apps.
  • Route each item by category and process each station’s normal tickets in arrival order.
  • Promote orders waiting over 15 minutes; explicit rush orders also use the rush lane.
  • Mark an order ready after all items finish; notify the front screen and delivery channel.

How well it must do it

  • Accept concurrent submissions without corrupting order counts.
  • Register new stations and routing rules without editing the router loop.
  • Give each station its own worker; bounded queues apply backpressure to submitters.

Out of scope

  • Payments and menu management.
  • Inventory and real kitchen hardware.

Design walkthrough

Orders and routing

order.go — Tickets can wait on a per-order completion signal.
Go
package main

import "time"

type Status string

const (
	Received Status = "received"
	Cooking  Status = "cooking"
	Ready    Status = "ready"
	PickedUp Status = "picked-up"
)

type Item struct{ Name, Category string }
type Order struct {
	ID, Channel string
	Items       []Item
	PlacedAt    time.Time
	Rush        bool
}
type Ticket struct {
	OrderID  string
	Item     Item
	PlacedAt time.Time
	After    <-chan struct{}
}

Validate every destination before sending anything. A category typo should reject the whole order.

routing.go — Map lookup stays outside the router loop.
Go
package main

type RoutingRule interface{ StationFor(Item) (string, bool) }
type ByCategory map[string]string

func (b ByCategory) StationFor(i Item) (string, bool) {
	name, ok := b[i.Category]
	return name, ok
}

Stations as goroutines

Go gives select no priority. A separate non-blocking check favours rush tickets already waiting. An expired normal head also gets checked between tickets.

station.go — A worker owns its pending normal ticket.
Go
package main

import (
	"context"
	"time"
)

type Station struct {
	rush, normal chan Ticket
	pending      *Ticket
	now          func() time.Time
}

func newStation(now func() time.Time) *Station {
	return &Station{rush: make(chan Ticket, 16), normal: make(chan Ticket, 16), now: now}
}
func (s *Station) Run(ctx context.Context, tracker *OrderTracker) {
	for {
		t, ok := s.next(ctx)
		if !ok {
			return
		}
		if t.After != nil {
			select {
			case <-ctx.Done():
				return
			case <-t.After:
			}
		}
		tracker.Start(t.OrderID)
		tracker.Done(t)
	}
}

Cooking is instantaneous in this fake. Real stations would prepare the item between Start and Done. Only the coordinator cancels workers.

priority.go — Check delayed normal work, then rush, then either lane.
Go
package main

import (
	"context"
	"time"
)

func (s *Station) next(ctx context.Context) (Ticket, bool) {
	select {
	case <-ctx.Done():
		return Ticket{}, false
	default:
	}
	if s.pending == nil {
		select {
		case t := <-s.normal:
			s.pending = &t
		default:
		}
	}
	if s.pending != nil && s.now().Sub(s.pending.PlacedAt) > 15*time.Minute {
		t := *s.pending
		s.pending = nil
		return t, true
	}
	select {
	case t := <-s.rush:
		return t, true
	default:
		if s.pending != nil {
			t := *s.pending
			s.pending = nil
			return t, true
		}
		select {
		case <-ctx.Done():
			return Ticket{}, false
		case t := <-s.rush:
			return t, true
		case t := <-s.normal:
			return t, true
		}
	}
}

An aged normal head becomes eligible before the next ticket. The last select can still choose either ready lane, so priority remains approximate.

Tracking orders safely

tracker.go — Counts and lifecycle state share one mutex.
Go
package main

import (
	"errors"
	"sync"
)

type Notifier interface{ OrderReady(string, string) }
type progress struct {
	remaining, mains int
	channel          string
	status           Status
	mainsDone        chan struct{}
}
type OrderTracker struct {
	mu          sync.Mutex
	orders      map[string]*progress
	subscribers []Notifier
}

func (t *OrderTracker) Track(o Order) (<-chan struct{}, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if _, exists := t.orders[o.ID]; exists {
		return nil, errors.New("duplicate order")
	}
	n := 0
	for _, item := range o.Items {
		if item.Category != "dessert" {
			n++
		}
	}
	gate := make(chan struct{})
	if n == 0 {
		close(gate)
	}
	t.orders[o.ID] = &progress{len(o.Items), n, o.Channel, Received, gate}
	return gate, nil
}

The mains signal closes once, when the last non-dessert ticket finishes. Dessert workers can wait without holding the tracker lock.

completion.go — Copy the notification data before releasing the lock.
Go
package main

import "errors"

func (t *OrderTracker) Start(id string) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.orders[id].status == Received {
		t.orders[id].status = Cooking
	}
}
func (t *OrderTracker) Done(ticket Ticket) {
	t.mu.Lock()
	order := t.orders[ticket.OrderID]
	order.remaining--
	if ticket.Item.Category != "dessert" {
		order.mains--
		if order.mains == 0 {
			close(order.mainsDone)
		}
	}
	ready := order.remaining == 0
	if ready {
		order.status = Ready
	}
	channel := order.channel
	t.mu.Unlock()
	if ready {
		for _, subscriber := range t.subscribers {
			subscriber.OrderReady(ticket.OrderID, channel)
		}
	}
}
func (t *OrderTracker) Pickup(id string) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	order, ok := t.orders[id]
	if !ok || order.status != Ready {
		return errors.New("order not ready")
	}
	order.status = PickedUp
	return nil
}

Subscribers are fixed before workers start. A slow subscriber can delay its worker, but cannot hold up other count updates.

The router

router.go — Resolve everything before tracking or enqueueing.
Go
package main

import (
	"errors"
	"time"
)

type Router struct {
	Rule     RoutingRule
	Stations map[string]*Station
	Tracker  *OrderTracker
	Now      func() time.Time
}

func (r *Router) Submit(o Order) error {
	if o.ID == "" || len(o.Items) == 0 {
		return errors.New("empty order")
	}
	targets := make([]*Station, len(o.Items))
	for i, item := range o.Items {
		name, ok := r.Rule.StationFor(item)
		if !ok || r.Stations[name] == nil {
			return errors.New("unknown category")
		}
		targets[i] = r.Stations[name]
	}
	gate, err := r.Tracker.Track(o)
	if err != nil {
		return err
	}
	rush := o.Rush || r.Now().Sub(o.PlacedAt) > 15*time.Minute
	for i, item := range o.Items {
		ticket := Ticket{OrderID: o.ID, Item: item, PlacedAt: o.PlacedAt}
		if item.Category == "dessert" {
			ticket.After = gate
		}
		lane := targets[i].normal
		if rush {
			lane = targets[i].rush
		}
		lane <- ticket
	}
	return nil
}

Normal tickets stay FIFO within their lane. Rush tickets may overtake them. Submit applies backpressure when a destination queue fills.

Treat routing maps as immutable after startup. Stop submissions and wait for readiness before cancellation; cancellation itself does not drain queued tickets.

Run it

notify.go — Two subscribers represent the screen and delivery channel.
Go
package main

import "fmt"

type Console struct{ Name string }

func (c Console) OrderReady(id, channel string) {
	fmt.Println(c.Name, id, channel, "ready")
}

type ReadySignal struct{ ready chan string }

func (s ReadySignal) OrderReady(id, _ string) { s.ready <- id }

Register all workers before submitting. The ready signal arrives after both console notifications, so shutdown cannot cut them off.

main.go — Run three orders, then join every worker.
Go
package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ready := make(chan string, 3)
	tracker := &OrderTracker{orders: map[string]*progress{}, subscribers: []Notifier{
		Console{"front"}, Console{"delivery"}, ReadySignal{ready},
	}}
	now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
	clock := func() time.Time { return now }
	stations := map[string]*Station{"grill": newStation(clock), "drinks": newStation(clock)}
	rules := ByCategory{"main": "grill", "drink": "drinks"}
	stations["dessert"] = newStation(clock)
	rules["dessert"] = "dessert"
	router := Router{rules, stations, tracker, clock}
	var workers sync.WaitGroup
	for _, station := range stations {
		workers.Add(1)
		go func(s *Station) { defer workers.Done(); s.Run(ctx, tracker) }(station)
	}
	for i, id := range []string{"A", "B", "C"} {
		items := []Item{{"meal", "main"}, {"water", "drink"}, {"cake", "dessert"}}
		order := Order{id, "tablet", items, now.Add(-time.Duration(i) * 8 * time.Minute), i == 1}
		if err := router.Submit(order); err != nil {
			panic(err)
		}
	}
	for range 3 {
		if err := tracker.Pickup(<-ready); err != nil {
			panic(err)
		}
	}
	cancel()
	workers.Wait()
	fmt.Println("workers stopped")
}
output.txt — One possible run; order notifications can interleave.
Text
front A tablet ready
delivery A tablet ready
front B tablet ready
delivery B tablet ready
front C tablet ready
delivery C tablet ready
workers stopped

Extend it: a dessert station that waits for mains

The final code includes the extension. Station registration and the routing map gain one entry each; Router and Tracker keep their loops.

Those two edits only work because the types already include a dependency signal. Without that seam, adding a dessert station would not enforce sequencing.

The last main closes a per-order signal that releases the dessert worker before its ticket completes.

Dessert waits for completion, not a guessed delay.

The last main closes a per-order signal that releases the dessert worker before its ticket completes.

Keep desserts on their own station. Routing a dessert ahead of its mains onto the same worker could deadlock. A waiting dessert can delay later desserts.

Design decisions

Where does the all-items-done count live?

Our choice

Keep order counts and state together behind the tracker mutex.

Why not the alternatives

  • An atomic counter for every orderYou still need a protected map and coordinated lifecycle updates.

How do we shut down?

Our choice

Wait for accepted orders, cancel the context, then join workers.

Why not the alternatives

  • Close queues while submitters can sendA concurrent send to a closed channel panics.

How are notifications delivered?

Our choice

Use Notifier subscribers, with console output for this demo.

Why not the alternatives

  • Print inside the tracker lockOutput becomes coupled to count updates and blocks the shared lock.

Trade-offs

Pros

  • Stations share no cooking lock.
  • Unknown categories fail before side effects.
  • Dessert waits on an explicit completion signal.

Cons

  • Rush priority is approximate.
  • A full queue blocks its submitter.
  • Cancellation abandons work unless you drain first.

Use when

  • Independent specialised workers.
  • A small in-memory demonstration.

Avoid when

  • Durable delivery across crashes.
  • Strict priority or unbounded throughput.

Quick check

Why call notifiers after releasing the tracker's mutex?
Go's select picks randomly among ready cases. How does the station favour rush tickets?

Takeaways

  • Validate all routes before accepting an order.
  • Protect counts with a mutex and call subscribers after unlocking.
  • Drain accepted work before cancelling workers and joining them.

Try the quick check above whenever you feel ready.

Previous: Restaurant Kitchen Order Router — Part A: Design