JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionssystem-design
PrevNext

Learn the concept

Real-Time System Architecture

system-design
senior
real-time

Design a food delivery tracking page with real-time updates

real-time
websocket
maps
state-machine
food-delivery
tracking
mobile-optimization
Quick Answer

A food delivery tracking page uses WebSocket connections for real-time driver location updates on a live map, a state machine to model order lifecycle (placed through delivered), and Server-Sent Events or polling as fallbacks, with careful attention to mobile battery optimization, offline resilience, and animated map transitions.

Detailed Explanation

This is a classic frontend system design question frequently asked at companies like Zomato, Uber Eats, DoorDash, and Swiggy. The challenge combines real-time data handling, map rendering, state management, and mobile optimization into a single cohesive feature.

Requirements Gathering

Before diving into architecture, clarify requirements:

Functional:

  • Display current order status with a visual timeline (placed, confirmed, preparing, picked up, on the way, delivered)
  • Show driver's live location on an interactive map with animated movement
  • Display estimated time of arrival (ETA) that updates dynamically
  • Show restaurant details and driver information
  • Support multiple concurrent orders

Non-functional:

  • Location updates at 3-5 second intervals for smooth map animation
  • Graceful degradation when offline (show last known state)
  • Battery-efficient on mobile devices
  • Accessible to screen reader users
  • Handle edge cases: driver reassignment, order cancellation, restaurant closure

Real-Time Transport Layer

WebSocket is the right choice for driver location updates because the data flow is bidirectional (the client may send viewport bounds to optimize which updates it receives) and high-frequency (every 3-5 seconds).

Server-Sent Events (SSE) works well for order status changes because they are unidirectional and infrequent. SSE is simpler, auto-reconnects, and works through HTTP proxies without special configuration.

A hybrid approach is optimal:

  • WebSocket for driver GPS coordinates (high frequency, bidirectional)
  • SSE for order status transitions (low frequency, unidirectional)
  • Polling fallback when WebSocket is unavailable (corporate firewalls, older proxies) — poll every 10 seconds

Component Architecture

The page is composed of these key components:

  1. OrderTrackingPage — Container that manages WebSocket connections and order state
  2. StatusTimeline — Vertical stepper showing order progression through states
  3. LiveMap — Map with animated driver marker and route polyline
  4. ETADisplay — Dynamic countdown with time-range display
  5. OrderDetails — Restaurant name, items summary, driver info with photo and contact
  6. ConnectionStatus — Indicator showing real-time connection health

Order State Machine

Order status should be modeled as a finite state machine to enforce valid transitions and prevent impossible states. Using useReducer with a state machine pattern gives you predictable, testable state transitions:

  • placed -> confirmed (restaurant accepts)
  • confirmed -> preparing (kitchen starts)
  • preparing -> picked_up (driver collects)
  • picked_up -> on_the_way (driver en route)
  • on_the_way -> delivered (driver arrives)
  • Any state -> cancelled (cancellation)
  • picked_up -> driver_reassigned -> picked_up (driver swap)

Each state transition triggers UI updates: the timeline advances, ETA recalculates, and notifications fire.

Map Integration

Use Mapbox GL JS or Google Maps JavaScript API for the interactive map:

  • Marker animation — Do not teleport the driver marker. Interpolate between the old and new GPS coordinates using requestAnimationFrame over 3 seconds (matching the update interval) for smooth visual movement.
  • Route polyline — Show the planned route from restaurant to delivery address. Update the remaining route as the driver progresses.
  • Viewport management — Auto-fit the map bounds to include both the driver and delivery address, with padding. Stop auto-fitting if the user manually pans or zooms.
  • Clustering — Not needed for a single delivery, but relevant if showing multiple active orders on one map.

Battery and Data Optimization

Mobile users may track their order for 20-40 minutes. Aggressive real-time updates drain battery:

  • Visibility API — When the tab or app is backgrounded (document.hidden === true), reduce WebSocket update frequency to every 30 seconds or pause entirely. Resume full frequency when the user returns.
  • Adaptive update frequency — When the driver is far away (ETA > 15 min), update every 10 seconds. When close (ETA < 5 min), update every 2-3 seconds.
  • Batch DOM updates — Buffer incoming location updates and apply them in a single requestAnimationFrame callback rather than triggering re-renders for each message.

Offline Handling

  • Detect offline status with navigator.onLine and the online/offline events.
  • When offline, show the last known driver position and order status with a clear banner: "You're offline. Showing last known status."
  • Queue any user actions (e.g., contacting driver) and replay them when connectivity returns.
  • Use a Service Worker to cache the map tiles and application shell for basic offline functionality.

Error States and Edge Cases

  • Driver reassigned — Show a transition animation, update driver info, and briefly explain why.
  • Order cancelled — Immediately update the status timeline, show cancellation reason, and provide refund information.
  • Restaurant closed — Show a clear error state with next steps (refund, alternative restaurants).
  • GPS signal lost — Show the driver's last known position with a "Location unavailable" indicator. Fall back to ETA-based progress.
  • WebSocket disconnect — Automatically reconnect with exponential backoff. Show a subtle connection status indicator. Fall back to polling during reconnection.

