Shelves / Software Architecture
SA·LLD
Low-Level Design Case Studies
Applying the whole volume to machine-coding and low-level design problems: a repeatable approach (clarify, model entities and behaviours, define interfaces, choose patterns, handle concurrency and extensibility, test), then five complete worked designs with runnable code: a parking lot (Java and Go), an LRU cache (Java, Go, Rust, Python), a thread-safe rate limiter (Java and Go), an elevator controller (Kotlin), and an expense-splitting service (TypeScript and Python), with an evaluation rubric for machine-coding rounds.
Start here: from a one-paragraph problem to working, tested code
A low-level design (or machine-coding) problem gives you a paragraph ("design a parking lot", "an LRU cache", "a rate limiter") and an hour, and asks for working, extensible code. The skill isn't knowing a stock answer; it's a repeatable approach: clarify requirements and limits, model the entities and their behaviours, define interfaces first, pick patterns only where the problem calls for them, handle concurrency explicitly, and test the edge cases.
Two small designs, tested the way an interviewer would probe them
An LRU cache (hash map + doubly linked list, O(1) get and put) and a token-bucket rate limiter with an injected clock:
TestLRUEvictsLeastRecentlyUsed PASS (capacity 2: put a, put b, get a, put c → b evicted, a survives)
TestBucketWithFakeClock PASS allowed 19 of 200 requests over 2 s (burst 10 + 5/s × 2 s ≈ 20)
Because the limiter takes a Now func() time.Time, the test drives two seconds of traffic in microseconds with exact, repeatable results; a limiter that calls time.Now() directly can only be tested with sleeps and luck.
The follow-up question: "is it thread-safe?"
Eight goroutines hammering the cache, with and without its mutex:
with the mutex: PASS, size exactly 100 (its capacity); clean under -race
without the mutex, 5 plain runs: 5 crashes: "fatal error: concurrent map writes" / "concurrent map read and map write"
without the mutex, under -race: 23 DATA RACE reports, pointing at the map and list lines
Go's runtime detects some concurrent map misuse and kills the program; other languages silently corrupt the structure instead. Saying "I'd guard get and put with one mutex (or shard the cache by key for less contention)" and proving it with a race-detector test is what turns a correct design into a production-ready one.
How deep to go in low-level design
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L4 everywhere, and its projects at L5.
| Level | What you can do |
|---|---|
| L1 | Follow a worked LLD solution and name its entities and patterns |
| L2 | Solve a standard problem (LRU, rate limiter, parking lot) with working code |
| L3 | Explain your design's trade-offs, complexity and extension points |
| L4 | Make it concurrency-safe and testable, and prove it with tests (race detector, fake clocks) |
| L5 | Solve an unfamiliar problem cleanly under time pressure, discussing alternatives |
| L6 | Set and assess LLD standards for interviews and code reviews |
A repeatable approach
Low-level design (LLD) turns requirements for a component or small application into classes/types, interfaces, relationships and working code. In machine-coding interviews you typically get 60–120 minutes to build a working, extensible, well-structured program (often in-memory, console or simple API). The same skills apply at work when designing a module.
- Clarify (5–10 minutes): actors, core use cases, scale (single process? concurrent?), what's out of scope, persistence (in-memory unless told), interface (CLI, API, tests). Write the requirements down as a short list.
- Model: nouns → candidate entities and value objects; verbs → behaviours; states → enums or state types. Prefer value objects for money, IDs, time ranges.
- Interfaces and relationships: who owns what; which operations belong to which type (Information Expert); where boundaries for variation are (strategies, repositories).
- Patterns only where the requirements show variation or complexity: Strategy (pricing, allocation, splitting rules), State (lifecycles), Factory (creation by type), Observer (notifications), Command (undo, queues), Decorator (cross-cutting).
- Robustness: input validation, error types, concurrency (thread safety where multiple users/threads act), idempotency, extensibility points.
- Implement incrementally: core happy path first, then edge cases; small tests; a driver/demo. Keep classes cohesive and names in the domain language.
Case 1: Parking lot
Requirements
- A parking lot has multiple floors; each floor has spots of types: motorcycle, compact, large, electric (with charger).
- Vehicles (motorcycle, car, truck, EV) enter, receive a ticket for an allocated spot, and exit, paying a fee based on duration and vehicle/spot type.
- Allocation strategy configurable (nearest to entrance, lowest floor first, EV-first for EVs).
- Pricing strategy configurable (hourly with first-hour rate, flat weekend rate).
- Show availability per floor and type.
- Multiple entry gates operate concurrently: no spot may be double-allocated.
- Out of scope: real payments, persistence, reservations.
Model
| Concept | Type |
|---|---|
VehicleType, SpotType |
Enums with a compatibility rule (a car fits compact or large; a motorcycle fits any) |
Vehicle |
Value (licence plate, type) |
Spot |
Entity (ID, floor, type, occupied-by) |
Floor |
Entity holding spots, availability counts |
Ticket |
Entity (ID, vehicle, spot, entry time; exit time and fee when closed) |
Money |
Value object |
SpotAllocationStrategy |
Strategy interface |
PricingStrategy |
Strategy interface |
ParkingLot |
Facade/service: park(vehicle), exit(ticketId), availability() |
Implementation (Java 25)
import java.time.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
enum VehicleType { MOTORCYCLE, CAR, TRUCK, EV }
enum SpotType {
MOTORCYCLE, COMPACT, LARGE, ELECTRIC;
boolean fits(VehicleType v) {
return switch (v) {
case MOTORCYCLE -> true; // fits anywhere
case CAR -> this == COMPACT || this == LARGE;
case TRUCK -> this == LARGE;
case EV -> this == ELECTRIC || this == COMPACT || this == LARGE;
};
}
}
record Vehicle(String plate, VehicleType type) {
Vehicle { if (plate == null || plate.isBlank()) throw new IllegalArgumentException("plate required"); }
}
record Money(long paise) {
static Money rupees(long r) { return new Money(r * 100); }
Money plus(Money o) { return new Money(paise + o.paise); }
Money times(long n) { return new Money(paise * n); }
}
final class Spot {
final String id; final int floor; final SpotType type;
private Vehicle occupant; // guarded by ParkingLot's lock
Spot(String id, int floor, SpotType type) { this.id = id; this.floor = floor; this.type = type; }
boolean isFree() { return occupant == null; }
void occupy(Vehicle v) { if (occupant != null) throw new IllegalStateException(id + " occupied"); occupant = v; }
void release() { occupant = null; }
}
record Ticket(String id, Vehicle vehicle, Spot spot, Instant entry) {}
record Receipt(Ticket ticket, Instant exit, Money fee) {}
interface SpotAllocationStrategy { Optional<Spot> choose(List<Spot> freeSpots, Vehicle v); }
interface PricingStrategy { Money fee(Ticket t, Instant exit); }
final class NearestFirst implements SpotAllocationStrategy { // spots list is ordered by distance
public Optional<Spot> choose(List<Spot> free, Vehicle v) {
return free.stream().filter(s -> s.type.fits(v.type())).findFirst();
}
}
final class EvFirst implements SpotAllocationStrategy {
private final SpotAllocationStrategy fallback = new NearestFirst();
public Optional<Spot> choose(List<Spot> free, Vehicle v) {
if (v.type() == VehicleType.EV) {
var ev = free.stream().filter(s -> s.type == SpotType.ELECTRIC).findFirst();
if (ev.isPresent()) return ev;
}
return fallback.choose(free, v);
}
}
final class HourlyPricing implements PricingStrategy {
private final Map<SpotType, Money> firstHour, perHour;
HourlyPricing(Map<SpotType, Money> firstHour, Map<SpotType, Money> perHour) {
this.firstHour = Map.copyOf(firstHour); this.perHour = Map.copyOf(perHour);
}
public Money fee(Ticket t, Instant exit) {
long minutes = Math.max(1, Duration.between(t.entry(), exit).toMinutes());
long hours = (minutes + 59) / 60; // round up
SpotType type = t.spot().type;
return firstHour.get(type).plus(perHour.get(type).times(hours - 1));
}
}
final class ParkingLot {
private final List<Spot> spots; // ordered by distance to entrance
private final Map<String, Ticket> active = new ConcurrentHashMap<>();
private final SpotAllocationStrategy allocation;
private final PricingStrategy pricing;
private final Clock clock;
private final AtomicLong seq = new AtomicLong();
private final Object lock = new Object(); // allocation must be atomic
ParkingLot(List<Spot> spots, SpotAllocationStrategy a, PricingStrategy p, Clock clock) {
this.spots = List.copyOf(spots); this.allocation = a; this.pricing = p; this.clock = clock;
}
Ticket park(Vehicle v) {
synchronized (lock) { // no two gates get the same spot
List<Spot> free = spots.stream().filter(Spot::isFree).toList();
Spot spot = allocation.choose(free, v).orElseThrow(() -> new NoSpotAvailable(v.type()));
spot.occupy(v);
Ticket t = new Ticket("T" + seq.incrementAndGet(), v, spot, clock.instant());
active.put(t.id(), t);
return t;
}
}
Receipt exit(String ticketId) {
Ticket t = Optional.ofNullable(active.remove(ticketId)).orElseThrow(() -> new UnknownTicket(ticketId));
Instant now = clock.instant();
synchronized (lock) { t.spot().release(); }
return new Receipt(t, now, pricing.fee(t, now));
}
Map<Integer, Map<SpotType, Long>> availability() {
synchronized (lock) {
Map<Integer, Map<SpotType, Long>> out = new TreeMap<>();
for (Spot s : spots) if (s.isFree())
out.computeIfAbsent(s.floor, f -> new EnumMap<>(SpotType.class)).merge(s.type, 1L, Long::sum);
return out;
}
}
}
final class NoSpotAvailable extends RuntimeException { NoSpotAvailable(VehicleType t) { super("no spot for " + t); } }
final class UnknownTicket extends RuntimeException { UnknownTicket(String id) { super("unknown ticket " + id); } }
Design notes:
- Strategies isolate the parts most likely to change (allocation, pricing): adding weekend pricing is a new class (OCP).
- Clock injection makes fee tests deterministic (
Clock.fixed, thenClock.offset). - Concurrency: allocation (find + occupy) must be atomic; a single lock is simple and correct for one lot. At larger scale: per-spot-type free lists (
ConcurrentLinkedQueue<Spot>per type and floor) withpoll()for lock-free allocation, or optimisticcompareAndSeton spot state. exitremoves the ticket first so double exits fail fast (idempotency could return the same receipt instead).- Extensions: reservations (a
RESERVEDstate), multiple entry/exit gates, displays (Observer on availability changes), payment methods (Strategy), persistence (repository interfaces).
Go version (idiomatic style)
package parking
import (
"errors"
"fmt"
"sync"
"time"
)
type VehicleType int
const (Motorcycle VehicleType = iota; Car; Truck; EV)
type SpotType int
const (MotorcycleSpot SpotType = iota; Compact; Large; Electric)
func (s SpotType) Fits(v VehicleType) bool {
switch v {
case Motorcycle: return true
case Car: return s == Compact || s == Large
case Truck: return s == Large
case EV: return s == Electric || s == Compact || s == Large
}
return false
}
type Spot struct { ID string; Floor int; Type SpotType; occupied bool }
type Ticket struct { ID, Plate string; Vehicle VehicleType; Spot *Spot; Entry time.Time }
// Strategies as small interfaces (or plain function types)
type Allocator func(free []*Spot, v VehicleType) *Spot
type Pricer func(t Ticket, exit time.Time) int64 // paise
func NearestFirst(free []*Spot, v VehicleType) *Spot {
for _, s := range free { if s.Type.Fits(v) { return s } }
return nil
}
var ErrNoSpot = errors.New("no spot available")
var ErrUnknownTicket = errors.New("unknown ticket")
type Lot struct {
mu sync.Mutex
spots []*Spot
active map[string]Ticket
allocate Allocator
price Pricer
now func() time.Time
seq int
}
func NewLot(spots []*Spot, a Allocator, p Pricer, now func() time.Time) *Lot {
return &Lot{spots: spots, active: map[string]Ticket{}, allocate: a, price: p, now: now}
}
func (l *Lot) Park(plate string, v VehicleType) (Ticket, error) {
l.mu.Lock()
defer l.mu.Unlock()
free := make([]*Spot, 0, len(l.spots))
for _, s := range l.spots { if !s.occupied { free = append(free, s) } }
spot := l.allocate(free, v)
if spot == nil { return Ticket{}, ErrNoSpot }
spot.occupied = true
l.seq++
t := Ticket{ID: fmt.Sprintf("T%d", l.seq), Plate: plate, Vehicle: v, Spot: spot, Entry: l.now()}
l.active[t.ID] = t
return t, nil
}
func (l *Lot) Exit(ticketID string) (fee int64, err error) {
l.mu.Lock()
defer l.mu.Unlock()
t, ok := l.active[ticketID]
if !ok { return 0, ErrUnknownTicket }
delete(l.active, ticketID)
t.Spot.occupied = false
return l.price(t, l.now()), nil
}
Case 2: LRU cache
Requirements
get(key)returns the value or nothing;put(key, value)inserts/updates.- Fixed capacity; when full, evict the least recently used entry.
- Both operations O(1).
- Optional: thread safety, TTL, eviction listener, generic types.
Design
A hash map from key to node gives O(1) lookup; a doubly linked list orders entries by recency (most recent at head); moving a node to the head and removing the tail are O(1).
// Java: explicit doubly linked list + HashMap (what interviewers usually want)
public final class LruCache<K, V> {
private final class Node { K key; V value; Node prev, next; Node(K k, V v) { key = k; value = v; } }
private final int capacity;
private final Map<K, Node> map = new HashMap<>();
private final Node head = new Node(null, null), tail = new Node(null, null); // sentinels
public LruCache(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException("capacity must be > 0");
this.capacity = capacity;
head.next = tail; tail.prev = head;
}
public synchronized Optional<V> get(K key) {
Node n = map.get(key);
if (n == null) return Optional.empty();
unlink(n); addFirst(n);
return Optional.of(n.value);
}
public synchronized void put(K key, V value) {
Node n = map.get(key);
if (n != null) { n.value = value; unlink(n); addFirst(n); return; }
if (map.size() == capacity) {
Node lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
n = new Node(key, value);
map.put(key, n);
addFirst(n);
}
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFirst(Node n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; }
}
// Shortcut in production: new LinkedHashMap<>(16, 0.75f, true) { removeEldestEntry(...) } or Caffeine.
// Go: container/list provides the doubly linked list; generics for type safety
package lru
import (
"container/list"
"sync"
)
type entry[K comparable, V any] struct { key K; value V }
type Cache[K comparable, V any] struct {
mu sync.Mutex
cap int
ll *list.List
items map[K]*list.Element
}
func New[K comparable, V any](capacity int) *Cache[K, V] {
return &Cache[K, V]{cap: capacity, ll: list.New(), items: make(map[K]*list.Element, capacity)}
}
func (c *Cache[K, V]) Get(k K) (V, bool) {
c.mu.Lock(); defer c.mu.Unlock()
if el, ok := c.items[k]; ok {
c.ll.MoveToFront(el)
return el.Value.(*entry[K, V]).value, true
}
var zero V
return zero, false
}
func (c *Cache[K, V]) Put(k K, v V) {
c.mu.Lock(); defer c.mu.Unlock()
if el, ok := c.items[k]; ok {
el.Value.(*entry[K, V]).value = v
c.ll.MoveToFront(el)
return
}
if c.ll.Len() == c.cap {
oldest := c.ll.Back()
c.ll.Remove(oldest)
delete(c.items, oldest.Value.(*entry[K, V]).key)
}
c.items[k] = c.ll.PushFront(&entry[K, V]{k, v})
}
// Rust: doubly linked lists fight the borrow checker; use an index-based arena (Vec slots + indices)
use std::collections::HashMap;
use std::hash::Hash;
const NIL: usize = usize::MAX;
struct Node<K, V> { key: K, value: V, prev: usize, next: usize }
pub struct LruCache<K, V> {
map: HashMap<K, usize>,
nodes: Vec<Node<K, V>>,
head: usize, tail: usize, cap: usize,
}
impl<K: Hash + Eq + Clone, V> LruCache<K, V> {
pub fn new(cap: usize) -> Self {
assert!(cap > 0);
Self { map: HashMap::with_capacity(cap), nodes: Vec::with_capacity(cap), head: NIL, tail: NIL, cap }
}
pub fn get(&mut self, k: &K) -> Option<&V> {
let i = *self.map.get(k)?;
self.detach(i);
self.push_front(i);
Some(&self.nodes[i].value)
}
pub fn put(&mut self, k: K, v: V) {
if let Some(&i) = self.map.get(&k) {
self.nodes[i].value = v;
self.detach(i); self.push_front(i);
return;
}
let i = if self.nodes.len() < self.cap {
self.nodes.push(Node { key: k.clone(), value: v, prev: NIL, next: NIL });
self.nodes.len() - 1
} else {
let lru = self.tail; // reuse the evicted slot
self.detach(lru);
self.map.remove(&self.nodes[lru].key);
self.nodes[lru] = Node { key: k.clone(), value: v, prev: NIL, next: NIL };
lru
};
self.map.insert(k, i);
self.push_front(i);
}
fn detach(&mut self, i: usize) {
let (p, n) = (self.nodes[i].prev, self.nodes[i].next);
if p != NIL { self.nodes[p].next = n } else { self.head = n }
if n != NIL { self.nodes[n].prev = p } else { self.tail = p }
}
fn push_front(&mut self, i: usize) {
self.nodes[i].prev = NIL;
self.nodes[i].next = self.head;
if self.head != NIL { self.nodes[self.head].prev = i }
self.head = i;
if self.tail == NIL { self.tail = i }
}
}
# Python: OrderedDict gives O(1) move_to_end and popitem(last=False)
from collections import OrderedDict
from threading import Lock
from typing import Generic, Hashable, Optional, TypeVar
K = TypeVar("K", bound=Hashable)
V = TypeVar("V")
class LRUCache(Generic[K, V]):
def __init__(self, capacity: int) -> None:
if capacity <= 0:
raise ValueError("capacity must be > 0")
self._cap = capacity
self._data: "OrderedDict[K, V]" = OrderedDict()
self._lock = Lock()
def get(self, key: K) -> Optional[V]:
with self._lock:
if key not in self._data:
return None
self._data.move_to_end(key, last=False) # front = most recent
return self._data[key]
def put(self, key: K, value: V) -> None:
with self._lock:
self._data[key] = value
self._data.move_to_end(key, last=False)
if len(self._data) > self._cap:
self._data.popitem(last=True) # evict least recent
Extensions to discuss: TTL per entry (store expiry; lazy expiration on access plus periodic sweeping), eviction listeners (Observer), size-based capacity (weights), sharded caches for concurrency (N segments each with its own lock, by key hash), and better policies than LRU for real workloads (W-TinyLFU, Vol. 12 ch. 126).
Case 3: Rate limiter
Requirements
- Limit each client key (API key, user ID) to N requests per period, allowing short bursts up to a capacity.
tryAcquire(key)returns allowed or rejected (with retry-after).- Thread-safe under concurrent requests; memory bounded (idle keys cleaned up).
- Pluggable algorithm (token bucket, sliding window); injectable clock for tests.
- Out of scope: distributed limiting across servers (discussed below).
Token bucket: each key has a bucket with capacity tokens refilled at rate tokens/second; a request consumes one token if available (Vol. 5 ch. 76).
// Java: lock-free token bucket per key using an immutable state + compareAndSet
public interface RateLimiter { Decision tryAcquire(String key); }
public record Decision(boolean allowed, Duration retryAfter) {}
public final class TokenBucketLimiter implements RateLimiter {
private record State(double tokens, long lastNanos) {}
private final double capacity, refillPerNano;
private final LongSupplier nanoClock;
private final ConcurrentHashMap<String, AtomicReference<State>> buckets = new ConcurrentHashMap<>();
public TokenBucketLimiter(int capacity, double tokensPerSecond, LongSupplier nanoClock) {
this.capacity = capacity; this.refillPerNano = tokensPerSecond / 1e9; this.nanoClock = nanoClock;
}
@Override
public Decision tryAcquire(String key) {
AtomicReference<State> ref = buckets.computeIfAbsent(key,
k -> new AtomicReference<>(new State(capacity, nanoClock.getAsLong())));
while (true) {
State s = ref.get();
long now = nanoClock.getAsLong();
double tokens = Math.min(capacity, s.tokens() + (now - s.lastNanos()) * refillPerNano);
if (tokens < 1.0) {
long waitNanos = (long) Math.ceil((1.0 - tokens) / refillPerNano);
return new Decision(false, Duration.ofNanos(waitNanos));
}
if (ref.compareAndSet(s, new State(tokens - 1.0, now))) return new Decision(true, Duration.ZERO);
// another thread updated the bucket concurrently: retry with fresh state
}
}
// A scheduled task can evict buckets idle for longer than capacity/rate (they'd be full anyway).
}
// Go: per-key token buckets with a mutex per bucket and a sync.Map of buckets
type bucket struct {
mu sync.Mutex
tokens float64
last time.Time
}
type TokenBucket struct {
capacity float64
rate float64 // tokens per second
now func() time.Time
buckets sync.Map // key -> *bucket
}
func (tb *TokenBucket) Allow(key string) (bool, time.Duration) {
v, _ := tb.buckets.LoadOrStore(key, &bucket{tokens: tb.capacity, last: tb.now()})
b := v.(*bucket)
b.mu.Lock()
defer b.mu.Unlock()
now := tb.now()
b.tokens = math.Min(tb.capacity, b.tokens+now.Sub(b.last).Seconds()*tb.rate)
b.last = now
if b.tokens < 1 {
wait := time.Duration((1 - b.tokens) / tb.rate * float64(time.Second))
return false, wait
}
b.tokens--
return true, 0
}
// In production Go services: golang.org/x/time/rate.Limiter per key implements the same algorithm.
Tests with a fake clock: allow capacity requests immediately, reject the next, advance the clock by 1/rate seconds, allow one more. Add a concurrency test (100 goroutines/threads hammering one key; exactly capacity allowed).
Extensions: different limits per plan (Strategy/config), sliding window log/counter algorithm implementing the same interface, distributed limiting with Redis (atomic Lua script implementing the token bucket, or GCRA; Vol. 12 ch. 130), returning RateLimit headers, and memory cleanup of idle keys.
Case 4: Elevator controller
Requirements
- A building with N floors and M elevators.
- Hall calls (up/down buttons on a floor) and car calls (floor buttons inside an elevator).
- A dispatcher assigns each hall call to an elevator (pluggable strategy: nearest car, least busy, zoning).
- Each elevator follows the SCAN/LOOK algorithm: keep moving in the current direction while there are requests ahead, then reverse.
- Elevator states: idle, moving up, moving down, doors open, out of service.
- Simulation driven by ticks (one floor per tick) for testability.
Design
Elevator: current floor, direction, state, sets of requested stops above/below;step()advances one tick.Dispatcher(Strategy):assign(hallCall, elevators) → elevator.Controller: receives calls, assigns, ticks all elevators; emits events (Observer) for displays.
enum class Direction { UP, DOWN, IDLE }
sealed interface ElevatorState {
data object Idle : ElevatorState
data class Moving(val dir: Direction) : ElevatorState
data class DoorsOpen(val ticksLeft: Int) : ElevatorState
data object OutOfService : ElevatorState
}
data class HallCall(val floor: Int, val dir: Direction)
class Elevator(val id: Int, private val minFloor: Int, private val maxFloor: Int) {
var floor = minFloor; private set
var state: ElevatorState = ElevatorState.Idle; private set
private val stops = sortedSetOf<Int>()
val direction: Direction get() = (state as? ElevatorState.Moving)?.dir ?: Direction.IDLE
val pendingStops: Int get() = stops.size
fun addStop(f: Int) {
require(f in minFloor..maxFloor) { "floor $f out of range" }
if (state == ElevatorState.OutOfService) error("elevator $id out of service")
stops += f
}
/** One simulation tick, LOOK algorithm. Returns an event description or null. */
fun step(): String? = when (val s = state) {
ElevatorState.OutOfService -> null
is ElevatorState.DoorsOpen ->
if (s.ticksLeft > 1) { state = s.copy(ticksLeft = s.ticksLeft - 1); null }
else { state = nextMove(); "E$id doors closed at $floor" }
ElevatorState.Idle -> { state = nextMove(); null }
is ElevatorState.Moving -> {
floor += if (s.dir == Direction.UP) 1 else -1
if (stops.remove(floor)) { state = ElevatorState.DoorsOpen(ticksLeft = 2); "E$id arrived at $floor" }
else { state = nextMove(); null } // re-evaluate: never overshoot
}
}
private fun nextMove(): ElevatorState {
if (stops.isEmpty()) return ElevatorState.Idle
if (floor in stops) { stops -= floor; return ElevatorState.DoorsOpen(2) }
val ahead = when (direction) {
Direction.UP -> stops.any { it > floor }
Direction.DOWN -> stops.any { it < floor }
Direction.IDLE -> false
}
return when {
ahead -> ElevatorState.Moving(direction) // keep going (LOOK)
stops.any { it > floor } && stops.none { it < floor } -> ElevatorState.Moving(Direction.UP)
stops.any { it < floor } && stops.none { it > floor } -> ElevatorState.Moving(Direction.DOWN)
else -> ElevatorState.Moving( // both sides: go to nearest
if (stops.minOf { kotlin.math.abs(it - floor) } == stops.filter { it > floor }.minOfOrNull { it - floor })
Direction.UP else Direction.DOWN)
}
}
}
fun interface Dispatcher { fun assign(call: HallCall, elevators: List<Elevator>): Elevator }
/** Prefer an elevator already moving toward the call in the same direction; else the nearest idle; else least busy. */
val nearestSuitable = Dispatcher { call, elevators ->
val inService = elevators.filter { it.state != ElevatorState.OutOfService }
inService.filter {
(it.direction == Direction.UP && call.dir == Direction.UP && it.floor <= call.floor) ||
(it.direction == Direction.DOWN && call.dir == Direction.DOWN && it.floor >= call.floor)
}.minByOrNull { kotlin.math.abs(it.floor - call.floor) }
?: inService.filter { it.direction == Direction.IDLE }.minByOrNull { kotlin.math.abs(it.floor - call.floor) }
?: inService.minBy { it.pendingStops }
}
class Controller(private val elevators: List<Elevator>, private val dispatcher: Dispatcher,
private val onEvent: (String) -> Unit = ::println) {
fun hallCall(call: HallCall) = dispatcher.assign(call, elevators).addStop(call.floor)
fun carCall(elevatorId: Int, floor: Int) = elevators.first { it.id == elevatorId }.addStop(floor)
fun tick() = elevators.forEach { e -> e.step()?.let(onEvent) }
}
fun main() {
val ctl = Controller(List(2) { Elevator(it + 1, 0, 15) }, nearestSuitable)
ctl.hallCall(HallCall(7, Direction.DOWN))
ctl.carCall(2, 3)
repeat(20) { ctl.tick() }
}
Patterns used: State (sealed ElevatorState, explicit transitions), Strategy (Dispatcher), Observer (event callback for displays), Command-like call objects. Extensions: capacity/weight limits, express zones, peak-mode dispatching (morning up-peak), maintenance mode, emergency recall, destination dispatch (passengers enter destination in the lobby), and concurrency (a real controller runs ticks on a scheduler and receives calls from threads: serialise them through a queue/actor).
Case 5: Expense splitting service
Requirements
- Users belong to groups; anyone can add an expense paid by one user, split among participants by equal, exact amounts, or percentage rules.
- Maintain balances (who owes whom) and produce simplified settlements (minimise number of transfers).
- Record settlements (payments between users).
- Money must be exact (integer minor units); splits must sum exactly to the total (distribute remainders deterministically).
- Validate inputs (percentages sum to 100, exact amounts sum to total, participants in group).
Design
Moneyvalue object (minor units),UserId/GroupId.SplitStrategyinterface withEqual,Exact,Percentageimplementations (Strategy; new types like "shares" plug in).Ledgerkeeps net balance per user (positive = is owed, negative = owes) per group; expenses and settlements update it.simplify()uses a greedy algorithm: repeatedly match the largest creditor with the largest debtor (produces at most n−1 transfers; finding the true minimum is NP-hard in general, but greedy is standard).
// TypeScript
type UserId = string & { readonly __brand: "UserId" };
const u = (s: string) => s as UserId;
interface Split { user: UserId; amount: number } // minor units (paise)
interface SplitStrategy { split(total: number, participants: UserId[]): Split[] }
const equal: SplitStrategy = {
split(total, participants) {
const n = participants.length;
const base = Math.floor(total / n);
let remainder = total - base * n; // distribute leftover paise deterministically
return participants.map((user) => ({ user, amount: base + (remainder-- > 0 ? 1 : 0) }));
},
};
const exact = (amounts: Record<string, number>): SplitStrategy => ({
split(total, participants) {
const sum = participants.reduce((acc, p) => acc + (amounts[p] ?? 0), 0);
if (sum !== total) throw new Error(`exact amounts sum to ${sum}, expected ${total}`);
return participants.map((user) => ({ user, amount: amounts[user] }));
},
});
const percentage = (pcts: Record<string, number>): SplitStrategy => ({
split(total, participants) {
const sumPct = participants.reduce((a, p) => a + (pcts[p] ?? 0), 0);
if (Math.abs(sumPct - 100) > 1e-9) throw new Error("percentages must sum to 100");
const raw = participants.map((user) => ({ user, exact: (total * pcts[user]) / 100 }));
const floored = raw.map((r) => ({ user: r.user, amount: Math.floor(r.exact), frac: r.exact % 1 }));
let left = total - floored.reduce((a, s) => a + s.amount, 0);
floored.sort((a, b) => b.frac - a.frac); // largest remainder method
for (const s of floored) if (left-- > 0) s.amount += 1;
return floored.map(({ user, amount }) => ({ user, amount }));
},
});
class Group {
private balances = new Map<UserId, number>();
constructor(readonly members: Set<UserId>) { members.forEach((m) => this.balances.set(m, 0)); }
addExpense(paidBy: UserId, total: number, participants: UserId[], strategy: SplitStrategy) {
if (total <= 0) throw new Error("total must be positive");
for (const p of [paidBy, ...participants]) if (!this.members.has(p)) throw new Error(`${p} not in group`);
for (const { user, amount } of strategy.split(total, participants)) {
this.adjust(user, -amount); // each participant owes their share
}
this.adjust(paidBy, total); // payer is owed the total
}
settle(from: UserId, to: UserId, amount: number) { this.adjust(from, amount); this.adjust(to, -amount); }
simplify(): Array<{ from: UserId; to: UserId; amount: number }> {
const creditors = [...this.balances].filter(([, b]) => b > 0).map(([u, b]) => ({ u, b }));
const debtors = [...this.balances].filter(([, b]) => b < 0).map(([u, b]) => ({ u, b: -b }));
const out: Array<{ from: UserId; to: UserId; amount: number }> = [];
while (creditors.length && debtors.length) {
creditors.sort((a, b) => b.b - a.b); debtors.sort((a, b) => b.b - a.b);
const c = creditors[0], d = debtors[0];
const amt = Math.min(c.b, d.b);
out.push({ from: d.u, to: c.u, amount: amt });
c.b -= amt; d.b -= amt;
if (c.b === 0) creditors.shift();
if (d.b === 0) debtors.shift();
}
return out;
}
private adjust(user: UserId, delta: number) { this.balances.set(user, (this.balances.get(user) ?? 0) + delta); }
}
// demo
const g = new Group(new Set([u("ana"), u("ravi"), u("kim")]));
g.addExpense(u("ana"), 90000, [u("ana"), u("ravi"), u("kim")], equal); // ₹900 dinner
g.addExpense(u("ravi"), 30000, [u("ana"), u("kim")], percentage({ ana: 40, kim: 60 }));
console.log(g.simplify()); // [{ from: 'kim', to: 'ana', amount: 48000 }] — ravi is already square
# Python: same design with dataclasses and a Protocol for strategies
from dataclasses import dataclass, field
from typing import Protocol
class SplitStrategy(Protocol):
def split(self, total: int, participants: list[str]) -> dict[str, int]: ...
class Equal:
def split(self, total: int, participants: list[str]) -> dict[str, int]:
base, rem = divmod(total, len(participants))
return {p: base + (1 if i < rem else 0) for i, p in enumerate(participants)}
@dataclass
class Exact:
amounts: dict[str, int]
def split(self, total: int, participants: list[str]) -> dict[str, int]:
if sum(self.amounts[p] for p in participants) != total:
raise ValueError("exact amounts must sum to total")
return {p: self.amounts[p] for p in participants}
@dataclass
class Group:
members: set[str]
balances: dict[str, int] = field(default_factory=dict)
def add_expense(self, paid_by: str, total: int, participants: list[str], strategy: SplitStrategy) -> None:
if total <= 0 or not set(participants) <= self.members or paid_by not in self.members:
raise ValueError("invalid expense")
for user, share in strategy.split(total, participants).items():
self.balances[user] = self.balances.get(user, 0) - share
self.balances[paid_by] = self.balances.get(paid_by, 0) + total
def simplify(self) -> list[tuple[str, str, int]]:
creditors = sorted(((b, u) for u, b in self.balances.items() if b > 0), reverse=True)
debtors = sorted(((-b, u) for u, b in self.balances.items() if b < 0), reverse=True)
out, i, j = [], 0, 0
creditors = [list(x) for x in creditors]; debtors = [list(x) for x in debtors]
while i < len(creditors) and j < len(debtors):
amt = min(creditors[i][0], debtors[j][0])
out.append((debtors[j][1], creditors[i][1], amt))
creditors[i][0] -= amt; debtors[j][0] -= amt
if creditors[i][0] == 0: i += 1
if debtors[j][0] == 0: j += 1
return out
Key correctness points: integer money, remainder distribution that always sums to the total (test this with property-based tests: for any total and participant count, shares sum to total and differ by at most 1), input validation, and an invariant that all balances sum to zero (assert it after every operation). Extensions: multiple currencies (convert at expense time with recorded rates), expense edits/deletes (store expenses and recompute balances, or post reversing entries like a ledger), notifications (Observer), persistence (repositories), and concurrency (per-group locking or optimistic versioning).
Evaluation rubric for machine coding
| Dimension | Weak | Strong |
|---|---|---|
| Requirements | Starts coding immediately; misses edge cases | Clarifies scope, lists assumptions and out-of-scope items |
| Working code | Doesn't run, or only fragments | Runnable demo covering core flows, then extensions |
| Modelling | Primitive obsession, god class, anaemic data bags | Cohesive types, value objects, behaviour where the data is |
| Extensibility | Hard-coded if/else for every variant |
Strategies/interfaces at real variation points; OCP without over-engineering |
| Correctness | Ignores money rounding, invalid input, state errors | Validation, explicit errors, invariants asserted |
| Concurrency | Ignored when relevant | Identifies shared state, uses appropriate locks/atomics/actors, explains trade-offs |
| Code quality | Unclear names, long methods, duplication | Domain naming, small focused functions, consistent style |
| Testability | Untested; time and randomness hard-coded | Injected clock/IDs, unit tests for core rules |
| Communication | Silent or unstructured | Explains choices and trade-offs, adapts to follow-ups |
Practice set (each 60–90 minutes): parking lot, LRU/LFU cache, rate limiter, elevator system, splitwise, library management, movie ticket booking (seat locking with expiry), snake and ladder / tic-tac-toe / chess move validation, vending machine (State), ATM (State + Chain of Responsibility for cash dispensing), logger with levels and sinks (Chain + Strategy), in-memory key-value store with transactions (Command + undo), pub/sub message queue, task scheduler with priorities and retries, food delivery order lifecycle, hotel booking with overlapping ranges, inventory with reservations.
Lab: LLD solutions under test
Go 1.24.7 on the lab machine (2 vCPUs). lld.go contains an LRU cache (container/list + map, optional mutex) and a token-bucket limiter with an injectable clock; lld_test.go holds the tests.
Experiment 1: behaviour
--- PASS: TestLRUEvictsLeastRecentlyUsed
--- PASS: TestLRUConcurrentLocked (8 goroutines × 2,000 put+get over 300 keys; final size 100)
--- PASS: TestBucketWithFakeClock allowed 19 of 200 over 2 s (burst 10 + 5/s × 2 s ≈ 20)
ok lld 0.008s
The limiter test asserts a range (19–21) rather than an exact count, because refill timing at the boundary is legitimately off by one. Choosing that tolerance deliberately, and saying why, is part of the answer.
Experiment 2: concurrency
| Variant | Plain go test (5 runs) |
go test -race |
|---|---|---|
| mutex around get/put | pass | pass (1.09 s) |
| no mutex | 5/5 crashed: fatal error: concurrent map writes / concurrent map read and map write |
FAIL, 23 DATA RACE reports at lld.go:11, :16, :18 |
Note that even Get mutates (it moves the entry to the front of the list), so a read-write lock doesn't help an LRU: every operation needs the exclusive lock. Ways to scale it: shard into 16–64 caches by key hash; approximate LRU (CLOCK, sampled eviction as Redis does); or a concurrent cache library (Ristretto in Go, Caffeine in Java) that batches recency updates.
Experiment 3: the extension question
Interviewers usually end with "now add X". For the rate limiter: per-user limits (a map of buckets with idle eviction), distributed limits (Redis with a Lua script, Volume 12 chapter 133), or a sliding-window algorithm. For the cache: TTLs (store expiry per entry; check on get), metrics (a Decorator, chapter 137), or write-through to a store (a Strategy for the backing store). A design that took each of these as an additive change, without editing existing code paths, is what the volume has been teaching.
Try it yourself
- Shard the LRU into 16 locked caches and benchmark it against the single-mutex version with
go test -bench . -cpu 1,2. - Add per-user token buckets with eviction of users idle for 10 minutes, and test eviction with the fake clock.
- Implement the parking lot from Case 1 with concurrent
Parkcalls and prove no spot is assigned twice under-race. - Add TTLs to the LRU and test expiry with an injected clock.
Revision sheet: low-level design
Key ideas
- Approach: clarify → entities and behaviours → interfaces → patterns where needed → concurrency → tests → extensions.
- Parking lot: spots by type, allocation strategy, tickets and pricing strategy, concurrency on allocation.
- LRU cache: map + doubly linked list; every operation mutates recency; sharding or approximate LRU for scale.
- Rate limiter: token bucket, leaky bucket, fixed and sliding windows; injected clock; per-key buckets; distributed variants.
- Elevator: state machine per car, request scheduling (SCAN/LOOK), dispatcher strategy.
- Expense splitting: ledger of balances, simplification of debts, exact money arithmetic.
- Quality bar: readable names, small classes, clear interfaces, tests for edge cases and concurrency.
Numbers to remember
- Lab: token bucket with burst 10, 5/s → 19 of 200 requests allowed over 2 s.
- Lab: unlocked LRU crashed 5/5 runs;
-racereported 23 races.
Pitfalls
- Coding before clarifying; gold-plated class hierarchies.
- Ignoring concurrency until asked, then bolting on locks.
- Calling
time.Now()andranddirectly, making tests flaky. - Floats for money in expense splitting.
- No tests, or only happy-path tests.
Glossary
- Machine coding: timed implementation of a small system.
- Token bucket: limiter with refill rate and burst capacity.
- Lock striping / sharding: several locks over partitions of data.
- SCAN/LOOK: elevator scheduling algorithms.
- Debt simplification: minimising settlements between participants.