Bird
Raised Fist0
LLDsystem_design~7 mins

Delivery agent assignment in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When multiple delivery agents are available, assigning orders manually or randomly can cause delays, uneven workload, and poor customer experience. Without a systematic approach, some agents may be overloaded while others remain idle, leading to inefficiency and slower deliveries.
Solution
This pattern assigns delivery agents to orders based on criteria like proximity, current workload, and delivery capacity. The system automatically selects the best available agent for each order, balancing load and minimizing delivery time. It continuously updates agent status to optimize assignments dynamically.
Architecture
Order
Service
Assignment
Agent Status Store
Agent Status Store

This diagram shows how the order service sends new orders to the assignment service, which consults the agent status store to pick the best delivery agent and then assigns the order to that agent.

Trade-offs
✓ Pros
Improves delivery speed by assigning nearest or least busy agents.
Balances workload among agents to prevent burnout and idle time.
Automates assignment, reducing manual errors and delays.
Allows dynamic updates as agent availability changes.
✗ Cons
Requires real-time tracking of agent status, adding system complexity.
Needs careful tuning of assignment criteria to avoid unfair load distribution.
May require fallback logic if no suitable agent is available.
Use when the delivery system has multiple agents and order volume exceeds 100 orders per hour, requiring automated, efficient assignment to maintain service quality.
Avoid when the delivery area is very small with only a few agents or order volume is below 10 orders per hour, where manual assignment is simpler and sufficient.
Real World Examples
Uber Eats
Assigns delivery partners to food orders based on proximity and current workload to minimize delivery time and balance agent utilization.
Amazon
Automatically assigns packages to delivery drivers considering route optimization and driver capacity to ensure timely deliveries.
DoorDash
Uses dynamic assignment to match delivery agents with orders in real-time, adjusting for traffic and agent availability.
Code Example
The before code assigns orders randomly, which can overload some agents. The after code assigns orders to the agent with the least current workload, balancing assignments and improving efficiency.
LLD
### Before: naive random assignment
import random

class DeliveryAgent:
    def __init__(self, id):
        self.id = id

class Order:
    def __init__(self, id):
        self.id = id

class AssignmentService:
    def __init__(self, agents):
        self.agents = agents

    def assign(self, order):
        agent = random.choice(self.agents)
        print(f"Order {order.id} assigned to agent {agent.id} (random)")


### After: assignment based on least workload

class DeliveryAgentWithLoad:
    def __init__(self, id):
        self.id = id
        self.current_load = 0

class AssignmentServiceWithLoad:
    def __init__(self, agents):
        self.agents = agents

    def assign(self, order):
        # Pick agent with least current load
        agent = min(self.agents, key=lambda a: a.current_load)
        agent.current_load += 1
        print(f"Order {order.id} assigned to agent {agent.id} (least load)")

# Example usage
agents = [DeliveryAgentWithLoad(i) for i in range(3)]
service = AssignmentServiceWithLoad(agents)
orders = [Order(i) for i in range(5)]
for order in orders:
    service.assign(order)
OutputSuccess
Alternatives
Round Robin Assignment
Assigns orders to agents in a fixed cyclic order without considering proximity or workload.
Use when: Use when agent workload is uniform and delivery area is small, making complex criteria unnecessary.
First-Come-First-Serve Assignment
Assigns orders to the first available agent regardless of location or load.
Use when: Use when order volume is low and agent availability is stable.
Auction-Based Assignment
Agents bid for orders based on their preferences and current status, and the system assigns based on bids.
Use when: Use when agents have varying preferences and incentives, and a market-driven approach is desired.
Summary
Delivery agent assignment automates matching orders to agents to prevent delays and overload.
It balances workload and considers factors like proximity to improve delivery speed.
This pattern is essential for systems with many agents and high order volumes.

Practice

(1/5)
1.

What is the primary goal of a delivery agent assignment system?

easy
A. Match orders to available delivery agents nearby
B. Track payment details of customers
C. Manage inventory in warehouses
D. Calculate delivery charges for orders

Solution

  1. Step 1: Understand the system purpose

    The delivery agent assignment system focuses on connecting orders with delivery agents who can fulfill them.
  2. Step 2: Identify the main function

    Matching orders to free agents nearby ensures timely delivery and efficient resource use.
  3. Final Answer:

    Match orders to available delivery agents nearby -> Option A
  4. Quick Check:

    Delivery agent assignment = Matching orders to agents [OK]
