Model Musings
SimPy PriorityResource Explained: When Some Requests Matter More
- Published
- Reading time
- 5 min
Not all customers are equal. Not all jobs are equally urgent. PriorityResource lets important requests jump the queue.
Basic Resource vs PriorityResource
Regular Resource: First come, first served. Fair. Simple.
PriorityResource: Lower priority number goes first. VIPs jump the queue.
import simpy
env = simpy.Environment()
resource = simpy.PriorityResource(env, capacity=1)
How Priority Works
Lower numbers = higher priority.
import simpy
def requester(env, name, resource, priority):
with resource.request(priority=priority) as req:
yield req
print(f"{name} (priority {priority}) gets resource at {env.now}")
yield env.timeout(5)
env = simpy.Environment()
resource = simpy.PriorityResource(env, capacity=1)
# First request (lowest priority)
env.process(requester(env, "Low", resource, priority=10))
# Second request (highest priority)
env.process(requester(env, "High", resource, priority=1))
# Third request (medium priority)
env.process(requester(env, "Medium", resource, priority=5))
env.run()
Output:
Low (priority 10) gets resource at 0
High (priority 1) gets resource at 5
Medium (priority 5) gets resource at 10
“Low” was first, so it got the resource. But when it released, “High” jumped ahead of “Medium” in the queue.
Real-World Examples
Emergency Department Triage
import simpy
PRIORITY = {
'critical': 1,
'urgent': 2,
'standard': 3,
'minor': 4
}
def patient(env, name, doctor, severity):
print(f"{name} ({severity}) arrives at {env.now}")
with doctor.request(priority=PRIORITY[severity]) as req:
yield req
print(f"{name} sees doctor at {env.now}")
yield env.timeout(10)
env = simpy.Environment()
doctor = simpy.PriorityResource(env, capacity=1)
env.process(patient(env, "Alice", doctor, "minor"))
env.process(patient(env, "Bob", doctor, "critical"))
env.process(patient(env, "Charlie", doctor, "urgent"))
env.run()
Output:
Alice (minor) arrives at 0
Bob (critical) arrives at 0
Charlie (urgent) arrives at 0
Alice sees doctor at 0
Bob sees doctor at 10
Charlie sees doctor at 20
Alice, the minor case, is seen first. She reached a free doctor before anyone else asked, and a PriorityResource never takes a doctor away from a patient; that is PreemptiveResource’s job. Priority decides who is next in the queue, so when Alice is done, Bob (critical) goes ahead of Charlie (urgent).
Job Scheduling
import simpy
def job(env, name, machine, priority, duration):
with machine.request(priority=priority) as req:
yield req
print(f"{name} starts at {env.now}")
yield env.timeout(duration)
env = simpy.Environment()
machine = simpy.PriorityResource(env, capacity=1)
# Customer jobs (low priority)
env.process(job(env, "Routine", machine, priority=10, duration=5))
# Expedited order (high priority)
env.process(job(env, "Rush", machine, priority=1, duration=5))
env.run()
Output:
Routine starts at 0
Rush starts at 5
The same rule again: Routine found the machine idle and started, so Rush waits its turn, but only behind the job already running. Any other routine work queued by then would wait behind Rush.
Ties: Same Priority
When priorities are equal, FIFO applies:
env.process(requester(env, "A", resource, priority=5))
env.process(requester(env, "B", resource, priority=5))
env.process(requester(env, "C", resource, priority=5))
A, B and C get served in order, with no favouritism among equals.
Dynamic Priority
Priority is set at request time, not at process creation, so work it out at the moment you ask:
def smart_customer(env, resource, arrived):
# Someone who has already spent a long time in the system goes first
priority = 1 if env.now - arrived > 10 else 5
with resource.request(priority=priority) as req:
yield req
# ...
Once the request is made, its priority is fixed: changing it afterwards does not move the request in the queue. To implement ageing (raising the priority the longer someone waits), cancel the request and make a new one with the higher priority.
Priority vs Regular Resource
| Feature | Resource | PriorityResource |
|---|---|---|
| Queue order | FIFO | Priority, then FIFO |
| Request syntax | request() | request(priority=n) |
| Fair | Yes | No (by design) |
When to Use PriorityResource
Use when:
- Some entities genuinely deserve faster service
- SLAs require tiered response times
- Business value varies by customer/job type
- You’re modelling emergency services or triage
Don’t use when:
- Fairness matters
- Priority abuse is a concern (low priority starves)
- The real system doesn’t prioritise
Starvation Warning
Priority queues can starve low-priority requests:
def high_priority_flood(env, resource):
"""Continuous stream of high-priority requests"""
while True:
yield env.timeout(1)
env.process(quick_job(env, resource, priority=1))
If high-priority requests keep arriving, low-priority requests wait forever.
Solutions:
- Age-based priority boosting
- Reserved capacity for low priority
- Maximum wait time enforcement
Collecting Statistics by Priority
wait_times = {1: [], 2: [], 3: []}
def job(env, resource, priority):
arrival = env.now
with resource.request(priority=priority) as req:
yield req
wait_times[priority].append(env.now - arrival)
yield env.timeout(5)
# After simulation
for p, times in wait_times.items():
avg = sum(times) / len(times) if times else 0
print(f"Priority {p} average wait: {avg:.2f}")
PriorityResource vs PreemptiveResource
PriorityResource: High priority jumps the queue but waits for current user to finish.
PreemptiveResource: High priority can interrupt and take over immediately.
The difference is not insignificant. PriorityResource respects current users. PreemptiveResource doesn’t.
Example: Call Centre with VIP Line
import random
import simpy
def caller(env, name, agents, is_vip):
priority = 1 if is_vip else 5
arrival = env.now
print(f"{env.now:5.1f}: {name} ({'VIP' if is_vip else 'Regular'}) calls")
with agents.request(priority=priority) as req:
yield req
wait = env.now - arrival
print(f"{env.now:5.1f}: {name} answered after {wait:.1f} (priority {priority})")
yield env.timeout(random.uniform(3, 8))
def calls(env, agents):
for i in range(10):
is_vip = random.random() < 0.2 # 20% VIP
env.process(caller(env, f"Caller{i}", agents, is_vip))
yield env.timeout(random.expovariate(1))
random.seed(42)
env = simpy.Environment()
agents = simpy.PriorityResource(env, capacity=2)
env.process(calls(env, agents))
env.run()
Output:
0.0: Caller0 (Regular) calls
0.0: Caller0 answered after 0.0 (priority 5)
0.0: Caller1 (Regular) calls
0.0: Caller1 answered after 0.0 (priority 5)
1.4: Caller2 (Regular) calls
1.4: Caller3 (Regular) calls
1.5: Caller4 (Regular) calls
2.2: Caller5 (VIP) calls
2.4: Caller6 (Regular) calls
3.2: Caller7 (Regular) calls
4.1: Caller8 (Regular) calls
4.1: Caller9 (Regular) calls
4.4: Caller5 answered after 2.2 (priority 1)
6.4: Caller2 answered after 5.0 (priority 5)
9.1: Caller3 answered after 7.6 (priority 5)
10.2: Caller4 answered after 8.7 (priority 5)
14.9: Caller6 answered after 12.5 (priority 5)
16.9: Caller7 answered after 13.7 (priority 5)
18.3: Caller8 answered after 14.3 (priority 5)
20.3: Caller9 answered after 16.3 (priority 5)
The one VIP, Caller5, rings at 2.2 with three regular callers already holding. The next agent to come free takes the VIP at 4.4, and Caller2, who has been waiting since 1.4, holds on until 6.4. The arrivals loop lives in its own process (calls) because yield only works inside a generator that SimPy is running.
Summary
PriorityResource:
- Serves lower priority numbers first
- FIFO among equal priorities
- Doesn’t interrupt current service
- Use for triage, tiered SLAs, job scheduling
When priority matters, use PriorityResource.