Machine Coding Problem

Helpdesk Ticketing System

macoAllproductivitystate-machineassignment-strategysla-escalation

Requirements & System Scope

Functional Scope (In-Scope)

  • Ticket Intake: A customer opens a ticket with a subject, a priority (LOW, NORMAL, HIGH or URGENT) and the skill needed to solve it, such as billing or network.
  • Lifecycle State Machine: A ticket moves through OPEN, ASSIGNED, IN_PROGRESS, WAITING_ON_CUSTOMER, RESOLVED, CLOSED and REOPENED. An explicit table lists every legal move, and any other move is rejected with IllegalTransitionException while the ticket stays untouched.
  • Agents with Skills and Capacity: Each agent has a set of skills and a maximum number of concurrent tickets. A ticket holds one slot from assignment until it is resolved or returned to the queue.
  • Pluggable Assignment: Round robin, least loaded and skill based strategies sit behind one AssignmentStrategy interface and can be swapped at runtime. Tickets that nobody could take wait in a queue that drains by priority first and age second.
  • SLA Deadlines: Each priority has a first-response window and a resolution window, measured on an injected clock. A deadline is at risk once 80 percent of its window has elapsed and breached when the window ends.
  • Escalation: An observer reacts to at-risk and breach events by raising the ticket priority or handing the ticket to a different agent.
  • Comments and Audit Trail: Every ticket keeps its comments, and every status change, assignment and escalation is appended to an audit trail with a timestamp and an actor.
  • Concurrency Safety: No ticket is assigned twice and no agent ever exceeds their capacity, even when many assigners and claimers run at once.

Explicit Boundaries (Out-of-Scope)

  • No Persistence: Tickets, agents and the SLA heap live in memory so the focus stays on the object model and the locking.
  • No Business Hours and No SLA Pause: Windows are plain durations and the resolution clock keeps running while a ticket waits on the customer. Both are discussed as extensions.
  • No Intake Channels or Access Control: Email ingestion, chat widgets and role checks are left out, and the actor string in the audit trail is only a label.
  • No Background Scheduler: The driver calls checkSla() directly. A production system runs the same call from a periodic job or a delayed queue.

Class Diagram & Entity Relationships

The helpdesk is a facade over two engines. One engine assigns tickets to agents, and the other tracks deadlines and escalates. The Ticket sits between them as the only object that owns a status. Every box mirrors a class in the Java blueprint, and the TypeScript and Python blueprints declare the same classes.

Loading...
  • Facade spine: Helpdesk is the only class a caller needs. It creates tickets, arms their SLA events, owns the Dispatcher and the SlaTracker, and registers EscalationObserver as the tracker’s listener.
  • Table instead of state classes: TicketStateMachine is a lookup table of legal moves. Every state behaves the same except for a few side effects, so one table is shorter and easier to audit than seven state classes.
  • Two seams: AssignmentStrategy decides who gets a ticket and SlaListener decides what happens when a deadline is at risk or missed. New policies plug into either one without touching Helpdesk.

Design Patterns & SOLID Principles

  • Strategy Pattern (Assignment):AssignmentStrategy has three implementations. RoundRobinStrategy rotates through the roster, LeastLoadedStrategy takes the agent with the fewest active tickets, and SkillBasedStrategy filters to agents who have the ticket’s skill and then asks an inner strategy to choose. Because the skill filter wraps another strategy, skill matching and load balancing combine without a new class for every pairing, and Dispatcher.setStrategy() swaps the policy at runtime.
  • State Pattern (Table-Driven Ticket Lifecycle):TicketStateMachine keeps the legal-transition table and Ticket.transition() consults it before every status change. This is the State pattern in its lightest form. The behavior tied to a transition is small, namely releasing the agent slot when a ticket returns to the queue or is resolved, and the facade cancelling or re-arming SLA events on resolve and reopen, so a table says it more plainly than seven state classes would.
  • Observer Pattern (SLA Events):SlaTracker is the subject and SlaListener is the observer interface. EscalationObserver is the one registered listener, and a second listener such as a pager or a dashboard could be added without changing the tracker.
  • Facade Pattern (Helpdesk):Helpdesk hides the dispatcher, the tracker and the ticket map behind a handful of calls, and it keeps the order of multi-step operations in one place, such as resolving a ticket and then cancelling its SLA events.
  • Dependency Injection (Clock): Every class that needs the time takes a Clock. The demo injects ManualClock and advances it by hand, so SLA behavior is tested without sleeping and results are repeatable.
  • Interface Segregation Principle (ISP) (Narrow Contracts): Each collaborator depends on one small contract. Dispatcher asks an AssignmentStrategy only to pick an agent, SlaTracker notifies a SlaListener only through onSlaEvent, and Clock exposes only now. EscalationObserver implements SlaListener alone, so it is never forced to provide assignment or timing methods it does not use.

Algorithm: Assignment, SLA Deadlines and Tie-Breaking

Baseline: scan the agents, scan the tickets

The simplest assignment walks the whole roster for every ticket, skips agents without capacity or skill, and keeps the best one. That costs O(A) per pick for A agents, and a pick that loses a race to another assigner is retried against the remaining agents. The simplest SLA check does the same over tickets, scanning every open ticket on every tick and comparing its deadlines with the clock. That costs O(T) per tick for T open tickets even when nothing is due. The blueprint keeps the scan for assignment because a support team has tens of agents, but it does not scan for deadlines.

Optimization 1: deadlines in a min-heap

Creating a ticket pushes four SlaEvent entries into one min-heap ordered by time, which are first response at risk, first response breached, resolution at risk and resolution breached. A tick only needs the next deadline, so it peeks the head, pops while the head is due, and stops at the first event in the future. Each push or pop is O(log n) for n events, so a tick that finds k due events costs O(k log n) plus the listener work, and a tick that finds none costs O(1).

