Templates › Process analytics

Process analytics dashboard for Snowflake (cycle time, SLA, bottlenecks)

Throughput, cycle time, SLA and bottlenecks for tickets, orders, claims or approvals. A Streamlit process analytics template for Snowflake.

OperationsStreamlitRuns in Snowflake145 lines of Python
Live demo: the real app, running in your browser on generated sample data

Click Run to start the app here.

The first start downloads Python for the browser (about 30 MB) and takes 10–30 seconds.

What it answers

How long does a case take, where does it wait, and how many miss the SLA? This template works on any case-based process (support tickets, orders, insurance claims, approvals): cases started and completed, the median cycle time, the share within SLA, and the steps that take longest.

It is for operations leads and process owners who have a log of case steps in Snowflake, from a ticketing system, an ERP or a workflow tool.

What's in it

  • Cases started and completed, median cycle time, share within SLA
  • Weekly throughput and cycle-time distribution against the SLA
  • Step durations (median, 90th percentile) to find bottlenecks
  • Open work by step and the cases over SLA

The data it needs

Steps

One row per step of a case (ticket, order, claim…) with start and end time; END_TIME empty while the step is open.

ColumnTypeAlso matches columns named
CASE_IDtextticket_id, order_id, claim_id, request_id, case_number, id
STEPtextactivity, stage, status, task, phase, step_name
TEAMtextowner_team, group, queue, department, assignee_group, resource
START_TIMEtimestampstarted_at, start_date, created_at, opened_at, timestamp, event_time
END_TIMEtimestampended_at, end_date, completed_at, closed_at, resolved_at

The query it starts from (STEPS_SQL):

SELECT CASE_ID, STEP, TEAM, START_TIME, END_TIME
FROM YOUR_DATABASE.YOUR_SCHEMA.CASE_STEPS

Using it on your data

You need one row per step with a start and an end time. Many systems store status changes instead; turn them into steps in the query by pairing each change with the next one (LEAD() over the case, ordered by time).

In StreamGen you don't edit any of this by hand: the agent looks at your tables, matches columns by name and type (including the names above), shows you the mapping, and checks the app on your live data before you deploy it.

Three ways to use it

Try it in StreamGen

Two hours on sample data in a ready-made Snowflake sandbox. No sign-up, nothing to install.

Start the 2-hour try

Install in your Snowflake

StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.

Open the Marketplace listing

Copy the code

It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.

Show the code

The code

All of it, as it runs in the demo above. The data section at the top is the only part that changes for your tables.

Show all 145 lines
"""Process analytics — throughput, cycle time, SLA and bottlenecks for a
case-based process (tickets, orders, claims, approvals…)."""

