Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 5: The Simulator

What the simulator does

The simulator generates synthetic shipment events, publishes them to a Confluent Cloud Kafka topic and consumes them back in real time. For each consumed event, it writes the shipment to both Neo4j and Snowflake Postgres – and if the shipment passes through a warehouse that’s currently offline, it reroutes it through an alternative warehouse found via the Neo4j graph.

The simulator has four responsibilities:

  1. Publish synthetic shipment events to the shipment-events Kafka topic.
  2. Consume those events from the same topic.
  3. Inject warehouse disruptions at random intervals and restore them after a random duration.
  4. Write every event to Neo4j and Snowflake Postgres, with rerouting applied where needed.

It runs directly in a Jupyter notebook cell. The loop stops on keyboard interrupt, after N_EVENTS events when that’s a positive number or automatically after MAX_RUNTIME_SECONDS.

The Neo4j graph (Chapter 2), the Snowflake Postgres tables (Chapter 3) and the Snowflake warehouse table (Chapter 4) must be in place before you start.

Starting clean

Every run starts by resetting the live state in all three systems, so you never have to clear anything by hand between runs:

  • Snowflake Postgres – the shipments and disruption_events tables are truncated.
  • Neo4j – all Shipment nodes are deleted in batches of 1000 and the active flag is removed from every warehouse. The supply chain graph itself is left alone.
  • Snowflake warehouse – the shipment_history table is truncated, so the analytics layer starts empty too.
with neo4j_driver.session() as session:
    session.run("MATCH (w:Warehouse) REMOVE w.active")
    deleted = 0
    while True:
        n = session.run("""
            MATCH (sh:Shipment)
            WITH sh LIMIT 1000
            DETACH DELETE sh
            RETURN count(*) AS n
        """).single()["n"]
        if n == 0:
            break
        deleted += n

The cell prints a summary of what it cleared. This is the output from a second run, after the previous run had left 1,975 shipments behind:

Postgres table shipments truncated.
Postgres table disruption_events truncated.
Neo4j: removed 1,975 Shipment nodes and cleared all active flags.
Snowflake warehouse: shipment_history truncated (if it exists).

This deletes all shipment data from the previous run, so stop the Streamlit apps before restarting the simulator.

The Kafka Producer and Consumer

The simulator uses confluent-kafka for both producing and consuming events. The producer publishes one event per iteration of the loop. The consumer reads one event back before writing to the databases. This tight produce-consume loop ensures that what gets written to Neo4j and Snowflake Postgres is exactly what landed in Kafka – the same event, with the same timestamp.

Both producer and consumer authenticate with SASL/SSL:

producer = Producer({
    "bootstrap.servers": CONFLUENT_BOOTSTRAP_SERVERS,
    "security.protocol": "SASL_SSL",
    "sasl.mechanisms":   "PLAIN",
    "sasl.username":     CONFLUENT_API_KEY,
    "sasl.password":     CONFLUENT_API_SECRET,
})

The consumer uses a fixed group.id and auto.offset.reset = "earliest", so on its first run it reads from the beginning of the topic. On later runs it resumes from the last committed offset.

Generating shipment events

Each shipment event is generated from a seeded random number generator, so the mix of suppliers, warehouses and statuses is broadly repeatable between runs. The shipment IDs are random UUIDs and the exact sequence can shift if the consumer poll returns nothing for an iteration, so two runs won’t be identical:

rng  = np.random.default_rng(RANDOM_SEED)

def make_shipment_event():
    status = str(rng.choice(STATUSES, p=STATUS_WEIGHTS))
    return {
        "shipment_id":    str(uuid.uuid4()),
        "supplier_id":    str(rng.choice(SUPPLIER_IDS)),
        "warehouse_id":   str(rng.choice(WAREHOUSE_IDS)),
        "dist_center_id": str(rng.choice(DIST_CENTER_IDS)),
        "retailer_id":    str(rng.choice(RETAILER_IDS)),
        "status":         status,
        "timestamp":      time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "delay_minutes":  int(rng.integers(15, 240)) if status == "delayed" else 0,
    }

Status weights are [0.25, 0.45, 0.15, 0.15] for departed, in_transit, delayed and delivered. Roughly 15% of shipments are delayed, which produces enough delay data for the analytics charts without overwhelming the status breakdown. Delays are assigned at random, independent of disruptions, warehouses and suppliers. Disruptions affect routing, not delay, so any differences you see between warehouses or suppliers in the analytics are noise in the synthetic data.