Deadlines are never moved. Escalation changes the priority and the owner but not the promise already made to the customer, so a heap entry is only ever cancelled, never updated. Cancelling sets a flag on the event and the entry is skipped when it eventually reaches the head, which is called lazy deletion. A resolved ticket therefore leaves its remaining events in the heap, flagged as cancelled, until their original times pass.

Optimization 2: indexed agents instead of a scan

When the roster grows into the hundreds, keep one min-heap of agents per skill keyed by active count and then agent id. A pick reads the head of the ticket’s skill heap in O(log A), reserves a slot, and pushes a refreshed entry, and stale entries whose load has changed are discarded when they reach the head. An agent who has several skills appears in several heaps, so a reserve must refresh each of them. Per-skill round robin queues are cheaper still, at the cost of ignoring load. The tryReserve() check stays exactly as it is, because an index only suggests an agent.

Tie-breaking rules

  • Queued tickets: highest priority first, then the oldest createdAt, then the lowest ticket number. A reopened ticket keeps its original age, so it does not go to the back of the line.
  • Least loaded agent: fewest active tickets, then the lowest agent id, so the choice is deterministic when loads are equal.
  • Round robin: the rotation resumes from the slot after the last agent picked, and agents without capacity are skipped over.
  • Equal deadlines: events with the same timestamp fire in arming order, using a sequence number as the second sort key. Without it, a millisecond clock would make ties common and the heap order would be arbitrary.

Complexity and the aha

  • Assign a ticket: O(A) with the scan, O(log A) with per-skill heaps.
  • Arm a ticket’s SLA: four heap pushes, O(log n).
  • SLA tick: O(k log n) for k due events.
  • Drain the queue: O(Q log Q) to sort Q queued tickets, plus one assignment each.

The aha is that the SLA question is not β€œwhich tickets are late” but β€œwhat is the next deadline”, and a heap answers that by looking at one element. Because escalation never rewrites a deadline, the heap needs only push, pop and cancel, which keeps it simple.

Core Execution Workflows

1. Create and Assign a Ticket

  1. The caller invokes createTicket(customer, subject, priority, skill). The ticket starts as OPEN with an audit entry, and SlaTracker arms four events from the current time using the priority’s windows.
  2. The caller invokes assign(ticketId), and Dispatcher copies the roster into a candidate pool.
  3. The active strategy picks an agent from the pool. If it returns nothing, assign returns NO_AGENT and the ticket stays queued.
  4. The dispatcher calls Ticket.assignTo(agent, actor):
    1. Under the ticket’s lock, check the table. A ticket that is not OPEN or REOPENED returns NOT_ASSIGNABLE before any capacity is touched.
    2. Call agent.tryReserve(). When the agent filled up in the meantime, return AGENT_FULL, and the dispatcher removes that agent from its pool and picks again.
    3. Otherwise record the owner, move the status to ASSIGNED, append the audit entry and return ASSIGNED.

2. Work a Ticket Through Its Lifecycle

  1. An agent or the customer calls transition(ticketId, to, actor). The ticket looks up the move in TicketStateMachine. An illegal move throws IllegalTransitionException that lists the legal next states, and nothing changes.
  2. Moving to OPEN or RESOLVED releases the agent’s slot and clears the owner. Moves between ASSIGNED, IN_PROGRESS and WAITING_ON_CUSTOMER keep the slot.
  3. The facade then reacts to the new status. RESOLVED cancels every pending SLA event, and REOPENED arms a fresh resolution deadline from the current time.
  4. The first comment written by an agent sets firstRespondedAt and cancels any first-response events that are still pending. Later comments only extend the trail.
  5. A CLOSED ticket has no outgoing moves, so a reopen attempt is rejected.

3. SLA Tick and Escalation

  1. A periodic caller invokes checkSla(), which reads the clock once.
  2. Under the tracker’s lock, tick() pops every event whose time is at or before now. Cancelled events are dropped silently and the rest are collected.
  3. After releasing the lock, each collected event goes to every listener. EscalationObserver first asks ticket.isSlaOpen(type), because the ticket may have been resolved or answered since the event was popped, and ignores stale events.
  4. An at-risk event for either deadline raises the priority one level, up to URGENT.
  5. A first-response breach writes an audit note and asks the dispatcher to reassign the ticket to a different agent. When no other agent can take it, the priority is raised to URGENT instead.
  6. A resolution breach writes an audit note and raises the priority to URGENT.

4. Draining the Queue

  1. assignQueued() collects every OPEN or REOPENED ticket and sorts it by priority, then age, then ticket number.
  2. Each ticket goes through the same assignment loop as workflow 1. A ticket with no available agent stays queued and does not block the tickets behind it, since another ticket may need a different skill.

Failure Paths

  1. An illegal transition throws and leaves status, owner, slot count and audit trail unchanged.
  2. A lost race for the last slot returns AGENT_FULL internally, and the dispatcher retries with the next candidate until one wins or the pool is empty.
  3. A claim on an already assigned ticket returns NOT_ASSIGNABLE and the claimer’s capacity is untouched.
  4. An SLA event that fires after the ticket was resolved or answered is ignored and writes nothing.

Concurrency & Thread Safety Strategy

Shared state and the races on it

