Streamlit developer on retainer: @st.cache_resource caches Whisper model and results dict as shared singleton — transcriptions leak across user sessions — 15 users affected — $80,000 — 3 months
streamlit 1.31.0 • Python 3.11; @st.cache_resource returns SAME object reference to ALL sessions (global singleton); mutable results dict bundled in cached return value; every session writes to same dict; User B reads User A’s transcriptions; 15 paying users’ audio content leaked; fix: @st.cache_resource for model only; per-session results in st.session_state (session-scoped, never shared) • Northfield Streamlit Analytics Ltd. (3-person; 3 months; 2.0h)
Northfield Streamlit Analytics Ltd. is a 3-person startup building a real-time meeting transcription SaaS. Their product allows enterprise users to upload meeting recordings, transcribe them with Whisper, and review searchable transcripts in a Streamlit dashboard. The app ran on a single VM with Streamlit 1.31.0. Loading Whisper large-v2 from disk takes 8–12 seconds and consumes 10 GB of VRAM, so the team used @st.cache_resource to load the model once and reuse it across all sessions — the documented and correct use case. To keep the code simple, the same cached function also initialized and returned an empty results dictionary, returning both together as a single dict: {“model”: whisper_model, “results”: {}}.
The app logic then wrote each user’s completed transcription into the results dict after processing: app_state[“results”][st.session_state.user_email] = transcript. During development with one developer testing alone, this worked correctly — there was only one session and one user writing to the dict. In early beta with 5 users, results occasionally appeared in the wrong account but were attributed to a UI rendering glitch. By the time 15 paying enterprise customers had used the app, users were opening the dashboard and seeing other companies’ meeting transcripts — personally-identifiable conversation content from unrelated organizations — at the top of the results panel.
# transcription_app.py — Northfield Streamlit Analytics Ltd.
# streamlit 1.31.0; Python 3.11
import streamlit as st
import whisper
@st.cache_resource
def load_app_state():
"""
Bug: @st.cache_resource returns the SAME object to ALL sessions.
Designed for stateless singletons (models, DB connections).
Here it returns a mutable results dict bundled with the model.
"""
model = whisper.load_model("large-v2")
# This empty dict is SHARED across all user sessions.
# Any session that writes to it modifies the shared singleton.
return {
"model": model,
"results": {}, # ← mutable; will accumulate all users' data
}
def main():
app_state = load_app_state() # same dict for every session
st.title("Meeting Transcription")
uploaded = st.file_uploader("Upload recording", type=["mp3", "wav", "m4a"])
if uploaded:
with st.spinner("Transcribing..."):
# Save temp file and transcribe
import tempfile, os
suffix = "." + uploaded.name.split(".")[-1]
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
f.write(uploaded.read())
tmp_path = f.name
result = app_state["model"].transcribe(tmp_path, fp16=True)
os.unlink(tmp_path)
# Bug: writes to shared singleton dict
# st.session_state.user_email is unique per session,
# but app_state["results"] is THE SAME DICT for all sessions.
# User A transcribes → results["userA@corp.com"] = "..."
# User B opens app → load_app_state() returns same cached dict
# → app_state["results"] already contains "userA@corp.com" entry
user_email = st.session_state.get("user_email", "anonymous")
app_state["results"][user_email] = result["text"]
# Display all results — shows EVERY USER'S transcripts
st.subheader("All Transcriptions")
for email, text in app_state["results"].items():
st.markdown(f"**{email}:** {text[:200]}...")
# @st.cache_resource identity check (confirms singleton):
#
# In browser tab 1 (User A session):
# app_state = load_app_state()
# print(id(app_state["results"])) # e.g. 140234567890
#
# In browser tab 2 (User B session, same server process):
# app_state = load_app_state()
# print(id(app_state["results"])) # 140234567890 — SAME object
#
# Both sessions share the same dict in memory.
# User A writes → User B reads User A's data on next rerun.
#
# @st.cache_data would not have this problem (deep-copies on return)
# but raises TypeError here because whisper.Whisper is not hashable:
# TypeError: unhashable type: 'whisper.Whisper'
if __name__ == "__main__":
main()
The root cause became clear when the same function was called from two simultaneous browser sessions and id(app_state[“results”]) was printed in both: identical memory addresses. @st.cache_resource is explicitly designed to return the same object instance to every caller — this is documented as the feature, not a bug. The fix was to separate the model (genuinely shared, stateless) from the results (per-session, mutable): the model stays in @st.cache_resource; results move to st.session_state. Streamlit’s st.session_state is strictly scoped to one browser session and is never shared across users regardless of server configuration. After the fix, id(st.session_state[“results”]) from two simultaneous sessions returned different addresses.
Fix: model in @st.cache_resource, results in st.session_state
# Fixed transcription_app.py — Northfield Streamlit Analytics Ltd.
import streamlit as st
import whisper
import tempfile, os
@st.cache_resource
def load_model():
"""Fix: cache ONLY the stateless model. No mutable state."""
return whisper.load_model("large-v2")
def main():
model = load_model() # same model instance for all sessions — correct
# Fix: initialize per-session results in st.session_state.
# st.session_state is scoped to one browser tab / user session.
# Writing to st.session_state in session A never affects session B.
if "results" not in st.session_state:
st.session_state.results = {} # fresh dict per session
st.title("Meeting Transcription")
uploaded = st.file_uploader("Upload recording", type=["mp3", "wav", "m4a"])
if uploaded:
with st.spinner("Transcribing..."):
suffix = "." + uploaded.name.split(".")[-1]
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
f.write(uploaded.read())
tmp_path = f.name
result = model.transcribe(tmp_path, fp16=True)
os.unlink(tmp_path)
# Fix: write to session-scoped state, not shared singleton
user_email = st.session_state.get("user_email", "anonymous")
st.session_state.results[user_email] = result["text"]
# Display only THIS session's results — no cross-session leakage
st.subheader("Your Transcriptions")
for email, text in st.session_state.results.items():
st.markdown(f"**{email}:** {text[:200]}...")
# Results after fix — Northfield Streamlit Analytics Ltd.:
# Cross-session data leakage: present → eliminated
# Model load time (first user): 10s → 10s (unchanged)
# Model load time (subsequent): 10s → 0s (cache_resource still works)
# VRAM usage: 10 GB → 10 GB (single instance still shared)
# Duration of investigation: 3 months → 2.0h retainer session
#
# Session state isolation sanity check (add to onboarding):
# # In development, open two browser tabs simultaneously
# # and print the memory address of session-local data:
# st.write(f"results id: {id(st.session_state.results)}")
# # Both tabs should show DIFFERENT addresses.
# # If the same address appears in both tabs, the data is shared.
#
# Rule of thumb for Streamlit caching:
# @st.cache_resource → stateless singletons: ML models, DB connections,
# API clients. Never store user data here.
# @st.cache_data → deterministic functions of their arguments:
# data loading, preprocessing. Returns deep copy.
# st.session_state → all per-user, per-session mutable state.
# database → data that must persist across sessions (user prefs,
# saved results, audit logs).
if __name__ == "__main__":
main()
Related retainer posts
- gradio developer on retainer — Gradio 4.24.0; gr.Audio(type=“filepath”) passes WebM/Opus blob; librosa NoBackendError (no FFmpeg on server); 100% demo failure; fix: type=“numpy”; 1.5h
- montreal forced aligner developer on retainer — MFA 2.0.4; SQLite corpus cache; --clean not passed after .lab update; 12 runs read stale cache; TTS MOS 2.4 → 4.1; fix: mfa align ... --clean; 2.0h
- distil-whisper developer on retainer — distil-whisper/distil-large-v2; condition_on_prev_tokens=True; music intro hallucination cascade; 83% episodes corrupted; fix: condition_on_prev_tokens=False; 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →