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 6: The Streamlit Apps

Two dashboards

The system has two Streamlit dashboards. The live operations dashboard (app.py, port 8501) shows current shipment status, active disruptions, rerouted shipments and a disruption events log. The analytics dashboard (analytics_app.py, port 8502) shows status breakdown, delay trends, warehouse health, shipment flow, supplier performance and SLA breaches, updated every 30 seconds from the Snowflake warehouse.

Install the app dependencies from requirements.txt first with pip install -r requirements.txt, then run the apps alongside the simulator. Stop both apps before restarting the simulator, because its startup reset empties the tables they read from:

streamlit run app.py
streamlit run analytics_app.py --server.port 8502

The live operations dashboard

Auto-refresh

The live operations dashboard refreshes every 10 seconds. streamlit-autorefresh handles this with a single call near the top of the script:

st_autorefresh(interval=REFRESH_SECONDS * 1000)

Every 10 seconds the entire script re-runs from top to bottom, re-querying Snowflake Postgres for the latest shipment and disruption data.

Connections

All queries read from Snowflake Postgres using psycopg2. Each query opens its own connection and closes it as soon as the query finishes, using contextlib.closing. (A psycopg2 connection used in a plain with block ends the transaction but stays open.) @st.cache_data caches each result for just under the refresh interval, which avoids hammering the database on every rerun but still fetches fresh data on each refresh:

CACHE_TTL_SECONDS = REFRESH_SECONDS - 1

@st.cache_data(ttl=CACHE_TTL_SECONDS)
def fetch_status_counts():
    with closing(get_conn()) as conn:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT status, COUNT(*) AS count
                FROM shipments
                GROUP BY status
            """)
            rows = cur.fetchall()
    return {row[0]: row[1] for row in rows}

The disruption banner

The most prominent element on the dashboard is the disruption banner – a full-width colored box at the top of the page. It shows green for normal operations, red when a warehouse is offline and amber immediately after a restore. After a configurable grace period (RESTORED_GRACE_SECONDS, defaulting to 60 seconds), the banner returns to green even if the last event in disruption_events was a restore.

The current phase is determined by the most recent row in disruption_events:

cur.execute("""
    SELECT event_type, warehouse_id, recorded_at
    FROM disruption_events
    ORDER BY recorded_at DESC
    LIMIT 1
""")

If the last event was disrupted, the banner is red. If it was restored and fewer than RESTORED_GRACE_SECONDS have elapsed, the banner is amber. Otherwise it’s green.

Status metric tiles

Four metric tiles below the banner show shipment counts for each status – departed, in_transit, delayed and delivered. Each tile uses the same color palette as the analytics dashboard’s doughnut chart for consistency across both apps.

Delayed shipments by warehouse

A vertical bar chart shows delayed shipment counts per warehouse, using a Reds colorscale. Warehouses with more delayed shipments appear with a deeper red fill, making the worst-performing warehouses immediately visible.

Recent rerouted shipments

A table of up to ten rows shows the most recent rerouted shipments with the original warehouse, the alternative warehouse and the timestamp. This table is the most direct way to see the disruption routing in action.

Disruption events log

A second table of up to ten rows at the bottom of the page shows the most recent rows from disruption_events – every warehouse disruption and restore, with timestamps. This gives an at-a-glance history of disruption activity during the current simulator run.

The analytics dashboard

Auto-refresh and sync

The analytics dashboard refreshes every 30 seconds. On each refresh it syncs new rows from shipments in Snowflake Postgres into shipment_history in the Snowflake warehouse using the incremental watermark pattern from Chapter 4:

sf_cur.execute("SELECT MAX(recorded_at) FROM shipment_history")
last_synced_at = sf_cur.fetchone()[0] or datetime(1970, 1, 1, tzinfo=timezone.utc)

Only rows newer than the watermark are pulled and appended. The first refresh after a long simulator run may sync thousands of rows; subsequent refreshes sync only the handful of rows that arrived in the last 30 seconds.

The table is created if it’s missing, with CREATE TABLE IF NOT EXISTS, so a dropped table doesn’t stop the app. The database, schema and compute warehouse from Chapter 4 must already exist:

sf_cur.execute("""
    CREATE TABLE IF NOT EXISTS shipment_history (...)
