2Brute2Best
πŸ”₯0
P18

Design Uber / Ola Ride Dispatch & Trip Lifecycle

Hard High-frequency interview topic Pro OnlyStrategyStateObserver
⚑ 30-Second Interview Cheat SheetP18 · 45-Min Design Plan
4 Patterns Combined
1. Scope Boundaries

In a 45-minute LLD interview, this problem evaluates state machine design, swappable dispatch algorithms, dynamic fare calculation, and real-time observer notifications. Scope the design to: modeling riders and drivers, matching drivers via interchangeable strategies (NearestDriverStrategy, HighestRatedDriverStrategy), calculating fares with normal and surge strategies, enforcing a strict trip lifecycle (Requested β†’ DriverAssigned β†’ InProgress β†’ Completed / Cancelled), and broadcasting status updates to observers. Geospatial indexing (H3/S2) and payment gateways can be highlighted as production extensions.

2. Core Noun Entities
Tripstateful-class
ITripStateinterface
IDriverMatchingStrategyinterface
IFareStrategyinterface
3. Hotspot β†’ Pattern
Trip lifecycle progression and legal action guards β†’ State Pattern (ITripState with concrete lifecycle state classes)
Driver matching heuristics (Nearest vs Highest-Rated vs Batched) β†’ Strategy Pattern (IDriverMatchingStrategy)
Dynamic fare pricing models (Standard vs Peak Surge) β†’ Strategy Pattern (IFareStrategy: NormalFareStrategy and SurgeFareStrategy)
Broadcasting lifecycle milestones to mobile clients and telemetry β†’ Observer Pattern (ITripObserver)
01

Problem statement & clarifying requirements

Design a ride-sharing dispatch service like Uber or Ola. The platform must match ride requests to drivers using swappable strategies (such as Nearest Driver or Highest-Rated Driver), calculate fares dynamically under normal and surge pricing, guide each ride through a strict Trip Lifecycle State Machine (Requested β†’ DriverAssigned β†’ InProgress β†’ Completed / Cancelled), and broadcast live status updates to both rider and driver via an Observer event bus.

Questions you should ask the interviewer first
β€œCan a trip be cancelled at any point during its lifecycle?”

No. A trip can be cancelled while in Requested or DriverAssigned states, but cancellation is strictly forbidden once InProgress (the passenger is already onboard).

β€œHow are driver matching algorithms selected and swapped?”

Driver matching follows the Strategy pattern: dispatchers can toggle between NearestDriverStrategy during normal hours and HighestRatedDriverStrategy for premium tiers or special events without altering trip logic.

β€œHow does dynamic pricing account for peak rush hours?”

Fare estimation uses a Strategy / Decorator: SurgeFareStrategy wraps NormalFareStrategy and applies a dynamic demand multiplier (e.g., 1.5x to 2.5x).

β€œHow are riders and drivers notified when state transitions occur?”

The Trip context acts as an Observer Subject: every state change publishes structured transition events to attached ITripObserver subscribers (push notifications, driver telemetry).

02

First, sketch the design yourself

Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.

  1. 1.

    Avoid sprawling switch(status) statements inside Trip methods; use the State pattern so each phase encapsulates its own allowed transitions and guard clauses.

  2. 2.

    Ensure driver availability invariants are maintained across all terminal states: whether a trip finishes via completeTrip() or aborts via cancelTrip(), the assigned driver must be freed back to the active fleet.

  3. 3.

    Decouple pricing and matching algorithms behind clean pure virtual interfaces so new algorithms (e.g. pooled rides, batched dispatch) plug in seamlessly.

03

How to think through this problem (5-step walkthrough)

Step 1 Β· Scope the 45-minute target & core boundary

In a 45-minute LLD interview, this problem evaluates state machine design, swappable dispatch algorithms, dynamic fare calculation, and real-time observer notifications. Scope the design to: modeling riders and drivers, matching drivers via interchangeable strategies (NearestDriverStrategy, HighestRatedDriverStrategy), calculating fares with normal and surge strategies, enforcing a strict trip lifecycle (Requested β†’ DriverAssigned β†’ InProgress β†’ Completed / Cancelled), and broadcasting status updates to observers. Geospatial indexing (H3/S2) and payment gateways can be highlighted as production extensions.