The events are synthetic: the supplier, warehouse, distribution center and retailer are chosen independently, so an event doesn’t always follow a real path through the graph. That’s fine for the demonstration, because the routing logic only needs to know which warehouse an event used.

The disruption lifecycle

Warehouse disruptions fire randomly during the simulation. Two configuration parameters control the timing:

  • DISRUPTION_INTERVAL_MIN / DISRUPTION_INTERVAL_MAX – how many events pass between disruptions.
  • DISRUPTION_DURATION_MIN / DISRUPTION_DURATION_MAX – how long each disruption lasts in events.

Both the gap between disruptions and the duration of each disruption are drawn randomly from these ranges using the seeded rng. Disruptions look unpredictable but the overall pattern is broadly repeatable.

The first disruption always hits W003, which is the warehouse used in the Chapter 2 graph verification test. Subsequent disruptions target a randomly chosen warehouse drawn after each restore. Because the choice is random, the same warehouse can be hit more than once in a row.

The lifecycle has three phases:

normal -> disrupted -> restored -> disrupted -> restored -> ...

Transitioning to disrupted sets the warehouse’s active property to false in Neo4j and writes a disrupted row to disruption_events in Snowflake Postgres. Transitioning to restored removes the active property and writes a restored row. If you stop the simulator during a disruption, the finally block restores the offline warehouse and logs the restore, so the graph and the dashboard banner aren’t left in a disrupted state.

Rerouting

When the simulator is in the disrupted phase and a consumed event routes through the disrupted warehouse, it calls find_alternative_route() to ask Neo4j for a path that avoids it:

if phase == "disrupted" and consumed["warehouse_id"] == current_disruption:
    alt_warehouse_id = find_alternative_route(
        session,
        consumed["supplier_id"],
        consumed["retailer_id"],
    )

The rerouting query is the one from Chapter 2: a variable-length path with a WHERE NONE() filter, ordered by total shipping cost. Every supplier-to-retailer path has exactly three hops, so hop count can’t rank the alternatives and cost has to:

def find_alternative_route(session, supplier_id, retailer_id):
    result = session.run("""
        MATCH (s:Supplier {id: $supplier_id}),
              (r:Retailer {id: $retailer_id})
        MATCH path = (s)-[:SHIPS_TO*1..6]->(r)
        WHERE NONE(
            n IN nodes(path)
            WHERE n:Warehouse AND coalesce(n.active, true) = false
        )
        WITH path,
             reduce(total = 0.0, rel IN relationships(path) | total + rel.cost) AS total_cost
        ORDER BY total_cost ASC
        LIMIT 1
        RETURN [n IN nodes(path) | n.id] AS node_ids
    """,
        supplier_id = supplier_id,
        retailer_id = retailer_id,
    )
    record = result.single()
    if record is None:
        return None
    # The warehouse is always the second node in the path
    return record["node_ids"][1]

If an alternative is found, alt_warehouse_id is passed to both write_to_neo4j and write_to_postgres, which record the rerouting in both systems. If no alternative exists, the function returns None and the shipment is written without being rerouted.

Writing to Neo4j and Snowflake Postgres

Each consumed event is written to both systems before the loop advances.

Neo4j – a MERGE on shipment_id creates or updates the Shipment node and its four relationships. If the shipment was rerouted, the VIA_WAREHOUSE relationship points to the alternative warehouse rather than the original:

MERGE (sh:Shipment {shipment_id: $shipment_id})
SET sh.status        = $status,
    sh.delay_minutes = $delay_minutes,
    sh.timestamp     = $timestamp,
    sh.rerouted      = $rerouted

Neo4j writes use write_to_neo4j_with_retry(), which opens a fresh session per attempt and retries up to twice on connection failure. This handles the session timeouts that Aura enforces on long-running connections.

Snowflake Postgres – an INSERT ... ON CONFLICT DO UPDATE makes the write an idempotent upsert. Every event has a fresh UUID, so a conflict only happens if Kafka redelivers a message. When it does, the update overwrites the routing fields instead of failing with a duplicate key error:

INSERT INTO shipments (...)
ON CONFLICT (shipment_id) DO UPDATE
    SET rerouted         = EXCLUDED.rerouted,
        alt_warehouse_id = EXCLUDED.alt_warehouse_id,
        status           = EXCLUDED.status

