All articles

Model Musings

SimPy Store Explained: Managing Distinct Objects

Published
Reading time
5 min

Resources count slots. Containers track levels. Stores hold distinct items.

When you need to pass actual objects between processes (parts, messages, jobs), Store is your tool.

When to Use Store

Resource: “Give me any available server.”

Container: “Give me 10 litres of fuel.”

Store: “Give me the next item in the queue.”

import simpy

env = simpy.Environment()
store = simpy.Store(env, capacity=10)

Basic Operations

# Put an item
yield store.put("item1")

# Get an item (FIFO)
item = yield store.get()
print(item)  # "item1"

Items are objects. Strings, numbers, custom classes: anything.

Producer-Consumer Pattern

import simpy

def producer(env, store):
    for i in range(5):
        item = f"Product_{i}"
        yield store.put(item)
        print(f"Produced {item} at {env.now}")
        yield env.timeout(2)

def consumer(env, store):
    while True:
        item = yield store.get()
        print(f"Consumed {item} at {env.now}")
        yield env.timeout(3)

env = simpy.Environment()
store = simpy.Store(env)
env.process(producer(env, store))
env.process(consumer(env, store))
env.run(until=20)

Output:

Produced Product_0 at 0
Consumed Product_0 at 0
Produced Product_1 at 2
Consumed Product_1 at 3
Produced Product_2 at 4
Consumed Product_2 at 6
Produced Product_3 at 6
Produced Product_4 at 8
Consumed Product_3 at 9
Consumed Product_4 at 12

The consumer is the slower of the two (3 time units against 2), so items start to wait in the store: Product_3 is made at 6 but not consumed until 9. The store is the buffer between them, and it holds the actual products in the order they arrived.

Blocking Behaviour

put() blocks when store is full:

store = simpy.Store(env, capacity=3)
yield store.put("a")  # OK
yield store.put("b")  # OK
yield store.put("c")  # OK
yield store.put("d")  # Blocks until space available

get() blocks when store is empty:

store = simpy.Store(env)
item = yield store.get()  # Blocks until something is put

Custom Objects

Stores shine with complex objects:

class Part:
    def __init__(self, part_id, part_type, priority):
        self.part_id = part_id
        self.part_type = part_type
        self.priority = priority

def producer(env, store):
    for i in range(10):
        part = Part(i, "widget", priority=i % 3)
        yield store.put(part)
        yield env.timeout(1)

def consumer(env, store):
    while True:
        part = yield store.get()
        print(f"Processing part {part.part_id} ({part.part_type})")
        yield env.timeout(2)

Checking Store State

store.items      # List of items currently in store
store.capacity   # Maximum capacity (inf if not specified)
len(store.items) # Current count

Unlimited Capacity

By default, stores have infinite capacity:

store = simpy.Store(env)  # No limit

For bounded buffers, specify capacity:

store = simpy.Store(env, capacity=50)

FilterStore: Selective Getting

What if you need a specific type of item? Use FilterStore:

store = simpy.FilterStore(env, capacity=10)

# Put various items
yield store.put({'type': 'red', 'id': 1})
yield store.put({'type': 'blue', 'id': 2})
yield store.put({'type': 'red', 'id': 3})

# Get only red items
red_item = yield store.get(lambda item: item['type'] == 'red')
print(red_item)  # {'type': 'red', 'id': 1}

The filter function decides which items match.

PriorityStore: Priority-Based Getting

Get items by priority:

from simpy import PriorityItem

store = simpy.PriorityStore(env, capacity=10)

yield store.put(PriorityItem(priority=3, item="low"))
yield store.put(PriorityItem(priority=1, item="high"))
yield store.put(PriorityItem(priority=2, item="medium"))

item = yield store.get()  # PriorityItem(priority=1, item='high')

Lower priority number = higher priority (retrieved first). Note that get() hands back the whole PriorityItem; the payload you put in is its .item, here 'high'.

Real-World Example: Job Queue

import random
import simpy

class Job:
    def __init__(self, job_id, job_type, duration):
        self.job_id = job_id
        self.job_type = job_type
        self.duration = duration
        self.created = None

def job_creator(env, job_queue):
    job_id = 0
    while True:
        job = Job(job_id, "standard", random.uniform(5, 15))
        job.created = env.now
        yield job_queue.put(job)
        print(f"Job {job_id} created at {env.now:.1f}")
        job_id += 1
        yield env.timeout(random.expovariate(1/3))

def worker(env, name, job_queue):
    while True:
        job = yield job_queue.get()
        wait_time = env.now - job.created
        print(f"{name} starts job {job.job_id} (waited {wait_time:.1f})")
        yield env.timeout(job.duration)
        print(f"{name} finished job {job.job_id}")

random.seed(42)
env = simpy.Environment()
job_queue = simpy.Store(env)
env.process(job_creator(env, job_queue))
env.process(worker(env, "Worker1", job_queue))
env.process(worker(env, "Worker2", job_queue))
env.run(until=20)

Output:

Job 0 created at 0.0
Worker1 starts job 0 (waited 0.0)
Job 1 created at 0.1
Worker2 starts job 1 (waited 0.0)
Job 2 created at 0.8
Job 3 created at 4.2
Job 4 created at 4.5
Job 5 created at 4.6
Job 6 created at 6.7
Job 7 created at 7.4
Worker2 finished job 1
Worker2 starts job 2 (waited 7.0)
Job 8 created at 9.7
Worker1 finished job 0
Worker1 starts job 3 (waited 7.2)
Job 9 created at 12.4
Job 10 created at 12.4
Job 11 created at 16.0
Job 12 created at 16.5
Job 13 created at 17.7
Job 14 created at 18.0

Two workers taking ten minutes a job on average finish one every five minutes between them, while a new job arrives every three. The store never objects: with no capacity set it simply fills, and by the end of the run eleven jobs are waiting. That silence is worth remembering when you size a real buffer.

Store vs Resource

FeatureResourceStore
What it holdsSlotsObjects
Put operationrequest()put(item)
Get operationN/A (release)get()
Items returnedNoYes
Custom itemsNoYes

Use Resource when you just need capacity. Use Store when you need the actual items.

Store vs Container

FeatureContainerStore
What it tracksLevels/amountsDistinct items
Put amountput(quantity)put(item)
Get amountget(quantity)get() (one item)
Items areFungibleDistinct

Use Container for fuel, inventory levels. Use Store for parts, messages, jobs.

Common Patterns

Message Passing

mailbox = simpy.Store(env)

def sender(env, mailbox):
    yield mailbox.put({'type': 'greeting', 'content': 'Hello'})

def receiver(env, mailbox):
    message = yield mailbox.get()
    print(f"Received: {message['content']}")

Conveyor/Buffer

buffer = simpy.Store(env, capacity=20)

def machine_a(env, buffer):
    while True:
        part = produce_part()
        yield buffer.put(part)
        yield env.timeout(production_time)

def machine_b(env, buffer):
    while True:
        part = yield buffer.get()
        process(part)
        yield env.timeout(processing_time)

Summary

Store:

  • Holds distinct items, not slots or levels
  • FIFO by default
  • Use FilterStore for selective gets
  • Use PriorityStore for priority-based gets
  • Perfect for jobs, messages, parts, orders

Pass objects between processes. Use Store.

Next Steps

Ready to build a model of your own?

The free SimPy Handbook covers the foundations; the Simulation Bootcamp covers everything else, from first principles to models a business will act on.