Four pieces of state are shared. Each agent has an active counter, each ticket has a status, an owner and a priority, the tracker has one heap with its cancel index, and the round robin strategy has a cursor. Several races follow from that.

  • Two assigners, one agent: Both pick the same agent while that agent has one free slot. Both read β€œhas capacity” and both increment, so the agent ends up over capacity.
  • Two agents, one ticket: Two agents claim the same OPEN ticket. Both pass the status check, so the ticket gets two owners and one agent leaks a slot.
  • Escalation versus resolution: The observer reassigns a ticket at the moment its agent resolves it, which could hand a resolved ticket to a new agent.
  • Two ticks: Two threads call checkSla() together and both fire the same breach, doubling the escalation.
  • A stale event: A deadline event is popped, then the agent replies before the observer runs, so the observer would escalate a ticket that no longer needs it.

The guards and where they sit

Agent.tryReserve() reads the counter and increments it inside one monitor in Java, one threading.Lock in Python, and one synchronous method in TypeScript. That removes the first race, and the loser gets AGENT_FULL and re-picks from the rest of its pool. Ticket.assignTo() runs the table check, the reserve and the owner update under the ticket’s monitor (an RLock in Python), and it checks the table before reserving, so the loser of a claim returns NOT_ASSIGNABLE without ever touching an agent. Reassignment and every status change take the same ticket monitor, so the observer and the agent serialize, and reassignTo() refuses a ticket that is no longer ASSIGNED or IN_PROGRESS.

SlaTracker guards its heap and cancel index with its own monitor. Popping an event under that monitor is the claim on it, so two concurrent ticks never receive the same event. The tracker collects due events, releases its lock, and only then calls listeners, because listeners take ticket and agent monitors. As a last guard, isSlaOpen() re-checks the ticket under its own monitor, which neutralizes a stale event. The remaining shared pieces use ConcurrentHashMap, AtomicInteger and a CopyOnWriteArrayList roster in Java, a small lock around the ticket map and counter in Python, and nothing extra in TypeScript, where the single-threaded event loop already runs each method to completion.

Lock order and deadlock avoidance

The rule is a ticket monitor first and then at most one agent monitor at a time. Agent never calls back into Ticket, so no thread can hold an agent monitor while waiting for a ticket monitor. Reassignment takes the new agent’s monitor for the reserve and releases it, and then takes the old agent’s monitor for the release, never both together. Two tickets swapping agents in opposite directions therefore cannot deadlock, because each thread holds only its own ticket and one agent at any instant. The tracker monitor is never held while a ticket or agent monitor is requested, and the round robin monitor only ever wraps agent reads.

What the blueprint does not guard

  • Strategy snapshots are advisory: hasCapacity() and getActive() can be stale by the time a pick is used, which is why the real check is tryReserve() and why a failed reserve simply retries.
  • Facade steps are separate: Helpdesk.transition() changes the ticket and then cancels its SLA events as two steps. A tick can slip between them, and only the isSlaOpen() re-check keeps that harmless.
  • Queue draining works on a snapshot: A ticket can change state between listing and assigning, and it is simply reported as not assignable.
  • One process only: Monitors protect threads in one JVM. Two helpdesk nodes would each have their own heap, their own counters and their own idea of capacity.

Hardening for production

A database makes both checks conditional writes. A ticket row carries a version column and the assignment becomes UPDATE tickets SET status = 'ASSIGNED', assignee = :agent, version = version + 1 WHERE id = :id AND version = :seen AND status IN ('OPEN', 'REOPENED'). Zero updated rows means another writer won, so the caller reloads and retries or gives up, which is optimistic locking. Capacity is UPDATE agents SET active = active + 1 WHERE id = :agent AND active < capacity, which is the same compare-and-increment as tryReserve(), and both statements run in one transaction so a lost ticket update rolls the slot back. SLA events become rows indexed by due time, and workers claim them with SELECT ... FOR UPDATE SKIP LOCKED so several workers never fire the same event. Retried calls should carry an idempotency key, so a duplicate claim or transition is recognized instead of reapplied.

A test that exposes a broken guard

Start two threads behind a latch, one claiming a ticket for each of two agents, and repeat the round a few thousand times with fresh tickets. Assert that exactly one claim returns ASSIGNED and that the two agents together hold exactly one slot. If assignTo() reserved capacity before checking the table, or if tryReserve() lost its monitor, some round would show a leaked slot or an agent above its capacity.

Complete Clean Code Blueprint

Below is a clean, multi-language blueprint of the helpdesk. Each driver runs four scenes with an injected clock: the three strategies on one roster, queue ordering, a full lifecycle with SLA escalation and an audit trail, and a concurrent run where two agents claim one ticket and twelve assigners compete for the remaining slots.

// ─── JAVA BLUEPRINT ──────────────────────────────────────────────────────────
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

enum Priority {
    LOW, NORMAL, HIGH, URGENT;

    Priority next() { return this == URGENT ? URGENT : values()[ordinal() + 1]; }
}

enum TicketStatus { OPEN, ASSIGNED, IN_PROGRESS, WAITING_ON_CUSTOMER, RESOLVED, CLOSED, REOPENED }

enum AssignOutcome { ASSIGNED, AGENT_FULL, NOT_ASSIGNABLE, NO_AGENT }

enum SlaEventType {
    FIRST_RESPONSE_AT_RISK(true), FIRST_RESPONSE_BREACHED(true),
    RESOLUTION_AT_RISK(false), RESOLUTION_BREACHED(false);

    private final boolean firstResponse;
    SlaEventType(boolean firstResponse) { this.firstResponse = firstResponse; }
    boolean isFirstResponse() { return firstResponse; }
}

class IllegalTransitionException extends RuntimeException {
    IllegalTransitionException(String message) { super(message); }
}

// The clock is injected everywhere, so tests and demos never sleep.
interface Clock { long now(); }

class ManualClock implements Clock {
    private final AtomicLong millis = new AtomicLong(0);
    public long now() { return millis.get(); }
    void advanceMinutes(long minutes) { millis.addAndGet(minutes * SlaPolicy.MINUTE); }
}