import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(page_title="Process analytics", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated sample data. To use your own table, set
# DEMO = False and make the query return these columns (rename with AS).
# One row per step of a case; END_TIME is empty while the step is open.
DEMO = True
STEPS_SQL = """
SELECT CASE_ID, STEP, TEAM, START_TIME, END_TIME
FROM {{DATABASE}}.{{SCHEMA}}.CASE_STEPS
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = px.colors.qualitative.Safe
SLA_HOURS = 72   # target from the first step's start to the last step's end
STEP_ORDER = ["Received", "Triage", "Review", "Approval", "Fulfilment"]


def demo_steps() -> pd.DataFrame:
    rng = np.random.default_rng(13)
    now = pd.Timestamp.today().floor("h")
    durations = {"Received": 0.5, "Triage": 4, "Review": 18, "Approval": 10, "Fulfilment": 14}  # mean hours
    teams = {"Received": "Intake", "Triage": "Intake", "Review": "Specialists", "Approval": "Managers", "Fulfilment": "Operations"}
    rows = []
    for i in range(1, 1501):
        t = now - pd.Timedelta(hours=float(rng.uniform(0, 120 * 24)))
        for step in STEP_ORDER:
            if step == "Approval" and rng.random() < 0.3:
                continue  # small cases skip approval
            hours = rng.gamma(1.6, durations[step] / 1.6) * (1.6 if step == "Review" and t.dayofweek >= 4 else 1)
            end = t + pd.Timedelta(hours=float(hours))
            rows.append((f"C-{i:05d}", step, teams[step], t, end if end < now else pd.NaT))
            if end >= now:
                break
            t = end + pd.Timedelta(hours=float(rng.exponential(2)))
    return pd.DataFrame(rows, columns=["CASE_ID", "STEP", "TEAM", "START_TIME", "END_TIME"])


@st.cache_data(ttl=600, show_spinner=False)
def load_steps() -> pd.DataFrame:
    if DEMO:
        df = demo_steps()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(STEPS_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    for c in ("START_TIME", "END_TIME"):
        df[c] = pd.to_datetime(df[c], errors="coerce")
    for c in ("CASE_ID", "STEP", "TEAM"):
        df[c] = df[c].fillna("Unknown").astype(str)
    df["HOURS"] = (df["END_TIME"] - df["START_TIME"]).dt.total_seconds() / 3600
    return df.dropna(subset=["START_TIME"])


def cases_from(steps: pd.DataFrame) -> pd.DataFrame:
    c = steps.groupby("CASE_ID").agg(STARTED=("START_TIME", "min"), ENDED=("END_TIME", "max"),
                                     OPEN_STEPS=("END_TIME", lambda s: s.isna().sum()), LAST_STEP=("STEP", "last"))
    c["DONE"] = c["OPEN_STEPS"].eq(0)
    c.loc[~c["DONE"], "ENDED"] = pd.NaT
    c["CYCLE_HOURS"] = (c["ENDED"] - c["STARTED"]).dt.total_seconds() / 3600
    c["BREACHED"] = c["DONE"] & (c["CYCLE_HOURS"] > SLA_HOURS)
    return c.reset_index()


st.title("Process analytics")
if DEMO:
    st.caption("Showing generated demo data — connect your own table in the DATA section.")

try:
    steps = load_steps()
except Exception as e:
    st.error(f"Could not load process data: {e}")
    st.stop()
if steps.empty:
    st.info("No cases yet.")
    st.stop()

with st.sidebar:
    st.header("Filters")
    weeks = st.slider("Weeks", 2, 16, 8)
    teams = st.multiselect("Team", sorted(steps["TEAM"].unique()))

cases = cases_from(steps)
since = steps["START_TIME"].max() - pd.Timedelta(weeks=weeks)
recent_cases = cases[cases["STARTED"] >= since]
done = recent_cases[recent_cases["DONE"]]
open_cases = cases[~cases["DONE"]]
scoped_steps = steps[steps["CASE_ID"].isin(recent_cases["CASE_ID"])]
if teams:
    scoped_steps = scoped_steps[scoped_steps["TEAM"].isin(teams)]

k = st.columns(4)
k[0].metric("Cases started", f"{len(recent_cases):,}")
k[1].metric("Completed", f"{len(done):,}")
k[2].metric("Median cycle time", f"{done['CYCLE_HOURS'].median():.1f} h" if not done.empty else "–")
k[3].metric(f"Within SLA ({SLA_HOURS} h)", f"{1 - done['BREACHED'].mean():.0%}" if not done.empty else "–")
st.caption(f"Cases started in the last {weeks} weeks · {len(open_cases):,} cases open right now.")

left, right = st.columns(2)
weekly = (recent_cases.assign(WEEK=recent_cases["STARTED"].dt.to_period("W").dt.start_time)
          .groupby("WEEK").agg(STARTED=("CASE_ID", "size"), COMPLETED=("DONE", "sum")).reset_index()
          .melt(id_vars="WEEK", var_name="KIND", value_name="CASES"))
weekly["KIND"] = weekly["KIND"].str.capitalize()
fig = px.bar(weekly, x="WEEK", y="CASES", color="KIND", barmode="group", color_discrete_sequence=COLORS,
             labels={"WEEK": "", "CASES": "Cases"}, title="Throughput by week")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

fig = px.histogram(done, x="CYCLE_HOURS", nbins=40, color="BREACHED", color_discrete_map={False: COLORS[0], True: "#d62728"},
                   labels={"CYCLE_HOURS": "Cycle time (hours)", "BREACHED": "Over SLA"}, title="Cycle time")
fig.add_vline(x=SLA_HOURS, line_dash="dash", annotation_text="SLA")
fig.update_layout(margin=dict(t=50, b=10), yaxis_title="Cases")
right.plotly_chart(fig, width="stretch")

st.subheader("Where time goes")
order = [s for s in STEP_ORDER if s in set(scoped_steps["STEP"])] + sorted(set(scoped_steps["STEP"]) - set(STEP_ORDER))
by_step = (scoped_steps.dropna(subset=["HOURS"]).groupby("STEP")["HOURS"]
           .agg(MEDIAN="median", P90=lambda s: s.quantile(0.9), STEPS="size").reindex(order).dropna(how="all").reset_index())
left, right = st.columns([3, 2])
fig = px.bar(by_step.melt(id_vars="STEP", value_vars=["MEDIAN", "P90"], var_name="STAT", value_name="H"),
             x="STEP", y="H", color="STAT", barmode="group", color_discrete_sequence=COLORS,
             labels={"STEP": "", "H": "Hours", "STAT": ""}, title="Step duration (median and 90th percentile)")
fig.update_layout(margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")

waiting = steps[steps["END_TIME"].isna()].copy()
waiting["WAITING_H"] = (steps["START_TIME"].max() - waiting["START_TIME"]).dt.total_seconds() / 3600
backlog = waiting.groupby("STEP", as_index=False).agg(OPEN=("CASE_ID", "size"), OLDEST_H=("WAITING_H", "max"))
right.markdown("**Open work by step**")
right.dataframe(backlog.reset_index(drop=True), width="stretch", column_config={
    "OPEN": st.column_config.NumberColumn("Open"),
    "OLDEST_H": st.column_config.NumberColumn("Oldest (hours)", format="%.0f"),
})

with st.expander("Cases over SLA"):
    st.dataframe(done[done["BREACHED"]].sort_values("CYCLE_HOURS", ascending=False).reset_index(drop=True), width="stretch")

Questions

Is this process mining?

It covers the measures most teams ask about first (cycle time, SLA, bottlenecks), without process maps. Ask StreamGen's agent to add the most common paths through the process.

Can the SLA differ by case type?

Yes. Add the case type as a column and an SLA per type; the agent can wire it in.

Can I use the code without StreamGen?

Yes. It is a plain Streamlit app. In Snowsight, create a Streamlit app, paste the code, add plotly to its packages, set DEMO = False and point the query at your table. StreamGen does that mapping, the checks and the deploy for you, and keeps the app working afterwards.

Does my data leave Snowflake?

No. In Snowflake the app runs inside your account and queries your tables there. The live demo on this page runs in your browser on generated sample data; nothing is sent anywhere.

Warehouse or container runtime?

Both work. The template only needs pandas, numpy and plotly, which both Streamlit in Snowflake runtimes provide.

Related templates

All templates · Guides

Build it on your own Snowflake data

In StreamGen you pick this template, the agent matches it to your tables, checks it, and deploys it to Snowflake with roles, approvals and an audit trail. Then ask for changes in plain words.

No sign-up for the 2-hour try. The Native App is free to install, with a free 7-day trial key.