Step 2 Β· Extract candidate nouns (and reject false classes)

Not every noun in the prompt deserves its own class. Separate dumb data structs from stateful managers, and turn trivial nouns into fields or enums.

Trip
Stateful Class / Manager

Context class tracking rider ID, pickup/drop coordinates, fare strategy, assigned driver, attached observers, and delegating lifecycle actions to the active ITripState.

ITripState
Abstract Interface

Polymorphic State contract (RequestedState, DriverAssignedState, InProgressState, CompletedState, CancelledState) defining allowed lifecycle transitions and action guards.

IDriverMatchingStrategy
Abstract Interface

Strategy contract (NearestDriverStrategy, HighestRatedDriverStrategy) selecting the most suitable candidate from active available drivers.

IFareStrategy
Abstract Interface

Strategy contract calculating trip fares based on distance, duration, and demand surges (NormalFareStrategy, SurgeFareStrategy).

ITripObserver
Abstract Interface

Observer interface broadcasting lifecycle status changes (onTripEvent(tripId, event, msg)) to rider and driver push notification channels.

DistanceKilometers / SurgeMultiplier
Reject as Class β†’ Field / Method

Trap noun β€” DistanceKilometers and SurgeMultiplier are simple floating-point scalars (double), not separate class hierarchies. Making them classes creates unnecessary object wrapping boilerplate with zero domain behavior.

Step 3 Β· Draft the naive design & spot what breaks

A naive implementation models the trip lifecycle with a mutable enum (TripStatus) and sprawls switch(status) statements across every method in Trip. Guard logic like "cannot cancel when passenger is onboard" gets duplicated or forgotten. Adding new states (like DriverArrived or Disputed) requires editing every single method in Trip, directly violating the Open-Closed Principle and risking invalid state transitions.

Step 4 Β· Map change hotspots to design patterns
Trip lifecycle progression and legal action guards→ State Pattern (ITripState with concrete lifecycle state classes)

Scattered conditionals allow illegal actions, such as completing a trip before assigning a driver or cancelling while in transit.

Driver matching heuristics (Nearest vs Highest-Rated vs Batched)β†’ Strategy Pattern (IDriverMatchingStrategy)

Hardcoding dispatch logic in the trip context prevents switching dispatch algorithms during peak demand or premium tiers.

Dynamic fare pricing models (Standard vs Peak Surge)β†’ Strategy Pattern (IFareStrategy: NormalFareStrategy and SurgeFareStrategy)

Fixed fare calculation logic cannot adjust dynamically to weather surges, holiday pricing, or promotional discounts.

Broadcasting lifecycle milestones to mobile clients and telemetry→ Observer Pattern (ITripObserver)

Calling rider SMS and driver notification services directly from trip transition methods entangles domain logic with external communication protocols.

Step 5 Β· Lock down C++23 ownership, invariants & concurrency
  • βœ“

    In-progress non-cancellability: A trip in InProgressState cannot be cancelled under any circumstances (cancelTrip() returns false), protecting driver and passenger safety once transit begins.

  • βœ“

    Driver availability conservation: Whenever a trip reaches a terminal state (CompletedState or CancelledState), the assigned driver's availability flag must be released (isAvailable = true) so the driver rejoins the dispatchable fleet.

  • βœ“

    Notification atomicity: Every state transition executes through a central transitionTo(newState, message) helper that atomically updates the state pointer and broadcasts the event to all attached ITripObserver instances.

04

Entities & design patterns used

Brute2Best Pro Content

Unlock Full UML Diagram & C++23 Solution

The complete UML diagram, production-ready C++23 code, follow-up extensions, and design pitfall analysis are part of Brute2Best Pro. All 7 foundation chapters are 100% free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Systems Integration

Related C++ Systems & Algorithmic Foundations

Deep dive into underlying layers