Designing an Online Queue Management System

Difficulty: Intermediate Patterns: Strategy, Observer, State Asked at: TCS, PhonePe, Banks, Government portals


Functional Requirements

  1. Generate tokens - customers receive a numbered token with estimated wait time
  2. Multiple service counters - different counters handle different service types
  3. Priority queue - VIP/senior citizen tokens served before regular tokens
    💡 A priority queue hands back the most important item first instead of the oldest one, so a VIP token that just arrived can jump ahead of a regular token that has been waiting.
  4. Estimated wait time - calculate based on average service time and queue length
  5. Call next - counter operator calls the next token in queue
  6. Counter assignment - strategy to assign tokens to counters (shortest queue, round-robin)
    💡 Round-robin = walk the counters in a fixed cycle, one token each, then start over; shortest-queue instead picks whichever counter is least loaded. They are the same two algorithms a load balancer chooses between.

Non-Functional Requirements

  1. Thread-safety - concurrent token generation and counter operations must be safe
    💡 Thread-safety = the design stays correct when several threads run through it at once. Here two kiosks issuing tokens at the same instant must not both get token #42.
  2. Fairness - within same priority, tokens are served in first in first out (FIFO) order
    💡 First in first out (FIFO) = whoever queued earliest is served earliest, like a physical line. It only applies within one priority band here, so SENIOR tokens still go ahead of REGULAR ones.
  3. Real-time updates - observers notified on token status changes for display boards
    💡 “Real-time” here means the system pushes changes out as they happen instead of the display boards asking every few seconds. Over a network that push is a WebSocket or server-sent events connection.

Core Entities

Entity Description
Token Number, customer name, priority, status, service type
TokenPriority Enum: REGULAR, SENIOR, VIP
TokenStatus Enum: WAITING, SERVING, COMPLETED, CANCELLED
ServiceType Enum: GENERAL, DEPOSIT, WITHDRAWAL, LOAN, ACCOUNT_OPENING
Counter ID, service types it handles, current token being served
CounterStatus Enum: OPEN, BUSY, CLOSED
AssignmentStrategy Interface for token-to-counter routing
QueueManager Central system managing tokens, counters, and assignment
QueueObserver Notified on token called, completed, queue updates

💡 An observer is an object that registers itself with the system and gets called back whenever something happens, instead of polling for changes. The display board, an SMS sender and an analytics sink are all just observers, and QueueManager knows none of them by name. Learn more →


Class Diagram

classDiagram
    class TokenPriority {
        <<enumeration>>
        REGULAR
        SENIOR
        VIP
    }

    class TokenStatus {
        <<enumeration>>
        WAITING
        SERVING
        COMPLETED
        CANCELLED
    }

    class ServiceType {
        <<enumeration>>
        GENERAL
        DEPOSIT
        WITHDRAWAL
        LOAN
        ACCOUNT_OPENING
    }

    class CounterStatus {
        <<enumeration>>
        OPEN
        BUSY
        CLOSED
    }

    class Token {
        -int number
        -String customerName
        -TokenPriority priority
        -TokenStatus status
        -ServiceType serviceType
        -long createdAt
        -long servedAt
        -long completedAt
        +getWaitTimeMs() long
    }

    class Counter {
        -int id
        -String name
        -Set~ServiceType~ serviceTypes
        -CounterStatus status
        -Token currentToken
        -int tokensServed
        -double avgServiceTimeMs
        +canServe(ServiceType) boolean
        +assignToken(Token)
        +completeService()
    }

    class AssignmentStrategy {
        <<interface>>
        +assignCounter(Token, List~Counter~) Counter
        +getName() String
    }

    class ShortestQueueStrategy {
        +assignCounter(Token, List~Counter~) Counter
    }

    class RoundRobinStrategy {
        -int lastAssignedIndex
        +assignCounter(Token, List~Counter~) Counter
    }

    class QueueObserver {
        <<interface>>
        +onTokenGenerated(Token token)
        +onTokenCalled(Token token, Counter counter)
        +onTokenCompleted(Token token, Counter counter)
        +onTokenCancelled(Token token)
        +onQueueUpdated(int queueSize)
    }

    class QueueManager {
        -PriorityQueue~Token~ waitingQueue
        -Map~Integer, Counter~ counters
        -Map~Integer, Token~ tokenRegistry
        -AssignmentStrategy strategy
        -List~QueueObserver~ observers
        -AtomicInteger tokenCounter
        +generateToken(String name, TokenPriority, ServiceType) Token
        +callNext(int counterId) Token
        +completeService(int counterId)
        +cancelToken(int tokenNumber)
        +getEstimatedWaitTime(Token) long
        +getQueueStatus() String
    }

    QueueManager --> Token
    QueueManager --> Counter
    QueueManager --> AssignmentStrategy
    QueueManager --> QueueObserver
    Token --> TokenPriority
    Token --> TokenStatus
    Token --> ServiceType
    Counter --> CounterStatus
    Counter --> ServiceType
    AssignmentStrategy <|.. ShortestQueueStrategy
    AssignmentStrategy <|.. RoundRobinStrategy

💡 Reading the arrows: a dashed arrow with a hollow head (<|..) means “implements this interface”, so ShortestQueueStrategy is one interchangeable assignment policy. A plain arrow (-->) just means “holds a reference to”. Learn more →

Key classes:

  • QueueManager — the only class that mutates shared state. It owns the waiting queue, the counter map, the token registry, the assignment strategy and the observer list, and every operation (generate, call next, complete, cancel) goes through it.
  • Token — one customer’s claim on service: number, name, priority, service type, current status and the timestamps used to compute waiting and service time.
  • Counter — one service desk. It knows which service types it is allowed to handle, which token it is currently serving, and its own running average service time, which is what makes wait estimates improve over the day.
  • AssignmentStrategy — the swap point for “which counter should take this token”. ShortestQueueStrategy and RoundRobinStrategy are the two supplied policies.
  • QueueObserver — the notification boundary. Implementations react to token events (generated, called, completed, cancelled) without QueueManager knowing what a display board or an SMS gateway is.
  • The four enums (TokenPriority, TokenStatus, ServiceType, CounterStatus) — fixed sets of legal values. Using an enum instead of a string means an illegal status simply cannot be constructed.

Design Patterns

Pattern Where Why
Strategy AssignmentStrategy with ShortestQueue/RoundRobin Swap counter assignment logic without changing QueueManager
Observer QueueObserver notified on token events Display boards, SMS alerts, analytics decoupled from core
State TokenStatus governs valid transitions Token lifecycle enforced (WAITING→SERVING→COMPLETED)

💡 Strategy pattern = put each algorithm behind one shared interface so the caller can swap it at runtime. QueueManager calls strategy.assignCounter(...) and never contains an if (policy == ROUND_ROBIN) branch.

💡 State pattern = let the object’s current state decide which operations are legal. A token in COMPLETED cannot be called again, so the illegal move is rejected by the status check rather than by a comment telling you not to do it.


Data Structures

Component Structure Why
Waiting queue PriorityQueue<Token> ordered by priority then arrival time VIP/senior served first; within same priority, FIFO
Token registry ConcurrentHashMap<Integer, Token> O(1) lookup by token number
Counters ConcurrentHashMap<Integer, Counter> O(1) counter lookup
Per-counter queue Optional Queue<Token> per counter Used by shortest-queue strategy
Observers CopyOnWriteArrayList<QueueObserver> Thread-safe notification

💡 PriorityQueue is a heap, not a sorted list: it keeps the single smallest element cheap to find and reorders lazily, so push and pop cost O(log n) while “who is next” is O(1). The comparator here orders by priority band first, then arrival time.