The display

The simulator refreshes its output every PRINT_EVERY events, showing the current phase, the latest event and the running status breakdown:

Events processed : 1000
Phase            : Restored -- W004 back online
Rerouted         : 16
Refresh every    : 10

Latest event:
  -> 38988ea7... S008 -> W001 -> DC007 -> R001 [departed]

Last reroute:
  9a95b4b5... W004 -> W002

Status breakdown:
  departed     : 254
  in_transit   : 433
  delayed      : 166
  delivered    : 147
Total events processed : 1000
Total rerouted         : 16

These outputs come from a run with N_EVENTS set to 1000, so the loop stops by itself. The two total lines come from the finally block, which also runs when you interrupt the loop.

The !! prefix marks delayed events. The -> prefix marks normal events.

Runtime limit

The simulator stops automatically after MAX_RUNTIME_SECONDS even when N_EVENTS is set to -1 for continuous operation:

start_time = time.time()
while (N_EVENTS == -1 or counter < N_EVENTS) and \
      (time.time() - start_time < MAX_RUNTIME_SECONDS):
    ...

This ensures the simulator doesn’t run indefinitely if left unattended.

Verifying the result

Two verify cells at the end of the notebook check that both systems agree. The first connects to Neo4j and counts Shipment nodes by status:

Neo4j -- Shipment nodes by status:
  departed     : 254
  in_transit   : 433
  delayed      : 166
  delivered    : 147

  Total         : 1000
  Rerouted      : 16

The second connects to Snowflake Postgres and prints the same summary for the shipments table, followed by every row of disruption_events:

Snowflake Postgres -- shipments table by status:
  departed     : 254
  in_transit   : 433
  delayed      : 166
  delivered    : 147

  Total         : 1000
  Rerouted      : 16

Snowflake Postgres -- disruption_events:
  Warehouse    Event        Timestamp
  W003         disrupted    2026-10-17 18:02:22.552081+00:00
  W003         restored     2026-10-17 18:03:27.962843+00:00
  W003         disrupted    2026-10-17 18:05:14.694457+00:00
  W003         restored     2026-10-17 18:05:53.010754+00:00
  W004         disrupted    2026-10-17 18:07:55.396563+00:00
  W004         restored     2026-10-17 18:08:47.601405+00:00

The totals and rerouted counts match across the two systems and match the simulator’s final totals. This run produced six disruption rows. A longer run produces more.

Gotchas

Long-lived Neo4j Aura sessions time out. Aura closes idle connections after a period of inactivity, throwing SessionExpired. The fix is to open a fresh session per operation rather than holding one open for the duration of the loop. All Neo4j calls in the simulator use short-lived with neo4j_driver.session() as session: blocks and the main shipment write uses write_to_neo4j_with_retry() to handle dropped connections automatically.

Very few rerouted shipments. If the disruption window is too short relative to the event rate and the number of warehouses, very few shipments will pass through the disrupted warehouse during the disruption. Increase DISRUPTION_DURATION_MAX or decrease DISRUPTION_INTERVAL_MIN to produce more rerouting events. Some shipments also have no alternative route, in which case they’re written without being rerouted.

ON CONFLICT DO NOTHING would discard routing changes. If Kafka redelivers a message, DO NOTHING keeps the existing row and silently drops the new routing fields. Use DO UPDATE and set the rerouting columns explicitly. Note that the update doesn’t change recorded_at, so the Chapter 4 sync, which pulls only rows newer than its watermark, won’t copy the changed row to the warehouse.

Rerun the Kafka setup after stopping the loop. The loop’s finally block closes the consumer and restores any warehouse that is still offline. To run the loop again, rerun the cell that creates the producer and consumer first.

Tables are truncated, not dropped, at simulator startup. The shipments and disruption_events tables are owned by the Chapter 3 notebook, and shipment_history by the Chapter 4 notebook. The simulator truncates them at startup rather than dropping and recreating them. Re-running the Chapter 3 or Chapter 4 notebook after the simulator has run will drop and recreate the tables, clearing all data.

Stop the apps before restarting the simulator. The startup reset empties the tables the dashboards read from. If the analytics app is syncing at that moment, it can leave a half-reset state. Stop both apps, restart the simulator, then start the apps again.