Design a Support Agent Dispatcher with Interruption Handling
Data Structure DesignModel answerLast updated
Design an in-memory dispatch engine that pairs queued support tickets with available agents, extended to handle mid-task agent breaks and fair ticket re-queuing.
Design an in-memory event-driven dispatch engine for a customer service team. The system routes incoming customer requests (tickets) to human agents, processes task completions, and manages agent availability state transitions.
Operational Requirements
Core Event Loop & Matching Engine
- Queues & Fairness:
- Waiting tickets must be matched in strict FIFO order (earliest creation timestamp first).
- Available agents must be assigned in FIFO order (earliest agent availability timestamp first).
- Deterministic Processing:
- All events are processed sequentially in a single-threaded execution context.
- Every event state change (e.g., ticket creation, agent sign-in, task completion) must immediately trigger an assignment check to match available tickets with available agents.
Event Handling Requirements
agent_sign_in(agent_id, timestamp): Registers an agent as free.agent_sign_out(agent_id, timestamp): Removes an idle agent. If the agent is currently handling a ticket, reject or defer sign-out until idle.customer_request_arrives(ticket_id, timestamp): Enqueues a new ticket.task_completed(agent_id, ticket_id, timestamp): Marks the current assignment finished and sets the agent to available. Stale completion events (e.g., for a ticket no longer assigned to this agent) must be ignored safely.agent_break_requested(agent_id, timestamp): Immediately interrupts the agent mid-task. The agent transitions to aBREAKstate. The ticket being worked on must be re-queued immediately, preserving its original arrival timestamp so it retains priority over newer tickets.agent_break_ended(agent_id, timestamp): Transitions the agent fromBREAKback to available.
Clarifying Scope & Constraints
- Assume all state fits in memory.
- State transitions must handle invalid or stale events gracefully (e.g., duplicate sign-ins, operations on non-existent entities).
- Be prepared to discuss the time complexity of each state update operation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
A robust in-memory dispatcher separates domain state models (Entities and State Machines) from the matching policy logic (Engine).
+-----------------------+
| Dispatch Engine |
+-----------+-----------+
|
+-------------------+-------------------+
| |
+------v------+ +------v------+
| Ticket Queue| | Agent Queue |
| (FIFO) | | (FIFO) |
+-------------+ +-------------+
Data Structures & Complexity
To achieve optimal time complexity:
waiting_tickets: Doubly LinkedList /collections.dequemaintaining ticket objects in strict order of arrival. Re-queued tickets interrupted mid-request retain their original arrival time and can be pushed back to the head of the queue in $O(1)$ time.available_agents:collections.dequeorOrderedDictstoring free agent IDs in order of when they became idle.- State Lookup Maps:
agents:agent_id -> Agentobject ($O(1)$ lookup).tickets:ticket_id -> Ticketobject ($O(1)$ lookup).active_assignments:ticket_id -> agent_idmapping ($O(1)$ validation for stale events).
| Operation | Time Complexity | Notes |
|---|---|---|
agent_sign_in | $O(1)$ | Appends to free agents queue |
customer_request_arrives | $O(1)$ | Appends to waiting tickets queue |
task_completed | $O(1)$ | Validates active assignment map, frees agent |
agent_break_requested | $O(1)$ | Interrupts agent, prepends ticket to queue |
agent_break_ended | $O(1)$ | Re-adds agent to free agents queue |
dispatch_matching | $O(1)$ per assignment | Pops from both queues and matches |
Python Implementation
from collections import deque
from enum import Enum
from typing import Optional, Dict
class AgentState(Enum):
OFFLINE = 1
AVAILABLE = 2
BUSY = 3
ON_BREAK = 4
class TicketState(Enum):
QUEUED = 1
IN_PROGRESS = 2
COMPLETED = 3
class Ticket:
def __init__(self, ticket_id: str, arrival_time: float):
self.ticket_id = ticket_id
self.arrival_time = arrival_time
self.state = TicketState.QUEUED
self.assigned_agent_id: Optional[str] = None
self.interrupt_count = 0
class Agent:
def __init__(self, agent_id: str):
self.agent_id = agent_id
self.state = AgentState.OFFLINE
self.current_ticket_id: Optional[str] = None
class Dispatcher:
def __init__(self):
self.agents: Dict[str, Agent] = {}
self.tickets: Dict[str, Ticket] = {}
# Queues for fair dispatch
self.waiting_tickets: deque = deque() # stores ticket_ids
self.available_agents: deque = deque() # stores agent_ids
# Active assignment mapping for validation
self.active_assignments: Dict[str, str] = {} # ticket_id -> agent_id
def _dispatch(self):
"""Attempts to match waiting tickets with available agents."""
while self.waiting_tickets and self.available_agents:
agent_id = self.available_agents.popleft()
agent = self.agents.get(agent_id)
# Skip agent if state changed unexpectedly
if not agent or agent.state != AgentState.AVAILABLE:
continue
ticket_id = self.waiting_tickets.popleft()
ticket = self.tickets.get(ticket_id)
# Skip ticket if state changed unexpectedly
if not ticket or ticket.state != TicketState.QUEUED:
# Put agent back at the front if ticket was invalid
self.available_agents.appendleft(agent_id)
continue
# Execute Assignment
agent.state = AgentState.BUSY
agent.current_ticket_id = ticket_id
ticket.state = TicketState.IN_PROGRESS
ticket.assigned_agent_id = agent_id
self.active_assignments[ticket_id] = agent_id
def agent_sign_in(self, agent_id: str, timestamp: float):
if agent_id not in self.agents:
self.agents[agent_id] = Agent(agent_id)
agent = self.agents[agent_id]
if agent.state in (AgentState.BUSY, AgentState.AVAILABLE):
return # Already active/signed in
agent.state = AgentState.AVAILABLE
self.available_agents.append(agent_id)
self._dispatch()
def customer_request_arrives(self, ticket_id: str, timestamp: float):
if ticket_id in self.tickets:
return # Duplicate event ignored
ticket = Ticket(ticket_id, timestamp)
self.tickets[ticket_id] = ticket
self.waiting_tickets.append(ticket_id)
self._dispatch()
def task_completed(self, agent_id: str, ticket_id: str, timestamp: float):
# Validate event freshness & accuracy
if self.active_assignments.get(ticket_id) != agent_id:
# Stale or invalid completion event; ignore safely
return
agent = self.agents[agent_id]
ticket = self.tickets[ticket_id]
# Update Ticket State
ticket.state = TicketState.COMPLETED
ticket.assigned_agent_id = None
del self.active_assignments[ticket_id]
# Update Agent State
agent.current_ticket_id = None
agent.state = AgentState.AVAILABLE
self.available_agents.append(agent_id)
self._dispatch()
def agent_break_requested(self, agent_id: str, timestamp: float):
agent = self.agents.get(agent_id)
if not agent or agent.state == AgentState.ON_BREAK:
return
if agent.state == AgentState.AVAILABLE:
# Remove from idle queue
self.available_agents.remove(agent_id)
agent.state = AgentState.ON_BREAK
elif agent.state == AgentState.BUSY:
ticket_id = agent.current_ticket_id
ticket = self.tickets[ticket_id]
# Clear Assignment State
del self.active_assignments[ticket_id]
agent.current_ticket_id = None
agent.state = AgentState.ON_BREAK
# Re-queue ticket with high priority (front of FIFO queue)
ticket.state = TicketState.QUEUED
ticket.assigned_agent_id = None
ticket.interrupt_count += 1
self.waiting_tickets.appendleft(ticket_id)
self._dispatch()
def agent_break_ended(self, agent_id: str, timestamp: float):
agent = self.agents.get(agent_id)
if not agent or agent.state != AgentState.ON_BREAK:
return
agent.state = AgentState.AVAILABLE
self.available_agents.append(agent_id)
self._dispatch()
Key Edge Cases & Design Trade-offs
-
Stale Completion Events:
- Scenario: Agent A gets interrupted while working on Ticket T1. Ticket T1 is re-assigned to Agent B. Later, a delayed
task_completed(Agent A, T1)event arrives. - Handling: Handled via explicit
active_assignmentsdictionary verification (active_assignments.get(ticket_id) == agent_id). If the caller does not match the active record, the event is silently dropped.
- Scenario: Agent A gets interrupted while working on Ticket T1. Ticket T1 is re-assigned to Agent B. Later, a delayed
-
Re-queue Priority (Fairness):
- Strategy: Placing interrupted tickets at the front of the FIFO queue (
appendleft) guarantees that customers who suffered an agent interruption do not lose their place relative to new arrivals.
- Strategy: Placing interrupted tickets at the front of the FIFO queue (
-
Break During Idle State:
- Strategy: If an agent goes on break while available, removing them from
available_agentsin $O(N)$ with a standard deque can be optimized to $O(1)$ by using a doubly-linked list combined with a hash map of node pointers if agent scale is very high.
- Strategy: If an agent goes on break while available, removing them from