// The legal-transition table. Anything not listed here is rejected.
final class TicketStateMachine {
    private static final Map<TicketStatus, Set<TicketStatus>> ALLOWED = new EnumMap<>(TicketStatus.class);

    static {
        allow(TicketStatus.OPEN, TicketStatus.ASSIGNED);
        allow(TicketStatus.ASSIGNED, TicketStatus.IN_PROGRESS, TicketStatus.OPEN);
        allow(TicketStatus.IN_PROGRESS, TicketStatus.WAITING_ON_CUSTOMER, TicketStatus.RESOLVED, TicketStatus.OPEN);
        allow(TicketStatus.WAITING_ON_CUSTOMER, TicketStatus.IN_PROGRESS, TicketStatus.RESOLVED);
        allow(TicketStatus.RESOLVED, TicketStatus.CLOSED, TicketStatus.REOPENED);
        allow(TicketStatus.CLOSED);
        allow(TicketStatus.REOPENED, TicketStatus.ASSIGNED);
    }

    private TicketStateMachine() {}

    private static void allow(TicketStatus from, TicketStatus... to) {
        Set<TicketStatus> targets = EnumSet.noneOf(TicketStatus.class);
        targets.addAll(Arrays.asList(to));
        ALLOWED.put(from, targets);
    }

    static boolean canTransition(TicketStatus from, TicketStatus to) {
        return ALLOWED.get(from).contains(to);
    }

    static Set<TicketStatus> allowedFrom(TicketStatus from) {
        return Collections.unmodifiableSet(ALLOWED.get(from));
    }
}

class SlaPolicy {
    static final long MINUTE = 60_000L;
    private final Map<Priority, long[]> windows = new EnumMap<>(Priority.class);

    SlaPolicy() {
        windows.put(Priority.URGENT, new long[]{10 * MINUTE, 60 * MINUTE});
        windows.put(Priority.HIGH, new long[]{30 * MINUTE, 240 * MINUTE});
        windows.put(Priority.NORMAL, new long[]{120 * MINUTE, 1440 * MINUTE});
        windows.put(Priority.LOW, new long[]{480 * MINUTE, 4320 * MINUTE});
    }

    long firstResponseWindow(Priority p) { return windows.get(p)[0]; }
    long resolutionWindow(Priority p) { return windows.get(p)[1]; }
    // A deadline is "at risk" once 80 percent of its window has elapsed.
    long atRiskOffset(long window) { return window * 4 / 5; }
}

class Agent {
    private final String id;
    private final int capacity;
    private final Set<String> skills;
    private int active = 0;

    Agent(String id, int capacity, String... skills) {
        this.id = id;
        this.capacity = capacity;
        this.skills = new HashSet<>(Arrays.asList(skills));
    }

    String getId() { return id; }
    int getCapacity() { return capacity; }
    boolean hasSkill(String skill) { return skills.contains(skill); }
    synchronized int getActive() { return active; }
    synchronized boolean hasCapacity() { return active < capacity; }

    // Check and increment in one monitor, so two assigners can never take the last slot.
    synchronized boolean tryReserve() {
        if (active >= capacity) return false;
        active++;
        return true;
    }

    synchronized void release() { if (active > 0) active--; }
}

class Comment {
    final long at;
    final String author;
    final String text;
    final boolean byAgent;

    Comment(long at, String author, String text, boolean byAgent) {
        this.at = at;
        this.author = author;
        this.text = text;
        this.byAgent = byAgent;
    }
}

class AuditEntry {
    final long at;
    final String actor;
    final String action;

    AuditEntry(long at, String actor, String action) {
        this.at = at;
        this.actor = actor;
        this.action = action;
    }

    String format() { return "t+" + (at / SlaPolicy.MINUTE) + "m " + actor + ": " + action; }
}

// Lock order everywhere: Ticket monitor first, then at most one Agent monitor at a time.
// Agent never calls back into Ticket, so the two locks can never be taken in opposite order.
class Ticket {
    private final int number;
    private final String customer;
    private final String subject;
    private final String skill;
    private final long createdAt;
    private final Clock clock;
    private Priority priority;
    private TicketStatus status = TicketStatus.OPEN;
    private Agent assignee;
    private long firstRespondedAt = -1;
    private final List<Comment> comments = new ArrayList<>();
    private final List<AuditEntry> audit = new ArrayList<>();

    Ticket(int number, String customer, String subject, String skill, Priority priority, Clock clock) {
        this.number = number;
        this.customer = customer;
        this.subject = subject;
        this.skill = skill;
        this.priority = priority;
        this.clock = clock;
        this.createdAt = clock.now();
        log(customer, "opened with priority " + priority);
    }

    int getNumber() { return number; }
    String getId() { return "T-" + number; }
    String getCustomer() { return customer; }
    String getSubject() { return subject; }
    String getSkill() { return skill; }
    long getCreatedAt() { return createdAt; }
    synchronized TicketStatus getStatus() { return status; }
    synchronized Priority getPriority() { return priority; }
    synchronized Agent getAssignee() { return assignee; }
    synchronized boolean isQueued() { return status == TicketStatus.OPEN || status == TicketStatus.REOPENED; }
    synchronized List<Comment> getComments() { return new ArrayList<>(comments); }
    synchronized List<AuditEntry> getAudit() { return new ArrayList<>(audit); }

    // Check the table, reserve capacity, then set the owner, all under this ticket's monitor.
    synchronized AssignOutcome assignTo(Agent agent, String actor) {
        if (!TicketStateMachine.canTransition(status, TicketStatus.ASSIGNED)) return AssignOutcome.NOT_ASSIGNABLE;
        if (!agent.tryReserve()) return AssignOutcome.AGENT_FULL;
        assignee = agent;
        apply(TicketStatus.ASSIGNED, actor, " (" + agent.getId() + ")");
        return AssignOutcome.ASSIGNED;
    }