Hint: Focus on matching orders to agents, not payments or inventory [OK]
Common Mistakes:
  • Confusing delivery assignment with payment processing
  • Thinking inventory management is part of agent assignment
  • Assuming delivery charges calculation is the main goal
2.

Which data structure is best to quickly find the nearest free delivery agent for an order?

easy
A. Priority queue sorted by distance from order location
B. Stack of agents in order of registration
C. Hash map keyed by agent ID
D. Linked list of all agents

Solution

  1. Step 1: Identify the need for sorting by distance

    To find the nearest free agent, sorting agents by their distance to the order location is essential.
  2. Step 2: Choose a data structure supporting efficient nearest retrieval

    A priority queue can efficiently provide the closest agent by always giving the smallest distance first.
  3. Final Answer:

    Priority queue sorted by distance from order location -> Option A
  4. Quick Check:

    Nearest agent search = Priority queue [OK]
Hint: Use priority queue for nearest-first retrieval [OK]
Common Mistakes:
  • Using hash map which doesn't sort by distance
  • Using stack or linked list which are inefficient for nearest search
  • Ignoring the need to sort by distance
3.

Consider this pseudocode for assigning an agent:
for agent in agents:
  if agent.status == 'free' and distance(agent, order) < min_distance:
    min_distance = distance(agent, order)
    assigned_agent = agent
return assigned_agent

What will this code return if all agents are busy?

medium
A. The closest free agent
B. None or null
C. The first agent in the list
D. An error due to undefined variable

Solution

  1. Step 1: Check variable initializations

    The code does not initialize assigned_agent or min_distance before the loop.
  2. Step 2: Trace execution when all agents are busy

    The if condition's first part (agent.status == 'free') fails for all agents, so due to short-circuit evaluation of 'and', the second part (distance < min_distance) is never evaluated. The loop ends without ever setting assigned_agent. Returning an uninitialized assigned_agent causes an error due to undefined variable.
  3. Final Answer:

    An error due to undefined variable -> Option D
  4. Quick Check:

    No initialization + all busy = undefined variable error [OK]
Hint: No variable initialization leads to undefined variable error [OK]
Common Mistakes:
  • Thinking assigned_agent defaults to None or null
  • Assuming it returns the first agent regardless of status
  • Believing the code handles no free agents gracefully
4.

Given this snippet:
assigned_agent = None
for agent in agents:
  if agent.status = 'free':
    assigned_agent = agent
return assigned_agent

What is the main error in this code?

medium
A. Returning assigned_agent inside the loop
B. Not initializing assigned_agent before loop
C. Using assignment operator '=' instead of comparison '==' in if condition
D. Using 'free' instead of 'available' as status

Solution

  1. Step 1: Check the if condition syntax

    The condition uses '=' which assigns value instead of '==' which compares values.
  2. Step 2: Understand impact of wrong operator

    This causes a syntax error or unintended behavior because '=' cannot be used in conditions.
  3. Final Answer:

    Using assignment operator '=' instead of comparison '==' in if condition -> Option C
  4. Quick Check:

    Use '==' for comparison, not '=' [OK]
Hint: Use '==' for comparisons in conditions [OK]
Common Mistakes:
  • Confusing '=' with '==' in if statements
  • Thinking assigned_agent must be initialized inside loop
  • Assuming return inside loop is the error
5.

You want to design a scalable delivery agent assignment system for a city with thousands of agents and orders per minute. Which approach best improves scalability?

hard
A. Use a centralized server to check all agents for every order
B. Partition the city into zones and assign agents within zones only
C. Assign agents randomly without considering location
D. Assign the oldest registered agent to every order

Solution

  1. Step 1: Understand scalability challenges

    Checking all agents for every order is slow and resource-heavy at large scale.
  2. Step 2: Choose a partitioning strategy

    Dividing the city into zones limits search space, making assignment faster and scalable.
  3. Step 3: Evaluate other options

    Random or oldest agent assignment ignores location, causing delays and inefficiency.
  4. Final Answer:

    Partition the city into zones and assign agents within zones only -> Option B
  5. Quick Check:

    Zone partitioning = scalable assignment [OK]
Hint: Divide city into zones to limit search scope [OK]
Common Mistakes:
  • Using centralized server causing bottlenecks
  • Ignoring agent location in assignment
  • Assigning agents randomly or by registration time