Tech With Galvan
Back to Articles
DevelopmentAug 16, 2026 • 5 min read

Real-Time Dashboard with Streamlit + Plotly (Live Data)

Build a live, auto-refreshing dashboard in Streamlit with Plotly charts — real-time data, auto-refresh, and caching for performance.

Galvan
Galvan

Founder & Creator

Introduction

Static dashboards show yesterday’s data. Real-time dashboards show what’s happening now — and with Streamlit + Plotly, you can build one in under 50 lines. Auto-refresh, live charts, and zero frontend code.

This post builds a live metrics dashboard that refreshes every few seconds.

Setup

pip install streamlit plotly pandas

Step 1: Auto-refresh

Streamlit reruns on interaction. For auto-refresh, use st.rerun() with a delay:

import streamlit as st
import time

# Auto-refresh every 5 seconds
if "last_refresh" not in st.session_state:
    st.session_state.last_refresh = time.time()

if time.time() - st.session_state.last_refresh > 5:
    st.session_state.last_refresh = time.time()
    st.rerun()

Or use the newer st.fragment with run_every:

@st.fragment(run_every=5)
def live_metrics():
    st.metric("Active users", get_active_users())

run_every=5 reruns just that fragment every 5 seconds — much more efficient than full-page reruns.

Step 2: Live data source

import random, time
from datetime import datetime, timedelta

@st.cache_data(ttl=4)   # cache for 4s, then refresh
def fetch_metrics():
    # Replace with real API/DB call
    return {
        "timestamp": datetime.now(),
        "active_users": random.randint(50, 200),
        "requests_per_sec": random.randint(10, 80),
        "error_rate": round(random.uniform(0, 2), 2),
    }

# Keep last N readings in session state
if "history" not in st.session_state:
    st.session_state.history = []

new = fetch_metrics()
st.session_state.history.append(new)
st.session_state.history = st.session_state.history[-60:]   # keep last 60

Step 3: KPI cards

latest = st.session_state.history[-1]
cols = st.columns(4)
cols[0].metric("Active Users", latest["active_users"], delta="+5")
cols[1].metric("Req/sec", latest["requests_per_sec"])
cols[2].metric("Error Rate", f"{latest['error_rate']}%")
cols[3].metric("Uptime", "99.9%")

st.metric shows a big number with an optional delta arrow (green/red).

Step 4: Live line chart with Plotly

import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame(st.session_state.history)

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df["timestamp"], y=df["active_users"],
    mode="lines+markers", name="Active Users",
    line=dict(color="#3b82f6", width=2),
))
fig.add_trace(go.Scatter(
    x=df["timestamp"], y=df["requests_per_sec"],
    mode="lines", name="Req/sec",
    line=dict(color="#10b981", width=2),
))
fig.update_layout(
    title="Live Metrics",
    xaxis_title="Time",
    yaxis_title="Count",
    template="plotly_dark" if st.session_state.get("dark") else "plotly_white",
    height=400,
)
st.plotly_chart(fig, use_container_width=True)

Step 5: Put it together with fragments

import streamlit as st
import plotly.graph_objects as go
import pandas as pd
import time, random
from datetime import datetime

st.set_page_config(page_title="Live Dashboard", layout="wide")
st.title("📊 Live Dashboard")

@st.fragment(run_every=5)
def live_panel():
    # Fetch
    if "history" not in st.session_state:
        st.session_state.history = []
    st.session_state.history.append({
        "timestamp": datetime.now(),
        "active_users": random.randint(50, 200),
        "requests_per_sec": random.randint(10, 80),
        "error_rate": round(random.uniform(0, 2), 2),
    })
    st.session_state.history = st.session_state.history[-60:]

    latest = st.session_state.history[-1]
    c1, c2, c3, c4 = st.columns(4)
    c1.metric("Active Users", latest["active_users"])
    c2.metric("Req/sec", latest["requests_per_sec"])
    c3.metric("Error Rate", f"{latest['error_rate']}%")
    c4.metric("Samples", len(st.session_state.history))

    df = pd.DataFrame(st.session_state.history)
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df["timestamp"], y=df["active_users"],
                            mode="lines", name="Users", line=dict(color="#3b82f6")))
    fig.add_trace(go.Scatter(x=df["timestamp"], y=df["requests_per_sec"],
                            mode="lines", name="Req/s", line=dict(color="#10b981")))
    fig.update_layout(height=400, margin=dict(l=0, r=0, t=30, b=0))
    st.plotly_chart(fig, use_container_width=True)

live_panel()

Only the live_panel fragment reruns every 5s — the rest of the page stays put. Huge performance win.

Step 6: Real data sources

Replace the mock data with real sources:

@st.cache_data(ttl=4)
def fetch_from_api():
    import requests
    r = requests.get("https://api.yourservice.com/metrics", timeout=5)
    return r.json()

@st.cache_data(ttl=4)
def fetch_from_db():
    import sqlite3
    conn = sqlite3.connect("metrics.db")
    df = pd.read_sql("SELECT * FROM metrics ORDER BY ts DESC LIMIT 60", conn)
    return df

Plotly chart types for dashboards

Chart Use for
go.Scatter (lines) Time series, trends
go.Bar Comparisons, rankings
go.Pie / go.Sunburst Proportions
go.Heatmap Correlation, density
go.Indicator Single KPI with gauge
go.Figure with subplots Multi-panel dashboards

Performance tips for real-time

  1. Use st.fragment(run_every=...) — partial reruns, not full page.
  2. Cache data fetches with ttl matching the refresh interval.
  3. Limit history — keep last 60-120 points, not thousands.
  4. Use st.plotly_chart(..., use_container_width=True) — responsive.
  5. Avoid st.write in loops — batch output.
  6. Set page_icon and layout="wide" for dashboard feel.

Common mistakes

  • Full-page rerun every 5s — flickers and loses scroll position. Use fragments.
  • No caching — every refresh re-queries the DB/API. Add ttl.
  • Unbounded history — memory grows forever. Trim to last N.
  • Too many charts — each Plotly chart is heavy. 3-4 per page max.
  • No error handling — if the API is down, the whole dashboard crashes. Wrap in try/except.

Key Concepts

  • st.fragment(run_every=N) = partial auto-refresh
  • @st.cache_data(ttl=N) = cache with expiry
  • Plotly go.Figure = interactive charts
  • st.metric = KPI cards with deltas
  • Session state = persist history across reruns

What to Try Next

FAQ

Streamlit vs Grafana/Datadog for dashboards?

Grafana/Datadog are better for ops/infra monitoring (built for it, handles millions of points). Streamlit is better for custom business dashboards, ML monitoring, and when you want Python logic in the dashboard. Pick based on use case.

Can Streamlit handle 1000+ concurrent users?

Streamlit is single-threaded per session. For high traffic, use Streamlit Cloud (auto-scales) or run multiple instances behind a load balancer. For 1000+ concurrent, consider a React frontend + FastAPI backend instead.

Plotly vs Altair vs Matplotlib in Streamlit?

Plotly = interactive (hover, zoom, pan) — best for dashboards. Altair = declarative, clean — good for statistical charts. Matplotlib = static, familiar — fine for simple plots. Default to Plotly for dashboards.