System Design Academy

Saving…

Lesson 5 of 7 in Module 50 of 45 lessons complete

Hospital ER Triage & Bed Allocation — Part B: Build

Module 5, lesson 5Case study15 min

Definitions

Heap

In plain English
A heap is a tree-shaped structure that keeps its smallest item at the top, so taking the next one is fast.
Think of it like
It is like a pile of exam papers where the most urgent always floats to the top.

Starvation

In plain English
Starvation is when an item waits forever because higher-priority items keep arriving.
Think of it like
It is like a quiet customer never being served in a pushy queue.

The brief

Build er-triage with six patients, three beds and three concurrent nurse callers. Then add a testable waiting-time adjustment.

What it must do

  • Register patients with acuity from 1 to 5.
  • Order waiting patients by acuity, then arrival time; preserve registration order for exact ties.
  • Level 1 requires resuscitation; children under 16 prefer paediatric beds, then general beds.
  • Other patients use general beds; alert doctors when a level-1 patient arrives.
  • Move Waiting → InBed → Discharged or Admitted; release the ER bed at either exit.

How well it must do it

  • Prevent double booking when several nurses allocate concurrently.
  • Use O(log n) heap insertion and removal; bed matching also scans the small bed pool.
  • Change matching rules without changing the allocator loop.

Out of scope

  • Medical records and clinical advice.
  • Staff rostering and billing.

Design walkthrough

Patients and checked transitions

patient.go — Keep the clinical acuity unchanged.
Go
package main

import (
	"errors"
	"time"
)

type State string

const (
	Waiting    State = "waiting"
	InBed      State = "in-bed"
	Discharged State = "discharged"
	Admitted   State = "admitted"
)

type Patient struct {
	ID          string
	Age, Acuity int
	Arrived     time.Time
	State       State
	BedID       string
	sequence    int
}

func (p *Patient) Move(next State) error {
	allowed := p.State == Waiting && next == InBed ||
		p.State == InBed && (next == Discharged || next == Admitted)
	if !allowed {
		return errors.New("invalid patient transition")
	}
	p.State = next
	return nil
}

Callers submit values, not shared patient pointers. Only Allocator methods change registered patients, under its mutex.

A waiting heap

waiting.go — Implement the storage operations required by container/heap.
Go
package main

import "time"

type WaitingList struct {
	patients []*Patient
	now      time.Time
	aging    bool
}

func (w WaitingList) Len() int { return len(w.patients) }
func (w WaitingList) Less(i, j int) bool {
	a, b := w.patients[i], w.patients[j]
	x, y := w.priority(a), w.priority(b)
	if x != y {
		return x < y
	}
	if !a.Arrived.Equal(b.Arrived) {
		return a.Arrived.Before(b.Arrived)
	}
	return a.sequence < b.sequence
}
func (w WaitingList) Swap(i, j int) {
	w.patients[i], w.patients[j] = w.patients[j], w.patients[i]
}
func (w *WaitingList) Push(x any) {
	w.patients = append(w.patients, x.(*Patient))
}
func (w *WaitingList) Pop() any {
	n := len(w.patients) - 1
	p := w.patients[n]
	w.patients[n] = nil
	w.patients = w.patients[:n]
	return p
}

These Push and Pop methods only move storage. Call heap.Push and heap.Pop so the library also restores heap ordering.

priority.go — Snapshot time before comparing priorities.
Go
package main

import (
	"container/heap"
	"time"
)

type Clock interface{ Now() time.Time }
type FixedClock struct{ At time.Time }

func (c FixedClock) Now() time.Time { return c.At }
func (w WaitingList) priority(p *Patient) int {
	score := p.Acuity
	if w.aging && score > 2 && w.now.Sub(p.Arrived) >= 2*time.Hour {
		score--
	}
	return score
}
func (a *Allocator) Refresh(aging bool) {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.waiting.now = a.clock.Now()
	a.waiting.aging = aging
	heap.Init(&a.waiting)
}

Do not read a moving clock inside Less. A changing comparison can invalidate the heap. Refresh snapshots time and rebuilds in O(n).

A safe bed pool

beds.go — Choose, check and reserve under one mutex.
Go
package main

import "sync"

type BedType string

const (
	Resus      BedType = "resuscitation"
	General    BedType = "general"
	Paediatric BedType = "paediatric"
)

type Bed struct {
	ID        string
	Type      BedType
	PatientID string
}
type BedPool struct {
	mu   sync.Mutex
	beds []Bed
}