""")

Connections

The analytics dashboard connects to two systems:

  1. Snowflake Postgres – for the incremental sync source.
  2. Snowflake warehouse – for all analytics queries.

The Snowflake connection is opened at the start of each refresh and closed in a finally block once the queries finish, so it’s released even if a query fails. The Postgres connection is opened only for the sync. It’s closed in a finally block as soon as the new rows have been read, before they’re inserted into the warehouse:

pg_conn = get_pg_conn()
try:
    with pg_conn.cursor() as pg_cur:
        pg_cur.execute(...)
        rows = pg_cur.fetchall()
finally:
    pg_conn.close()

The Snowflake warehouse compute is an X-SMALL instance with auto-suspend, so it only consumes credits while queries are running.

Status breakdown

The first chart is a doughnut using go.Pie with hole=0.4. The same STATUS_COLORS dictionary is used in both apps for consistency (the notebook calls it COLOR_MAP):

STATUS_COLORS = {
    "departed":   "#4C9BE8",
    "in_transit": "#2A9D8F",
    "delayed":    "#E63946",
    "delivered":  "#57CC99",
}

A dual-axis line chart shows delayed shipment count per minute on the left axis and average delay duration in minutes on the right axis. The dashed line for average delay makes it easy to distinguish the two series without relying on color alone. The first and last points cover partial minutes, so the count often looks lower at both ends of the line.

Warehouse health heatmap

A go.Heatmap shows each warehouse’s health score – the percentage of its shipments that were not delayed – on a red-to-orange-to-green colorscale. The simulator assigns delays at random, independent of disruptions, so differences between warehouses are noise in the synthetic data. The scale is fixed at 0 to 100 so colors always mean the same thing, which means every warehouse lands in the green range with this synthetic data. With real data the heatmap would be a quick way to spot unhealthy warehouses.

Shipment flow sankey

A go.Sankey diagram shows the 50 largest flows of shipments from suppliers to warehouses. The left nodes are suppliers (blue) and the right nodes are warehouses (teal). The width of each link is proportional to the number of shipments between that supplier and warehouse. The chart uses each shipment’s original warehouse, so rerouted shipments are counted against the warehouse that was disrupted. Because the simulator picks suppliers and warehouses independently, the flows between any supplier and warehouse are similar in size, so the top 50 are close to an arbitrary selection and the chart shows a dense web.

Top suppliers and SLA breach

Two horizontal bar charts sit side by side at the bottom of the dashboard. The first ranks the ten suppliers with the highest delay rate using a Reds colorscale. The second ranks the ten warehouses with the highest SLA breach rate – the percentage of shipments where delay_minutes exceeded the threshold – using an Oranges colorscale. Both charts exclude nodes with fewer than three shipments to avoid misleading results from small samples. Because the simulator assigns delays at random, the rankings show how the dashboard works rather than real patterns.

The optional analytics notebook

The chapter’s notebook, 06_analytics.ipynb, is a one-time, static version of the analytics. It loads every row from shipments in Snowflake Postgres into a fresh scratch table in the Snowflake warehouse, then runs five analytical queries and charts them:

  1. Status breakdown.
  2. Delay trends over time.
  3. Rerouted shipments by alternative warehouse, with average delay for rerouted versus normal shipments.
  4. Top suppliers by delay rate.
  5. SLA breach rate, overall and by warehouse.

The SLA queries use a threshold set once in the configuration cell and passed in as a bind parameter:

SLA_THRESHOLD_MINUTES = 60

sf_cursor.execute("""
    SELECT
        warehouse_id,
        COUNT(*) AS total,
        SUM(CASE WHEN delay_minutes > %s THEN 1 ELSE 0 END) AS breaches
    FROM shipment_history_nb
    GROUP BY warehouse_id
""", (SLA_THRESHOLD_MINUTES,))

Running the notebook against the 1,000 shipments from the Chapter 5 run produces output like this:

Status breakdown:
    status  count  pct
in_transit    433 43.3
  departed    254 25.4
   delayed    166 16.6
 delivered    147 14.7

SLA threshold  : 60 minutes
Total          : 1,000
Breaches       : 133
Breach rate    : 13.3%

The status counts match the Chapter 5 verification output.

Unlike the dashboard, the notebook does a full load rather than an incremental sync. It writes to its own scratch table, shipment_history_nb, and drops that table in its teardown, so it can run alongside the Streamlit apps without touching the shipment_history table the analytics app uses. Stop the simulator before running it so the data don’t change while it loads.

Gotchas

use_container_width deprecated. Streamlit deprecated use_container_width in favor of width='stretch' in recent versions. Use st.plotly_chart(fig, width='stretch') rather than use_container_width=True.

streamlit-autorefresh silent argument removed. The silent keyword argument was removed from st_autorefresh in recent versions. Use st_autorefresh(interval=N) with no additional arguments.

@st.cache_data and live data. Setting ttl too high on cached queries means the dashboard shows stale data. Set ttl slightly below the refresh interval so that each auto-refresh fetches fresh data from the database.

Snowflake NUMBER columns arrive as Decimal. The Snowflake connector returns values such as rates rounded to one decimal place as Python Decimal objects. pandas stores them as object, so Plotly treats a column passed to color as categories and ignores color_continuous_scale. The bars come out in a pastel rainbow instead of a Reds or Oranges gradient. Cast the column with .astype(float) after building the DataFrame.

Charts fade during a refresh. Streamlit dims elements while the script reruns, and the analytics script syncs and runs six queries on every refresh. A screenshot taken mid-refresh shows faded charts, so wait for the page to settle first.

Keep one browser tab open on the analytics dashboard. Every open session runs its own sync. Two tabs read the same watermark and insert the same rows, which duplicates data in shipment_history. If that happens, restart the simulator, which resets the table, and keep a single tab open.

Snowflake warehouse auto-suspend. The X-SMALL compute warehouse suspends after 60 seconds of inactivity. The first query after a suspension has a cold-start delay of a few seconds while the warehouse resumes. This is normal and expected – the analytics dashboard shows a spinner while the sync and queries run.

mogrify doesn’t exist on the Snowflake connector. mogrify is a psycopg2 method. The Snowflake cursor has no such method, so use executemany with %s placeholders for batch inserts into shipment_history, as in Chapter 4.