    // Reassignment swaps the owner and keeps the status, so it is not a table transition.
    synchronized AssignOutcome reassignTo(Agent next, String actor) {
        boolean movable = status == TicketStatus.ASSIGNED || status == TicketStatus.IN_PROGRESS;
        if (!movable || assignee == null || assignee == next) return AssignOutcome.NOT_ASSIGNABLE;
        if (!next.tryReserve()) return AssignOutcome.AGENT_FULL;
        Agent previous = assignee;
        assignee = next;
        previous.release();
        log(actor, "reassigned from " + previous.getId() + " to " + next.getId());
        return AssignOutcome.ASSIGNED;
    }

    synchronized void transition(TicketStatus to, String actor) {
        if (to == TicketStatus.ASSIGNED) {
            throw new IllegalTransitionException("ASSIGNED needs an agent, use assignTo");
        }
        if (!TicketStateMachine.canTransition(status, to)) {
            throw new IllegalTransitionException(status + " -> " + to + " is not allowed, legal next states: "
                + TicketStateMachine.allowedFrom(status));
        }
        if (to == TicketStatus.OPEN || to == TicketStatus.RESOLVED) releaseAgent();
        apply(to, actor, "");
    }

    // Returns true when this comment is the first agent reply, which satisfies the first-response SLA.
    synchronized boolean addComment(String author, String text, boolean byAgent) {
        long now = clock.now();
        comments.add(new Comment(now, author, text, byAgent));
        log(author, "commented");
        if (byAgent && firstRespondedAt < 0) {
            firstRespondedAt = now;
            return true;
        }
        return false;
    }

    synchronized boolean raisePriority(Priority target, String reason) {
        boolean finished = status == TicketStatus.RESOLVED || status == TicketStatus.CLOSED;
        if (finished || target.compareTo(priority) <= 0) return false;
        log("escalation", "priority " + priority + " -> " + target + " (" + reason + ")");
        priority = target;
        return true;
    }

    synchronized void addAuditNote(String actor, String note) { log(actor, note); }

    // Re-checked by the observer because an SLA event can be stale by the time it is delivered.
    synchronized boolean isSlaOpen(SlaEventType type) {
        boolean finished = status == TicketStatus.RESOLVED || status == TicketStatus.CLOSED;
        return !finished && (!type.isFirstResponse() || firstRespondedAt < 0);
    }

    private void releaseAgent() {
        if (assignee != null) {
            assignee.release();
            assignee = null;
        }
    }

    private void apply(TicketStatus to, String actor, String detail) {
        log(actor, status + " -> " + to + detail);
        status = to;
    }

    private void log(String actor, String action) { audit.add(new AuditEntry(clock.now(), actor, action)); }
}

// ─── Assignment strategies ────────────────────────────────────────────────────
// A strategy only suggests an agent from a snapshot. The authoritative capacity check is Agent.tryReserve().
interface AssignmentStrategy {
    Agent pick(Ticket ticket, List<Agent> candidates);
}

class RoundRobinStrategy implements AssignmentStrategy {
    private int cursor = 0;

    public synchronized Agent pick(Ticket ticket, List<Agent> candidates) {
        int n = candidates.size();
        for (int i = 0; i < n; i++) {
            int index = (cursor + i) % n;
            Agent agent = candidates.get(index);
            if (agent.hasCapacity()) {
                cursor = index + 1;
                return agent;
            }
        }
        return null;
    }
}

class LeastLoadedStrategy implements AssignmentStrategy {
    public Agent pick(Ticket ticket, List<Agent> candidates) {
        Agent best = null;
        for (Agent agent : candidates) {
            if (!agent.hasCapacity()) continue;
            boolean lighter = best == null || agent.getActive() < best.getActive();
            boolean tieWithLowerId = best != null && agent.getActive() == best.getActive()
                && agent.getId().compareTo(best.getId()) < 0;
            if (lighter || tieWithLowerId) best = agent;
        }
        return best;
    }
}

// Filters to agents who have the skill, then lets an inner strategy choose among them.
class SkillBasedStrategy implements AssignmentStrategy {
    private final AssignmentStrategy inner;

    SkillBasedStrategy(AssignmentStrategy inner) { this.inner = inner; }

    public Agent pick(Ticket ticket, List<Agent> candidates) {
        List<Agent> skilled = new ArrayList<>();
        for (Agent agent : candidates) if (agent.hasSkill(ticket.getSkill())) skilled.add(agent);
        return inner.pick(ticket, skilled);
    }
}

class Dispatcher {
    private final List<Agent> agents = new CopyOnWriteArrayList<>();
    private volatile AssignmentStrategy strategy;

    Dispatcher(AssignmentStrategy strategy) { this.strategy = strategy; }

    void addAgent(Agent agent) { agents.add(agent); }
    void setStrategy(AssignmentStrategy strategy) { this.strategy = strategy; }

    Agent agent(String id) {
        for (Agent agent : agents) if (agent.getId().equals(id)) return agent;
        throw new NoSuchElementException("unknown agent " + id);
    }

    AssignOutcome assign(Ticket ticket) { return place(ticket, null); }

    AssignOutcome reassign(Ticket ticket) {
        Agent current = ticket.getAssignee();
        return current == null ? AssignOutcome.NOT_ASSIGNABLE : place(ticket, current);
    }