func (b *BedPool) Take(id string, types []BedType) (string, bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	for _, kind := range types {
		for i := range b.beds {
			bed := &b.beds[i]
			if bed.Type == kind && bed.PatientID == "" {
				bed.PatientID = id
				return bed.ID, true
			}
		}
	}
	return "", false
}

Reservation and release use the same pool lock. No caller can observe a partly updated occupancy record.

release.go — Release an occupied bed or report an error.
Go
package main

import "errors"

func (b *BedPool) Release(id string) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	for i := range b.beds {
		if b.beds[i].ID == id && b.beds[i].PatientID != "" {
			b.beds[i].PatientID = ""
			return nil
		}
	}
	return errors.New("bed not occupied")
}

Matching scans the bed pool, so total allocation is O(log n + b) for b beds. The heap alone gives the O(log n) part.

matching.go — Clinical level 1 wins over the child preference.
Go
package main

type MatchingRule interface{ Types(*Patient) []BedType }
type Standard struct{}

func (Standard) Types(p *Patient) []BedType {
	if p.Acuity == 1 {
		return []BedType{Resus}
	}
	if p.Age < 16 {
		return []BedType{Paediatric, General}
	}
	return []BedType{General}
}

Coordinate arrival and allocation

allocator.go — Validate and register before alerting outside the lock.
Go
package main

import (
	"container/heap"
	"errors"
	"sync"
)

type AlertSink interface{ LevelOne(string) }
type Allocator struct {
	mu       sync.Mutex
	waiting  WaitingList
	pool     *BedPool
	rule     MatchingRule
	alerts   AlertSink
	clock    Clock
	patients map[string]*Patient
	history  []string
}

func (a *Allocator) Arrive(p Patient) error {
	a.mu.Lock()
	if p.ID == "" || p.Age < 0 || p.Acuity < 1 || p.Acuity > 5 {
		a.mu.Unlock()
		return errors.New("invalid patient")
	}
	if _, ok := a.patients[p.ID]; ok {
		a.mu.Unlock()
		return errors.New("duplicate patient")
	}
	p.State, p.sequence = Waiting, len(a.patients)
	a.patients[p.ID] = &p
	heap.Push(&a.waiting, &p)
	a.mu.Unlock()
	if p.Acuity == 1 {
		a.alerts.LevelOne(p.ID)
	}
	return nil
}

All nurses use Allocate. It holds the coordination lock across selecting a patient and reserving the bed.

allocate.go — Leave the heap unchanged when its head cannot get a bed.
Go
package main

import (
	"container/heap"
	"errors"
)

func (a *Allocator) Allocate() bool {
	a.mu.Lock()
	defer a.mu.Unlock()
	if a.waiting.Len() == 0 {
		return false
	}
	p := a.waiting.patients[0]
	bed, ok := a.pool.Take(p.ID, a.rule.Types(p))
	if !ok {
		return false
	}
	heap.Pop(&a.waiting)
	if err := p.Move(InBed); err != nil {
		panic(err)
	}
	p.BedID = bed
	a.history = append(a.history, p.ID+" -> "+bed)
	return true
}
func (a *Allocator) Discharge(id string, next State) error {
	a.mu.Lock()
	defer a.mu.Unlock()
	p, ok := a.patients[id]
	if !ok || p.State != InBed || (next != Discharged && next != Admitted) {
		return errors.New("patient cannot leave")
	}
	if err := a.pool.Release(p.BedID); err != nil {
		return err
	}
	return p.Move(next)
}

A blocked head stops allocation. This preserves strict priority but can leave another bed type idle; bypassing needs a different scheduling policy.

Nurse A completes a protected reservation before Nurse B can select the next waiting patient.

Nurse callers share one check-and-assign boundary.

Nurse A completes a protected reservation before Nurse B can select the next waiting patient.

Run six patients with three nurses

demo.go — Capture snapshots while holding the allocator lock.
Go
package main

import (
	"fmt"
	"sync"
)

type ConsoleAlert struct{}

func (ConsoleAlert) LevelOne(id string) { fmt.Println("alert", id) }
func (a *Allocator) InBeds() []string {
	a.mu.Lock()
	defer a.mu.Unlock()
	var ids []string
	for id, p := range a.patients {
		if p.State == InBed {
			ids = append(ids, id)
		}
	}
	return ids
}
func nurses(a *Allocator) {
	var wg sync.WaitGroup
	for range 3 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for a.Allocate() {
			}
		}()
	}
	wg.Wait()
}
func must(err error) {
	if err != nil {
		panic(err)
	}
}

