Model Musings
Call Centre Simulation with SimPy: Optimising Customer Service
- Published
- Reading time
- 9 min
Call centres live and die by their metrics. Average wait time. Abandonment rate. Service level. Simulation helps you hit your targets without overstaffing.
The Call Centre Model
Key components:
- Callers - Arrive with varying patience
- Agents - Handle calls
- Queues - Where callers wait
- Skills - Some agents handle specific call types
- Abandonment - Impatient callers hang up
Basic Call Centre
import simpy
import random
class CallCentre:
def __init__(self, env, num_agents):
self.env = env
self.agents = simpy.Resource(env, capacity=num_agents)
self.stats = {
'calls_handled': 0,
'calls_abandoned': 0,
'wait_times': [],
'handle_times': []
}
def handle_call(self, call_id, patience):
arrival = self.env.now
with self.agents.request() as req:
# Wait for agent OR give up
result = yield req | self.env.timeout(patience)
if req in result:
# Connected to agent
wait = self.env.now - arrival
self.stats['wait_times'].append(wait)
# Handle the call
handle_time = random.lognormvariate(2, 0.5) # Mean about 8.4 mins
yield self.env.timeout(handle_time)
self.stats['handle_times'].append(handle_time)
self.stats['calls_handled'] += 1
else:
# Caller abandoned
self.stats['calls_abandoned'] += 1
def call_arrivals(env, call_centre, arrival_rate, mean_patience):
call_id = 0
while True:
yield env.timeout(random.expovariate(arrival_rate))
patience = random.expovariate(1/mean_patience)
env.process(call_centre.handle_call(call_id, patience))
call_id += 1
# Run simulation
env = simpy.Environment()
cc = CallCentre(env, num_agents=10)
env.process(call_arrivals(env, cc, arrival_rate=1/0.5, mean_patience=5))
env.run(until=480) # 8 hours
print(f"Calls handled: {cc.stats['calls_handled']}")
print(f"Calls abandoned: {cc.stats['calls_abandoned']}")
abandonment_rate = cc.stats['calls_abandoned'] / (cc.stats['calls_handled'] + cc.stats['calls_abandoned'])
print(f"Abandonment rate: {abandonment_rate:.1%}")
Multi-Skill Routing
Agents with different skills. A caller queues for the specialists first; if none has answered within a couple of minutes, the call overflows to the general agents for whatever patience the caller has left:
import simpy
import random
class SkillBasedCallCentre:
def __init__(self, env, agent_config, overflow_after=2):
self.env = env
self.overflow_after = overflow_after # Minutes before overflowing
self.agents = {}
for skill, count in agent_config.items():
self.agents[skill] = simpy.Resource(env, capacity=count)
self.stats = {'by_skill': {skill: [] for skill in agent_config}, 'abandoned': 0}
def handle_call(self, call_id, call_type, patience):
arrival = self.env.now
# Try the specialists first, then overflow to general agents
for skill in [call_type, 'general']:
remaining = patience - (self.env.now - arrival)
if remaining <= 0:
break
# Specialists get a couple of minutes; general agents get the rest
limit = remaining if skill == 'general' else min(remaining, self.overflow_after)
with self.agents[skill].request() as req:
result = yield req | self.env.timeout(limit)
if req in result:
wait = self.env.now - arrival
handle_time = random.expovariate(1/7)
yield self.env.timeout(handle_time)
self.stats['by_skill'][skill].append({
'call_id': call_id,
'wait': wait,
'handle': handle_time
})
return # Call handled
# Patience ran out in every queue
self.stats['abandoned'] += 1
def arrivals(env, cc, rate, mean_patience):
call_id = 0
while True:
yield env.timeout(random.expovariate(rate))
call_type = random.choice(['sales', 'support'])
patience = random.expovariate(1/mean_patience)
env.process(cc.handle_call(call_id, call_type, patience))
call_id += 1
# Config: 5 sales, 5 support, 3 general (overflow)
random.seed(42)
env = simpy.Environment()
config = {'sales': 5, 'support': 5, 'general': 3}
cc = SkillBasedCallCentre(env, config)
env.process(arrivals(env, cc, rate=1.8, mean_patience=6))
env.run(until=480)
for skill, calls in cc.stats['by_skill'].items():
mean_wait = sum(c['wait'] for c in calls) / len(calls) if calls else 0
print(f"{skill:8} handled {len(calls):3} mean wait {mean_wait:.1f} mins")
print(f"abandoned {cc.stats['abandoned']}")
Output:
sales handled 276 mean wait 0.4 mins
support handled 282 mean wait 0.4 mins
general handled 146 mean wait 2.8 mins
abandoned 132
The overflow limit is what makes the general agents useful. Let a caller wait out their whole patience in the specialist queue and there is nothing left to spend on the general one, so the overflow never happens; cap the first wait and the general team takes the calls the specialists cannot reach in time.
VIP Priority Queue
class PriorityCallCentre:
def __init__(self, env, num_agents):
self.env = env
self.agents = simpy.PriorityResource(env, capacity=num_agents)
self.stats = {'vip': [], 'regular': []}
def handle_call(self, call_id, is_vip, patience):
arrival = self.env.now
priority = 1 if is_vip else 5
customer_type = 'vip' if is_vip else 'regular'
with self.agents.request(priority=priority) as req:
result = yield req | self.env.timeout(patience)
if req in result:
wait = self.env.now - arrival
yield self.env.timeout(random.expovariate(1/7))
self.stats[customer_type].append({'wait': wait, 'served': True})
else:
self.stats[customer_type].append({'wait': patience, 'served': False})
Time-Varying Staffing
Match staffing to demand. The obvious move is to change the number of agents on the resource as the day goes on, and SimPy resists it: capacity is read-only. Writing to the private _capacity behind it is worse than an error, because nothing in SimPy expects that number to change. Lower it and the agents already on calls finish them, which is harmless. Raise it and the extra seats fill one at a time, and only as new calls arrive. SimPy looks at the queue when a call comes in or an agent hangs up, and then seats a single caller, so a hang-up merely refills the seat it frees. Until enough new calls have come in, the callers already waiting are served at the old pace while the new agents sit idle.
The dependable pattern is the one the server model uses for breaks. Give the resource a seat for every agent on the busiest shift, and stand for each agent who is off duty with a request at a higher priority than any caller. That request waits for an agent to finish their current call, takes the seat and keeps it until the rota brings the agent back:
import random
import simpy
OFF_DUTY, CALLER = 0, 1 # Lower number = higher priority
class ScheduledCallCentre:
def __init__(self, env, schedule):
"""
schedule = {
0: 5, # Midnight: 5 agents
6: 10, # 6am: 10 agents
9: 20, # 9am: 20 agents (peak)
17: 15, # 5pm: 15 agents
21: 8 # 9pm: 8 agents
}
"""
self.env = env
self.schedule = schedule
# A seat for every agent on the busiest shift
self.seats = max(schedule.values())
self.agents = simpy.PriorityResource(env, capacity=self.seats)
self.absences = [] # One OFF_DUTY request per agent not on duty
env.process(self.update_staffing())
def rostered(self):
return self.seats - len(self.absences)
def gone_home(self):
return sum(1 for absence in self.absences if absence.triggered)
def update_staffing(self):
while True:
current_hour = (self.env.now / 60) % 24
shift = max(hour for hour in self.schedule if hour <= current_hour)
target = self.schedule[shift]
# Send agents home: an absence goes ahead of every waiting caller
# and takes a seat the moment an agent finishes a call
while self.rostered() > target:
self.absences.append(self.agents.request(priority=OFF_DUTY))
# Bring agents back, latest absence first
while self.rostered() < target:
absence = self.absences.pop()
if absence.triggered:
self.agents.release(absence) # Back at their desk
else:
absence.cancel() # Still finishing a call; they stay
yield self.env.timeout(60) # Check hourly
def handle_call(self, patience):
with self.agents.request(priority=CALLER) as req:
result = yield req | self.env.timeout(patience)
if req in result:
yield self.env.timeout(random.expovariate(1/7))
def arrivals(env, centre, rates):
"""rates[h] is the mean number of calls per minute in hour h."""
while True:
hour = int(env.now // 60) % 24
yield env.timeout(random.expovariate(rates[hour]))
env.process(centre.handle_call(patience=random.expovariate(1/5)))
def watch(env, centre, start, minutes):
"""Print the floor once a minute from `start`."""
yield env.timeout(start)
for _ in range(minutes):
hours, mins = divmod(int(env.now), 60)
on_calls = centre.agents.count - centre.gone_home()
waiting = sum(1 for r in centre.agents.queue if r.priority == CALLER)
print(f"{hours:02}:{mins:02} rostered {centre.rostered():2} on calls {on_calls:2} "
f"gone home {centre.gone_home():2} callers waiting {waiting}")
yield env.timeout(1)
random.seed(42)
rates = [0.4] * 6 + [1.0] * 3 + [2.4] * 8 + [1.8] * 4 + [0.8] * 3
env = simpy.Environment()
centre = ScheduledCallCentre(env, {0: 5, 6: 10, 9: 20, 17: 15, 21: 8})
env.process(arrivals(env, centre, rates))
env.process(watch(env, centre, start=20 * 60 + 59, minutes=8))
env.run(until=24 * 60)
Output:
20:59 rostered 15 on calls 15 gone home 5 callers waiting 0
21:00 rostered 8 on calls 13 gone home 7 callers waiting 0
21:01 rostered 8 on calls 12 gone home 8 callers waiting 0
21:02 rostered 8 on calls 11 gone home 9 callers waiting 0
21:03 rostered 8 on calls 10 gone home 10 callers waiting 2
21:04 rostered 8 on calls 9 gone home 11 callers waiting 3
21:05 rostered 8 on calls 8 gone home 12 callers waiting 3
21:06 rostered 8 on calls 8 gone home 12 callers waiting 2
Watch the 9pm handover. The rota falls from 15 to 8, so seven more agents are due to leave. Two are free at that moment and go at once; the next five to finish a call go home as they hang up, and by 21:05 all twelve absent seats are held. Meanwhile a few callers wait, because an agent who finishes a call goes home rather than picking up the next one, which is exactly how a real shift change behaves. When the rota rises, the latest absences are released and those seats start taking calls immediately; an absence still waiting for a call to end is simply cancelled.
Two things to remember. agents.count now includes the agents who have gone home, so subtract them when you measure utilisation, as watch does. And keep OFF_DUTY a smaller number than every caller priority: with the VIP scheme above (1 and 5), 0 does the job.
Callback System
Instead of waiting, offer callback:
class CallCentreWithCallback:
def __init__(self, env, num_agents, callback_threshold):
self.env = env
self.agents = simpy.Resource(env, capacity=num_agents)
self.callback_threshold = callback_threshold
self.callback_queue = []
def handle_call(self, call_id, patience):
arrival = self.env.now
# If queue is long, offer callback
if len(self.agents.queue) > self.callback_threshold:
if random.random() < 0.7: # 70% accept callback
self.callback_queue.append({
'call_id': call_id,
'requested_at': self.env.now
})
print(f"Call {call_id} scheduled for callback")
return
# Normal queue handling
with self.agents.request() as req:
result = yield req | self.env.timeout(patience)
if req in result:
yield self.env.timeout(random.expovariate(1/7))
def process_callbacks(self):
while True:
yield self.env.timeout(1) # Check regularly
if self.callback_queue and self.agents.count < self.agents.capacity:
callback = self.callback_queue.pop(0)
self.env.process(self.make_callback(callback))
def make_callback(self, callback):
with self.agents.request() as req:
yield req
yield self.env.timeout(random.expovariate(1/7))
print(f"Callback to {callback['call_id']} completed")
Complete Call Centre Simulation
import simpy
import random
import numpy as np
class FullCallCentre:
def __init__(self, env, config):
self.env = env
self.config = config
self.agents = simpy.PriorityResource(env, capacity=config['agents'])
self.stats = {
'calls': [],
'service_levels': [],
'queue_lengths': []
}
def call(self, call_id, call_type, is_vip):
arrival = self.env.now
priority = 1 if is_vip else 5
patience = random.expovariate(1/self.config['mean_patience'])
record = {
'call_id': call_id,
'type': call_type,
'vip': is_vip,
'arrival': arrival
}
with self.agents.request(priority=priority) as req:
result = yield req | self.env.timeout(patience)
if req in result:
record['answered'] = True
record['wait'] = self.env.now - arrival
record['answered_in_target'] = record['wait'] <= self.config['target_wait']
# Handle time varies by type
handle_times = {'sales': 8, 'support': 10, 'billing': 5}
mean_handle = handle_times.get(call_type, 7)
handle = random.expovariate(1/mean_handle)
yield self.env.timeout(handle)
record['handle_time'] = handle
else:
record['answered'] = False
record['wait'] = patience
self.stats['calls'].append(record)
def arrivals(self):
call_id = 0
call_types = ['sales', 'support', 'billing']
type_probs = [0.3, 0.5, 0.2]
while True:
# Time-varying arrival rate
hour = (self.env.now / 60) % 24
if 9 <= hour <= 17:
rate = self.config['peak_rate']
else:
rate = self.config['off_peak_rate']
yield self.env.timeout(random.expovariate(rate))
call_type = random.choices(call_types, weights=type_probs)[0]
is_vip = random.random() < 0.1 # 10% VIP
self.env.process(self.call(call_id, call_type, is_vip))
call_id += 1
def monitor(self, interval=5):
while True:
self.stats['queue_lengths'].append({
'time': self.env.now,
'queue': len(self.agents.queue),
'busy': self.agents.count
})
yield self.env.timeout(interval)
def run(self, duration):
self.env.process(self.arrivals())
self.env.process(self.monitor())
self.env.run(until=duration)
def report(self):
calls = self.stats['calls']
answered = [c for c in calls if c['answered']]
abandoned = [c for c in calls if not c['answered']]
print("\n=== Call Centre Report ===")
print(f"Total calls: {len(calls)}")
print(f"Answered: {len(answered)}")
print(f"Abandoned: {len(abandoned)}")
print(f"Abandonment rate: {len(abandoned)/len(calls):.1%}")
if answered:
waits = [c['wait'] for c in answered]
print(f"\nWait time (answered):")
print(f" Mean: {np.mean(waits):.1f} mins")
print(f" 90th percentile: {np.percentile(waits, 90):.1f} mins")
in_target = [c for c in answered if c['answered_in_target']]
print(f"\nService level (target {self.config['target_wait']} mins):")
print(f" {len(in_target)/len(answered):.1%}")
# Run
random.seed(42)
env = simpy.Environment()
cc = FullCallCentre(env, {
'agents': 15,
'peak_rate': 2, # 2 calls/min at peak
'off_peak_rate': 0.5,
'mean_patience': 5, # 5 min average patience
'target_wait': 0.5 # 30 second target
})
cc.run(duration=480) # 8 hours
cc.report()
Summary
Call centre simulation captures:
- Variable arrival rates and call types
- Agent skills and priorities
- Customer patience and abandonment
- Service level metrics
- Staffing optimisation
Model the chaos. Meet your SLAs.