    // Pick, try to reserve, and when the pick lost the last slot to someone else, drop it and pick again.
    private AssignOutcome place(Ticket ticket, Agent exclude) {
        List<Agent> pool = new ArrayList<>(agents);
        if (exclude != null) pool.remove(exclude);
        AssignmentStrategy chosen = strategy;
        while (true) {
            Agent pick = chosen.pick(ticket, pool);
            if (pick == null) return AssignOutcome.NO_AGENT;
            AssignOutcome outcome = exclude == null
                ? ticket.assignTo(pick, "dispatcher")
                : ticket.reassignTo(pick, "escalation");
            if (outcome != AssignOutcome.AGENT_FULL) return outcome;
            pool.remove(pick);
        }
    }
}

// ─── SLA tracking and escalation ──────────────────────────────────────────────
class SlaEvent {
    final long at;
    final long seq;
    final Ticket ticket;
    final SlaEventType type;
    boolean cancelled;   // lazy deletion, only touched while holding the SlaTracker monitor

    SlaEvent(long at, long seq, Ticket ticket, SlaEventType type) {
        this.at = at;
        this.seq = seq;
        this.ticket = ticket;
        this.type = type;
    }
}

interface SlaListener {
    void onSlaEvent(Ticket ticket, SlaEventType type, long now);
}

// One min-heap of future deadlines. tick() only ever looks at the head, so a check costs
// O(k log n) for k events that are due, never O(n) over every open ticket.
class SlaTracker {
    private final Clock clock;
    private final SlaPolicy policy;
    private final PriorityQueue<SlaEvent> heap = new PriorityQueue<>(
        Comparator.<SlaEvent>comparingLong(e -> e.at).thenComparingLong(e -> e.seq));
    private final Map<String, List<SlaEvent>> byTicket = new HashMap<>();
    private final List<SlaListener> listeners = new CopyOnWriteArrayList<>();
    private long nextSeq = 0;

    SlaTracker(Clock clock, SlaPolicy policy) {
        this.clock = clock;
        this.policy = policy;
    }

    void addListener(SlaListener listener) { listeners.add(listener); }

    // The priority is passed in, so the tracker never takes a Ticket monitor while holding its own.
    synchronized void armFirstResponse(Ticket ticket, Priority priority, long from) {
        arm(ticket, from, policy.firstResponseWindow(priority),
            SlaEventType.FIRST_RESPONSE_AT_RISK, SlaEventType.FIRST_RESPONSE_BREACHED);
    }

    synchronized void armResolution(Ticket ticket, Priority priority, long from) {
        arm(ticket, from, policy.resolutionWindow(priority),
            SlaEventType.RESOLUTION_AT_RISK, SlaEventType.RESOLUTION_BREACHED);
    }

    synchronized void cancelFirstResponse(String ticketId) {
        List<SlaEvent> events = byTicket.get(ticketId);
        if (events == null) return;
        for (SlaEvent e : events) if (e.type.isFirstResponse()) e.cancelled = true;
        events.removeIf(e -> e.cancelled);
        if (events.isEmpty()) byTicket.remove(ticketId);
    }

    synchronized void cancelAll(String ticketId) {
        List<SlaEvent> events = byTicket.remove(ticketId);
        if (events != null) for (SlaEvent e : events) e.cancelled = true;
    }

    int tick() {
        long now = clock.now();
        List<SlaEvent> due = new ArrayList<>();
        synchronized (this) {
            while (!heap.isEmpty() && heap.peek().at <= now) {
                SlaEvent e = heap.poll();   // popping is the claim, so two tick() calls never share an event
                List<SlaEvent> events = byTicket.get(e.ticket.getId());
                if (events != null) {
                    events.remove(e);
                    if (events.isEmpty()) byTicket.remove(e.ticket.getId());
                }
                if (!e.cancelled) due.add(e);
            }
        }
        // Listeners run outside the lock because they take Ticket and Agent monitors.
        for (SlaEvent e : due) for (SlaListener l : listeners) l.onSlaEvent(e.ticket, e.type, now);
        return due.size();
    }

    private void arm(Ticket ticket, long from, long window, SlaEventType atRisk, SlaEventType breached) {
        push(new SlaEvent(from + policy.atRiskOffset(window), nextSeq++, ticket, atRisk));
        push(new SlaEvent(from + window, nextSeq++, ticket, breached));
    }

    private void push(SlaEvent event) {
        heap.add(event);
        byTicket.computeIfAbsent(event.ticket.getId(), k -> new ArrayList<>()).add(event);
    }
}

// At risk: bump one level. First response breached: hand the ticket to someone else, or go URGENT.
// Resolution breached: go URGENT. Deadlines stay as promised, so escalation never rewrites them.
class EscalationObserver implements SlaListener {
    private final Dispatcher dispatcher;

    EscalationObserver(Dispatcher dispatcher) { this.dispatcher = dispatcher; }

    public void onSlaEvent(Ticket ticket, SlaEventType type, long now) {
        if (!ticket.isSlaOpen(type)) return;
        switch (type) {
            case FIRST_RESPONSE_AT_RISK, RESOLUTION_AT_RISK ->
                ticket.raisePriority(ticket.getPriority().next(), "SLA at risk");
            case FIRST_RESPONSE_BREACHED -> {
                ticket.addAuditNote("sla", "first response SLA breached");
                if (dispatcher.reassign(ticket) != AssignOutcome.ASSIGNED) {
                    ticket.raisePriority(Priority.URGENT, "first response breached, no agent free");
                }
            }
            case RESOLUTION_BREACHED -> {
                ticket.addAuditNote("sla", "resolution SLA breached");
                ticket.raisePriority(Priority.URGENT, "resolution breached");
            }
        }
    }
}

// ─── Facade ───────────────────────────────────────────────────────────────────
class Helpdesk {
    private final Clock clock;
    private final SlaTracker sla;
    private final Dispatcher dispatcher;
    private final Map<String, Ticket> tickets = new ConcurrentHashMap<>();
    private final AtomicInteger numbers = new AtomicInteger(1);