The lock records assignment order, so printing after nurses join is stable. Which nurse wins the lock is deliberately unspecified.

main.go — Release each wave so all six patients can finish.
Go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
	pool := &BedPool{beds: []Bed{{"R", Resus, ""}, {"G", General, ""}, {"P", Paediatric, ""}}}
	a := &Allocator{pool: pool, rule: Standard{}, alerts: ConsoleAlert{},
		clock: FixedClock{now}, patients: map[string]*Patient{}}
	a.Refresh(false)
	ages, levels := []int{8, 40, 12, 50, 60, 10}, []int{1, 2, 2, 3, 4, 5}
	for i, id := range []string{"A", "B", "C", "D", "E", "F"} {
		must(a.Arrive(Patient{ID: id, Age: ages[i], Acuity: levels[i], Arrived: now}))
	}
	for {
		nurses(a)
		occupied := a.InBeds()
		if len(occupied) == 0 {
			break
		}
		for _, id := range occupied {
			must(a.Discharge(id, Discharged))
		}
	}
	for _, assignment := range a.history {
		fmt.Println(assignment)
	}
	if len(a.history) != 6 {
		panic("expected six assignments")
	}
	checkAging(now)
}
output.txt — The level-1 child receives the resuscitation bed.
Text
alert A
A -> R
B -> G
C -> P
D -> G
E -> G
F -> P
aging check: 4 -> 3; clinical acuity stays 4

Extend it: aging

After two hours, raise scheduling priority by one level, with a floor of 2. Clinical acuity and bed compatibility never change.

Enable aging through Refresh(true). The priority function adds one condition; heap.Init rebuilds ordering at that snapshot. Refresh again when time advances.

aging_demo.go — Move an injected clock forward without sleeping.
Go
package main

import (
	"fmt"
	"time"
)

func checkAging(now time.Time) {
	patient := &Patient{ID: "old", Acuity: 4, Arrived: now}
	clock := FixedClock{now}
	waiting := WaitingList{now: clock.Now(), aging: true}
	if waiting.priority(patient) != 4 {
		panic("aged too early")
	}
	clock.At = now.Add(2 * time.Hour)
	waiting.now = clock.Now()
	if waiting.priority(patient) != 3 || patient.Acuity != 4 {
		panic("aging changed clinical acuity")
	}
	urgent := &Patient{Acuity: 2, Arrived: now}
	if waiting.priority(urgent) != 2 {
		panic("promoted to clinical level 1")
	}
	fmt.Println("aging check: 4 -> 3; clinical acuity stays 4")
}

This one-step boost reduces some long waits; it does not guarantee freedom from starvation. Real clinical prioritisation requires a separately reviewed policy.

Design decisions

Why a heap rather than a sorted slice?

Our choice

Encapsulate O(log n) insertion and removal behind WaitingList.

Why not the alternatives

  • Sort all patients on every arrivalIt repeats O(n log n) work when only one patient changed.

Why mutexes rather than a pool-owning goroutine?

Our choice

Keep queue selection, state and bed reservation in one protected operation.

Why not the alternatives

  • Send separate check and reserve messagesSeparate operations could choose the same resource unless carefully combined.

Why inject time?

Our choice

Snapshot a Clock so aging checks run without waiting.

Why not the alternatives

  • Call time.Now inside LessA changing comparison can invalidate heap order between operations.

Trade-offs

Pros

  • Concurrent nurses cannot double-book.
  • Arrival ties are deterministic.
  • Time-based comparisons use a stable snapshot.

Cons

  • Pool scans add O(b) work.
  • Priority refresh costs O(n).
  • Strict head ordering can leave beds idle.

Use when

  • Small pools with priority rules.
  • Deterministic scheduling demonstrations.

Avoid when

  • Unreviewed clinical deployment.
  • Scheduling that must bypass incompatible queue heads.

Quick check

What does Less compare first in the waiting heap?
Why inject a Clock for aging?

Takeaways

  • Use heap.Push and heap.Pop rather than calling their raw storage helpers.
  • Serialize queue selection and bed reservation to prevent double booking.
  • Refresh time-based priorities explicitly before rebuilding the heap.

Try the quick check above whenever you feel ready.

Previous: Hospital ER Triage & Bed Allocation — Part A: Design