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 4: The Analytics Layer

What the analytics layer does

Snowflake Postgres in Chapter 3 gives us a fast operational store for live shipment events. But it’s optimized for writes and point reads, not for the heavier aggregation queries that answer questions like “which warehouses are causing the most delays over time?” or “how has the average delay changed across the last hour?”

For those questions we need an analytics layer – somewhere to accumulate historical data and run aggregations without affecting the operational store. The Snowflake warehouse is that layer.

The analytics layer needs to:

  • Store a full history of shipment events as they accumulate over a run.
  • Stay current with new events arriving from Snowflake Postgres.
  • Serve the analytics Streamlit dashboard with the six charts it displays on every refresh.
  • Handle heavier aggregation queries efficiently without impacting live operations.

Connecting to Snowflake

We use the snowflake-connector-python library to connect to the Snowflake warehouse. The account identifier is the part of your Snowflake URL before .snowflakecomputing.com. For example, if your URL is abc123.eu-west-1.snowflakecomputing.com then your account is abc123.eu-west-1:

sf = snowflake.connector.connect(
    account  = SNOWFLAKE_ACCOUNT,
    user     = SNOWFLAKE_USER,
    password = SNOWFLAKE_PASSWORD,
)
sf_cursor = sf.cursor()

The connection doesn’t select a database, schema or warehouse. We create and select those next.

Database and schema

We create the database and schema that hold the historical shipment data. IF NOT EXISTS makes the cell safe to re-run. The names come from the SNOWFLAKE_DATABASE and SNOWFLAKE_SCHEMA environment variables (SUPPLY_CHAIN and PUBLIC in our setup):

sf_cursor.execute(f"CREATE DATABASE IF NOT EXISTS {SNOWFLAKE_DATABASE}")
sf_cursor.execute(f"USE DATABASE {SNOWFLAKE_DATABASE}")
sf_cursor.execute(f"CREATE SCHEMA IF NOT EXISTS {SNOWFLAKE_SCHEMA}")
sf_cursor.execute(f"USE SCHEMA {SNOWFLAKE_SCHEMA}")

The compute warehouse

The Snowflake compute warehouse runs the analytics queries. We use an X-SMALL warehouse with auto-suspend and auto-resume to keep costs low. It spins up when a query arrives and suspends automatically after 60 seconds of inactivity. The notebook takes the name from the SNOWFLAKE_WAREHOUSE environment variable (SUPPLY_CHAIN_WH in our setup) and substitutes it into the SQL:

CREATE WAREHOUSE IF NOT EXISTS SUPPLY_CHAIN_WH
WITH WAREHOUSE_SIZE      = 'X-SMALL'
     AUTO_SUSPEND        = 60
     AUTO_RESUME         = TRUE
     INITIALLY_SUSPENDED = TRUE;

USE WAREHOUSE SUPPLY_CHAIN_WH;

INITIALLY_SUSPENDED = TRUE means the warehouse doesn’t consume credits until the first query runs.

The shipment history table

The shipment_history table mirrors the shipments table in Snowflake Postgres but is designed for analytics rather than transactions. It has no primary key constraint since it’s append-only and adds a synced_at column recording when each row was pulled from Snowflake Postgres:

CREATE TABLE shipment_history (
    shipment_id      TEXT,
    supplier_id      TEXT,
    warehouse_id     TEXT,
    dist_center_id   TEXT,
    retailer_id      TEXT,
    status           TEXT,
    delay_minutes    INTEGER,
    rerouted         BOOLEAN,
    alt_warehouse_id TEXT,
    recorded_at      TIMESTAMP_TZ,
    synced_at        TIMESTAMP_TZ
)

The table is dropped and recreated on each notebook run, so the notebook is safe to re-run from the start during development. This deletes any history already stored, so only run it against a database you’re happy to reset. In the analytics Streamlit app the table persists across refreshes and the incremental sync keeps it current.

The incremental sync pattern

Rather than writing directly to the Snowflake warehouse from the simulator, we use an incremental sync pattern. The analytics app reads new rows from the shipments table in Snowflake Postgres and appends them to shipment_history in the Snowflake warehouse.

The sync tracks a watermark – the MAX(recorded_at) already in shipment_history. On each sync call, it pulls only rows newer than that watermark and appends them. A small helper, get_pg_conn(), opens a psycopg2 connection to Snowflake Postgres using the same pattern as Chapter 3. The sync closes that connection in a finally block as soon as the rows are read, so it’s released even if the query fails:

def get_last_synced_at(sf_cursor):
    sf_cursor.execute("SELECT MAX(recorded_at) FROM shipment_history")
    result = sf_cursor.fetchone()[0]
    return result if result else datetime(1970, 1, 1, tzinfo=timezone.utc)

def sync_to_warehouse(sf_cursor):
    last_synced_at = get_last_synced_at(sf_cursor)
    synced_at      = datetime.now(timezone.utc)

    pg_conn = get_pg_conn()
    try:
        with pg_conn.cursor() as pg_cursor:
            pg_cursor.execute("""
                SELECT
                    shipment_id, supplier_id, warehouse_id, dist_center_id,
                    retailer_id, status, delay_minutes, rerouted,
                    alt_warehouse_id, recorded_at
                FROM shipments
                WHERE recorded_at > %s
                ORDER BY recorded_at
            """, (last_synced_at,))
            rows = pg_cursor.fetchall()
    finally:
        pg_conn.close()

    if not rows:
        return 0

    # batch insert into shipment_history (see below)
    ...
    return total

This pattern is the same one used by the analytics Streamlit app on every 30-second refresh. Running it in the notebook here confirms the connections and the watermark query work before the Kafka layer is running. The insert step only runs once there are rows to sync.

The first run will find no rows since the simulator hasn’t started yet. That’s expected.

Batch inserts

The sync function inserts rows in batches of 500 using executemany with %s placeholders. Any value with an isoformat method, such as a timestamp, is converted to a string first:

BATCH_SIZE = 500
placeholders = ", ".join(["%s"] * 11)
total = 0
for i in range(0, len(rows), BATCH_SIZE):
    batch = rows[i:i + BATCH_SIZE]
    values_list = [
        tuple(str(v) if hasattr(v, "isoformat") else v for v in (*row, synced_at))
        for row in batch
    ]
    sf_cursor.executemany(
        f"INSERT INTO shipment_history VALUES ({placeholders})",
        values_list,
    )
    total += len(batch)

There are 11 placeholders because each row has the 10 columns read from Snowflake Postgres plus the synced_at value.

Verifying the result

After creating the table and running the initial sync, we confirm the column definitions match expectations and check the row count:

Table: shipment_history
  Column               Type
  ----------------------------------------
  SHIPMENT_ID          TEXT
  SUPPLIER_ID          TEXT
  WAREHOUSE_ID         TEXT
  DIST_CENTER_ID       TEXT
  RETAILER_ID          TEXT
  STATUS               TEXT
  DELAY_MINUTES        NUMBER
  REROUTED             BOOLEAN
  ALT_WAREHOUSE_ID     TEXT
  RECORDED_AT          TIMESTAMP_TZ
  SYNCED_AT            TIMESTAMP_TZ

Row count: 0

Snowflake reports INTEGER columns as NUMBER, which is why DELAY_MINUTES appears with that type. Zero rows is correct at this stage – the simulator hasn’t run yet.

If you rerun the notebook after Chapter 5, the sync picks up the shipments the simulator wrote. The sync reports how many rows it copied and the row count matches the number of shipments in Snowflake Postgres.

Gotchas

mogrify doesn’t exist on the Snowflake connector. mogrify is a psycopg2 method that returns a complete SQL string with the values inserted. The Snowflake cursor has no such method, so code that calls it fails as soon as there are rows to insert. Use executemany with %s placeholders instead. This is the pattern used in the analytics notebook and the Streamlit app.

Timestamp binding. Convert datetime objects to strings before inserting into Snowflake. The connector doesn’t always handle timezone-aware datetime objects correctly. Wrapping with str(v) if hasattr(v, 'isoformat') else v ensures safe binding for all timestamp columns.

CREATE TABLE IF NOT EXISTS in the analytics app. The Chapter 4 notebook drops and recreates shipment_history on each run. The analytics Streamlit app doesn’t – it creates the table only if it doesn’t already exist, then appends to it incrementally. Don’t run this notebook while the app is running, as its DROP TABLE will delete data the app has already accumulated. The simulator in Chapter 5 truncates the table at startup, so you don’t need to rerun this notebook between simulator runs. The Chapter 6 notebook uses its own scratch table and can run alongside the app.