    Helpdesk(Clock clock, SlaPolicy policy, AssignmentStrategy strategy) {
        this.clock = clock;
        this.sla = new SlaTracker(clock, policy);
        this.dispatcher = new Dispatcher(strategy);
        this.sla.addListener(new EscalationObserver(dispatcher));
    }

    void addAgent(Agent agent) { dispatcher.addAgent(agent); }
    void setStrategy(AssignmentStrategy strategy) { dispatcher.setStrategy(strategy); }
    Ticket getTicket(String id) {
        Ticket ticket = tickets.get(id);
        if (ticket == null) throw new NoSuchElementException("unknown ticket " + id);
        return ticket;
    }

    Ticket createTicket(String customer, String subject, Priority priority, String skill) {
        Ticket ticket = new Ticket(numbers.getAndIncrement(), customer, subject, skill, priority, clock);
        tickets.put(ticket.getId(), ticket);
        long now = clock.now();
        sla.armFirstResponse(ticket, priority, now);
        sla.armResolution(ticket, priority, now);
        return ticket;
    }

    AssignOutcome assign(String ticketId) { return dispatcher.assign(getTicket(ticketId)); }

    // An agent pulls a specific ticket for themselves.
    AssignOutcome claim(String ticketId, String agentId) {
        return getTicket(ticketId).assignTo(dispatcher.agent(agentId), agentId);
    }

    void transition(String ticketId, TicketStatus to, String actor) {
        Ticket ticket = getTicket(ticketId);
        ticket.transition(to, actor);
        if (to == TicketStatus.RESOLVED) sla.cancelAll(ticketId);
        if (to == TicketStatus.REOPENED) sla.armResolution(ticket, ticket.getPriority(), clock.now());
    }

    boolean comment(String ticketId, String author, String text, boolean byAgent) {
        boolean firstResponse = getTicket(ticketId).addComment(author, text, byAgent);
        if (firstResponse) sla.cancelFirstResponse(ticketId);
        return firstResponse;
    }

    // Highest priority first, then oldest, then lowest ticket number.
    List<Ticket> queuedTickets() {
        List<Ticket> queue = new ArrayList<>();
        for (Ticket t : tickets.values()) if (t.isQueued()) queue.add(t);
        queue.sort(Comparator.comparing(Ticket::getPriority).reversed()
            .thenComparingLong(Ticket::getCreatedAt)
            .thenComparingInt(Ticket::getNumber));
        return queue;
    }

    int assignQueued() {
        int assigned = 0;
        for (Ticket t : queuedTickets()) {
            if (dispatcher.assign(t) == AssignOutcome.ASSIGNED) assigned++;
        }
        return assigned;
    }

    int checkSla() { return sla.tick(); }
}

// ─── Driver ───────────────────────────────────────────────────────────────────
public class Main {
    static String queueLine(Helpdesk desk) {
        StringBuilder line = new StringBuilder();
        for (Ticket t : desk.queuedTickets()) line.append(t.getId()).append('(').append(t.getPriority()).append(") ");
        return line.toString().trim();
    }

    static void strategyDemo() {
        System.out.println("=== 1. Assignment strategies on the same roster ===");
        Agent alice = new Agent("alice", 2, "billing", "general");
        Agent bob = new Agent("bob", 2, "network", "general");
        Agent carol = new Agent("carol", 1, "billing", "network");
        List<Agent> roster = List.of(alice, bob, carol);
        alice.tryReserve();   // alice already holds one ticket
        Ticket billing = new Ticket(0, "acme", "Card declined", "billing", Priority.NORMAL, new ManualClock());

        RoundRobinStrategy roundRobin = new RoundRobinStrategy();
        StringBuilder rotation = new StringBuilder();
        for (int i = 0; i < 4; i++) rotation.append(roundRobin.pick(billing, roster).getId()).append(' ');
        System.out.println("round robin picks  : " + rotation.toString().trim());
        System.out.println("least loaded picks : " + new LeastLoadedStrategy().pick(billing, roster).getId());
        System.out.println("skill based picks  : "
            + new SkillBasedStrategy(new LeastLoadedStrategy()).pick(billing, roster).getId());

        System.out.println();
        System.out.println("=== 2. Queue order: priority, then oldest, then ticket number ===");
        ManualClock clock = new ManualClock();
        Helpdesk desk = new Helpdesk(clock, new SlaPolicy(), new LeastLoadedStrategy());
        desk.createTicket("c1", "Slow dashboard", Priority.NORMAL, "general");
        clock.advanceMinutes(1);
        desk.createTicket("c2", "Login loop", Priority.HIGH, "general");
        desk.createTicket("c3", "Typo in invoice", Priority.LOW, "general");
        desk.createTicket("c4", "Checkout down", Priority.HIGH, "general");
        System.out.println("queue            : " + queueLine(desk));
        desk.addAgent(new Agent("dana", 2));
        System.out.println("assigned queued  : " + desk.assignQueued());
        System.out.println("still queued     : " + queueLine(desk));
    }