Accessibility

  • Use an ARIA live region to announce order status changes to screen readers.
  • Provide a text-based alternative to the map showing street address and ETA.
  • Ensure the status timeline is navigable with keyboard.
  • Use sufficient color contrast for status indicators (not just color — add icons and labels).

Code Examples

Order state machine with useReducerTypeScript
// Types for the order state machine
type OrderStatus =
  | 'placed'
  | 'confirmed'
  | 'preparing'
  | 'picked_up'
  | 'on_the_way'
  | 'delivered'
  | 'cancelled';

interface OrderState {
  status: OrderStatus;
  eta: number | null; // minutes
  driverLocation: { lat: number; lng: number } | null;
  driver: { name: string; photo: string; phone: string } | null;
  statusHistory: Array<{ status: OrderStatus; timestamp: number }>;
  error: string | null;
}

type OrderAction =
  | { type: 'STATUS_UPDATE'; status: OrderStatus; eta?: number }
  | { type: 'LOCATION_UPDATE'; lat: number; lng: number }
  | { type: 'DRIVER_ASSIGNED'; driver: OrderState['driver'] }
  | { type: 'DRIVER_REASSIGNED'; driver: OrderState['driver']; reason: string }
  | { type: 'ETA_UPDATE'; eta: number }
  | { type: 'CANCELLED'; reason: string }
  | { type: 'ERROR'; message: string };

// Valid transitions — enforced at the reducer level
const VALID_TRANSITIONS: Record<OrderStatus, OrderStatus[]> = {
  placed: ['confirmed', 'cancelled'],
  confirmed: ['preparing', 'cancelled'],
  preparing: ['picked_up', 'cancelled'],
  picked_up: ['on_the_way', 'cancelled'],
  on_the_way: ['delivered', 'cancelled'],
  delivered: [],
  cancelled: [],
};

function orderReducer(state: OrderState, action: OrderAction): OrderState {
  switch (action.type) {
    case 'STATUS_UPDATE': {
      const allowed = VALID_TRANSITIONS[state.status];
      if (!allowed.includes(action.status)) {
        console.warn(`Invalid transition: ${state.status} → ${action.status}`);
        return state;
      }
      return {
        ...state,
        status: action.status,
        eta: action.eta ?? state.eta,
        statusHistory: [
          ...state.statusHistory,
          { status: action.status, timestamp: Date.now() },
        ],
        error: null,
      };
    }
    case 'LOCATION_UPDATE':
      return {
        ...state,
        driverLocation: { lat: action.lat, lng: action.lng },
      };
    case 'DRIVER_ASSIGNED':
      return { ...state, driver: action.driver };
    case 'DRIVER_REASSIGNED':
      return {
        ...state,
        driver: action.driver,
        error: `Driver reassigned: ${action.reason}`,
      };
    case 'ETA_UPDATE':
      return { ...state, eta: action.eta };
    case 'CANCELLED':
      return {
        ...state,
        status: 'cancelled',
        error: action.reason,
        statusHistory: [
          ...state.statusHistory,
          { status: 'cancelled', timestamp: Date.now() },
        ],
      };
    case 'ERROR':
      return { ...state, error: action.message };
    default:
      return state;
  }
}

// Usage in component
function useOrderTracking(orderId: string) {
  const [state, dispatch] = useReducer(orderReducer, {
    status: 'placed',
    eta: null,
    driverLocation: null,
    driver: null,
    statusHistory: [{ status: 'placed', timestamp: Date.now() }],
    error: null,
  });

  return { state, dispatch };
}

Real-World Applications

Use Cases

Food Delivery Order Tracking

Showing customers a real-time map of their driver's location with animated movement, order status timeline, and dynamic ETA as the driver navigates through traffic

Ride-Sharing Driver Tracking

Displaying the assigned driver's approach on a live map with ETA countdown after booking a ride, with smooth marker animation between GPS updates

Package Delivery Tracking

Showing last-mile delivery progress on a map when the package is out for delivery, with status updates at each checkpoint

Mini Projects

Order Tracking Simulator

advanced

Build a food delivery tracking page with a mock WebSocket server that simulates a driver moving along a predefined route, with order status transitions and ETA updates

Real-Time Map with Animated Markers

intermediate

Create a map component that receives GPS coordinates via WebSocket and smoothly animates a marker between updates using requestAnimationFrame interpolation

Industry Examples

Uber Eats

Real-time order tracking with live driver location, animated map, and granular order status updates from restaurant to doorstep

DoorDash

Live order tracking with ETA predictions powered by ML models that account for traffic, restaurant prep time, and driver behavior

Zomato

Real-time delivery tracking with driver location, animated route progress, and status timeline showing each stage of the delivery

Resources

MDN — WebSocket API

docs

Mapbox GL JS Documentation

docs

MDN — Page Visibility API

docs

MDN — Server-Sent Events

docs

Related Questions

Design a real-time notification system for a web application

mid
real-time

How do you approach a frontend system design interview?

junior
fundamentals

What are the trade-offs between client-side and server-side rendering?

junior
rendering
Previous
How would you architect a micro-frontend system?
Next
Design an offline-first web application with sync capabilities
PrevNext