If latency budgets leave no room for synchronous retries, separate external hall calls from internal car requests, schedule each car's stops with two directional heaps (min-heap UP, max-heap DOWN) under a per-elevator lock, and inject `DispatchStrategy`.
TL;DR30-second simplified summary▾
Core Mechanics: In a 50-floor building with 6 elevators, dozens of passengers press hall and cabin buttons concurrently.
Visual & Structural Flow: Depicts Per-Elevator Directional LOOK & Maintenance State Machine (IDLE -> MOVING_UP -> MOVING_DOWN -> MAINTENANCE); HallRequest -> DispatchStrategy -> Per-Car LOOK Heaps (Hall / Cabin Panel -> ElevatorController -> DispatchStrategy -> ElevatorCar[i] (Lock)).
Trade-Offs & Production: A single Queue<Integer> per elevator cannot reorder stops along the way, while hardcoding NearestElevator inside BuildingController violates the Open-Closed Principle when. Structure the system around three clean abstractions: ElevatorCar (Per-Car Lock + Dual Heaps): Maintains upStops (min-heap) and downStops (max-heap) + currentWeightKg.
Failure Modes & Application: Directional sweep scheduling and decoupled dispatch strategies appear across systems engineering: OS Disk & I/O Schedulers: Classic Elevator/LOOK algorithms minimize disk-head seek latency without starving outer tracks.
Why multi-elevator dispatch is a classic LLD concurrency & scheduling problem.
Why this matters: The mechanism: understand how Why multi-elevator dispatch is a classic LLD concurrency & scheduling problem works from first principles.
Think of Why multi-elevator dispatch is a classic LLD concurrency & scheduling problem as the intuition layer for Design a Multi-Elevator Dispatch System (LLD): The mechanism: understand how Why multi-elevator dispatch is a classic LLD concurrency & scheduling problem works from first principles.
In a 50-floor building with 6 elevators, dozens of passengers press hall and cabin buttons concurrently. A clean LLD must prevent starvation of opposite-direction floors, isolate per-car scheduling state from global dispatch heuristics, and handle capacity limits or MAINTENANCE transitions without deadlocks.
FIFO thrashing, starvation, and global-lock bottlenecks.
Why this matters: The problem: see what breaks without FIFO thrashing, starvation, and global-lock bottlenecks under real concurrency or scale.
Naive elevator controllers fail under peak lobby rush:
- FIFO Yo-Yo Thrashing: Serving requests strictly in arrival order (
5 -> 48 -> 7 -> 42) wastes travel time and starves intermediate floors. - Infinite Direction Starvation: Continuously inserting new
UPrequests above can starveDOWNpassengers unless the car commits to its current sweep. - Global Lock Contention: Locking all 6 cars behind one mutex blocks cabin button presses while another car's door opens.
Per-Elevator Directional LOOK & Maintenance State Machine
Each car sweeps its current directional heap (LOOK) before reversing, guaranteeing zero starvation.
- Problem
- How to implement Design a Multi-Elevator Dispatch System (LLD) without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- If latency budgets leave no room for synchronous retries, separate external hall calls from internal car requests, schedule each car's stops with two directional heaps (min-heap UP, max-heap DOWN) under a per-elevator lock, and inject
DispatchStrategy. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Design a Multi-Elevator Dispatch System (LLD) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive FCFS queues and hardcoded nearest-car `if/else` chains.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Naive FCFS queues and hardcoded nearest-car if/else chains as the intuition layer for Design a Multi-Elevator Dispatch System (LLD): Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
A single Queue<Integer> per elevator cannot reorder stops along the way, while hardcoding NearestElevator inside BuildingController violates the Open-Closed Principle when you need LoadBalanced or rush-hour zoning strategies.
Naive FCFS queues and hardcoded nearest-car `if/else` chains
Enterprise solution: Dual Directional Heaps + Strategy Pattern.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Structure the system around three clean abstractions:
ElevatorCar(Per-Car Lock + Dual Heaps): MaintainsupStops(min-heap) anddownStops(max-heap) +currentWeightKg/maxCapacityKgguarded by its ownReentrantLock(LOOKalgorithm reverses only when the active directional heap empties).DispatchStrategyInterface:selectElevator(cars, HallRequest)scores eligible (!= MAINTENANCE, below capacity) cars—swappable betweenNearestDirectionalStrategyandLoadBalancedStrategy.ElevatorController: Routes externalHallRequest(floor, dir)throughDispatchStrategyand delegates internalCabinRequest(floor)directly to the car.
HallRequest -> DispatchStrategy -> Per-Car LOOK Heaps
Pluggable DispatchStrategy picks the best eligible car while per-car locks isolate concurrent stop insertions.
import heapq, threading
from enum import Enum
class Direction(Enum):
UP = 1; DOWN = -1; IDLE = 0; MAINTENANCE = 99
class ElevatorCar:
def __init__(self, car_id: int, max_load: int = 800):
self.car_id, self.floor, self.dir = car_id, 1, Direction.IDLE
self.max_load, self.load = max_load, 0
self.up_heap: list[int] = [] # min-heap
self.down_heap: list[int] = [] # max-heap (store -floor)
self._seen: set[int] = set()
self._lock = threading.Lock()
def add_stop(self, target: int) -> None:
with self._lock:
if self.dir == Direction.MAINTENANCE or target in self._seen:
return
self._seen.add(target)
if target >= self.floor:
heapq.heappush(self.up_heap, target)
else:
heapq.heappush(self.down_heap, -target)
Where LOOK scheduling and State/Strategy LLD patterns apply.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Directional sweep scheduling and decoupled dispatch strategies appear across systems engineering:
- OS Disk & I/O Schedulers: Classic Elevator/LOOK algorithms minimize disk-head seek latency without starving outer tracks.
- Fleet & Robotics Dispatchers: Warehouse AGV and ride-share dispatchers swap
DispatchStrategyimplementations dynamically by traffic load.
Practice: Make the trade-off yourself.
Why does each `ElevatorCar` maintain two separate heaps (min-heap for UP, max-heap for DOWN) under LOOK scheduling?