    static void lifecycleDemo() {
        System.out.println();
        System.out.println("=== 3. Lifecycle, state machine and SLA escalation ===");
        ManualClock clock = new ManualClock();
        Helpdesk desk = new Helpdesk(clock, new SlaPolicy(), new SkillBasedStrategy(new LeastLoadedStrategy()));
        desk.addAgent(new Agent("alice", 2, "billing", "general"));
        desk.addAgent(new Agent("bob", 2, "network", "general"));
        desk.addAgent(new Agent("carol", 1, "billing", "network"));

        Ticket refund = desk.createTicket("acme", "Refund missing", Priority.NORMAL, "billing");
        Ticket vpn = desk.createTicket("globex", "VPN keeps dropping", Priority.HIGH, "network");
        Ticket address = desk.createTicket("initech", "Change invoice address", Priority.LOW, "general");
        for (Ticket t : List.of(refund, vpn, address)) {
            AssignOutcome outcome = desk.assign(t.getId());
            System.out.println(t.getId() + " " + outcome + " to " + t.getAssignee().getId());
        }

        try {
            desk.transition(refund.getId(), TicketStatus.RESOLVED, "alice");
        } catch (IllegalTransitionException e) {
            System.out.println("rejected: " + e.getMessage());
        }
        desk.transition(refund.getId(), TicketStatus.IN_PROGRESS, "alice");
        clock.advanceMinutes(10);
        System.out.println("t+10m SLA events fired: " + desk.checkSla());
        boolean first = desk.comment(refund.getId(), "alice", "Looking into the refund", true);
        System.out.println("alice replied on " + refund.getId() + ", first response recorded: " + first);

        clock.advanceMinutes(14);
        System.out.println("t+24m SLA events fired: " + desk.checkSla() + ", " + vpn.getId()
            + " is now " + vpn.getPriority());
        clock.advanceMinutes(6);
        System.out.println("t+30m SLA events fired: " + desk.checkSla() + ", " + vpn.getId()
            + " now owned by " + vpn.getAssignee().getId());
        desk.transition(vpn.getId(), TicketStatus.IN_PROGRESS, "carol");
        desk.comment(vpn.getId(), "carol", "Replaced the gateway config", true);

        desk.transition(refund.getId(), TicketStatus.WAITING_ON_CUSTOMER, "alice");
        clock.advanceMinutes(20);
        desk.transition(refund.getId(), TicketStatus.IN_PROGRESS, "alice");
        desk.transition(refund.getId(), TicketStatus.RESOLVED, "alice");
        clock.advanceMinutes(10);
        desk.transition(refund.getId(), TicketStatus.REOPENED, "acme");
        System.out.println("t+60m reopened, queue: " + queueLine(desk) + ", assigned: " + desk.assignQueued()
            + ", owner: " + refund.getAssignee().getId());
        desk.transition(refund.getId(), TicketStatus.IN_PROGRESS, "alice");
        desk.transition(refund.getId(), TicketStatus.RESOLVED, "alice");
        desk.transition(refund.getId(), TicketStatus.CLOSED, "alice");
        try {
            desk.transition(refund.getId(), TicketStatus.REOPENED, "acme");
        } catch (IllegalTransitionException e) {
            System.out.println("rejected: " + e.getMessage());
        }

        clock.advanceMinutes(140);
        System.out.println("t+200m SLA events fired: " + desk.checkSla());
        clock.advanceMinutes(50);
        System.out.println("t+250m SLA events fired: " + desk.checkSla());

        for (Ticket t : List.of(refund, vpn, address)) {
            String owner = t.getAssignee() == null ? "nobody" : t.getAssignee().getId();
            System.out.println(t.getId() + " " + t.getStatus() + " " + t.getPriority() + " owner=" + owner
                + " comments=" + t.getComments().size());
        }
        System.out.println("Audit trail for " + vpn.getId() + ":");
        for (AuditEntry entry : vpn.getAudit()) System.out.println("  " + entry.format());
    }

    static void raceDemo() throws Exception {
        System.out.println();
        System.out.println("=== 4. Concurrency: claims and capacity under contention ===");
        Helpdesk desk = new Helpdesk(new ManualClock(), new SlaPolicy(), new LeastLoadedStrategy());
        Agent a1 = new Agent("a1", 2);
        Agent a2 = new Agent("a2", 2);
        Agent a3 = new Agent("a3", 1);
        for (Agent a : List.of(a1, a2, a3)) desk.addAgent(a);
        ExecutorService pool = Executors.newFixedThreadPool(12);

        Ticket contested = desk.createTicket("zeta", "Contested ticket", Priority.NORMAL, "general");
        CountDownLatch claimGate = new CountDownLatch(1);
        List<Future<AssignOutcome>> claims = new ArrayList<>();
        for (String agentId : List.of("a1", "a2")) {
            claims.add(pool.submit(() -> {
                claimGate.await();
                return desk.claim(contested.getId(), agentId);
            }));
        }
        claimGate.countDown();
        int winners = 0;
        for (Future<AssignOutcome> f : claims) if (f.get() == AssignOutcome.ASSIGNED) winners++;
        System.out.println("two agents claim " + contested.getId() + ": winners=" + winners
            + ", slots held=" + (a1.getActive() + a2.getActive()));

        List<String> ids = new ArrayList<>();
        for (int i = 0; i < 12; i++) ids.add(desk.createTicket("c" + i, "Issue " + i, Priority.NORMAL, "general").getId());
        CountDownLatch assignGate = new CountDownLatch(1);
        List<Future<AssignOutcome>> results = new ArrayList<>();
        for (String id : ids) {
            results.add(pool.submit(() -> {
                assignGate.await();
                return desk.assign(id);
            }));
        }
        assignGate.countDown();
        int assigned = 0;
        for (Future<AssignOutcome> f : results) if (f.get() == AssignOutcome.ASSIGNED) assigned++;
        pool.shutdown();
        System.out.println("12 assigners, 4 slots left: assigned=" + assigned + ", turned away=" + (12 - assigned));
        System.out.println("a1=" + a1.getActive() + "/" + a1.getCapacity() + " a2=" + a2.getActive() + "/"
            + a2.getCapacity() + " a3=" + a3.getActive() + "/" + a3.getCapacity());
    }

    public static void main(String[] args) throws Exception {
        strategyDemo();
        lifecycleDemo();
        raceDemo();
    }
}

πŸ’¬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...