Interactive ML Apps with Streamlit / Gradio
Prototype demos and internal tools quickly with Streamlit or Gradio UIs.
In plain words
Streamlit and Gradio let you build a small web page around your model with just Python, so other people can try it by clicking buttons and sliders.
Think of it like…
A shop window versus a warehouse. The window (Streamlit or Gradio) shows the product to visitors so you get reactions quickly, but it isn't designed to handle bulk orders; the warehouse (the prediction API and pipelines) does the heavy, reliable work behind it.
Where you’ve seen it
A churn explorer in Streamlit loads a 480 MB model and a 2-second customer table. Streamlit reruns the script on every widget change, so without caching each interaction costs 2 seconds of loading plus 0.4 seconds of prediction and plotting, 2.4 seconds per click; over a 30-interaction demo that is 72 seconds of waiting. Adding @st.cache_resource to the model loader and @st.cache_data to the table read reduces each rerun to 0.4 seconds, 12 seconds for the same demo. Caching also protects memory: cache_resource shares one model across all user sessions, so 50 concurrent users use about 480 MB for the model, whereas loading it inside each session would take 50 × 480 MB = 24 GB. The sidebar holds the inputs (st.slider for tenure, st.selectbox for contract), a form (st.form) groups them so the app reruns once on submit rather than on every slider move, and st.session_state remembers the user's last scenario. Results are a probability gauge (st.metric), a SHAP bar chart and a table of nearby customers. A Gradio version for a text-classification model exposes predict(text) -> {label: confidence} with gr.Textbox and gr.Label; Gradio queues requests, and with a concurrency limit of 1 and 0.4 seconds per prediction it handles about 2.5 requests a second, which is why the team raises concurrency_limit only after confirming the model is thread-safe. Both apps are deployed from a Docker image to an internal host behind single sign-on (or to a private Hugging Face Space) rather than a public link, since a shared demo URL gives anyone access to the model and to any data it loads. The data shown is a synthetic or anonymised sample, uploads are size-limited and virus-scanned and the app calls the production prediction API rather than embedding its own copy of the model when the demo needs to match production behaviour. For anything customers use, the team builds a real front end on the API.
Words you’ll hear
- Rerun model
- Streamlit re-executes the whole script whenever a widget changes.
- cache_resource / cache_data
- Streamlit caches for shared objects such as models, and for data results.
- session_state
- A per-user dictionary that survives reruns.
- Queue / concurrency limit
- Gradio's mechanism for controlling how many requests run at once.
Visual diagram
Theory & deep dive
How Streamlit and Gradio execute your code
Streamlit's execution model is the key concept: your script is re-run from top to bottom on every user interaction, and widgets simply return their current values. State that must persist (a selected scenario, a running history) goes into st.session_state. Anything expensive must be cached, otherwise every click repeats it: @st.cache_data caches function results that depend on inputs (data reads, aggregations) and returns copies, while @st.cache_resource caches a single shared object (a loaded model, a database connection) across all sessions. With a 2-second data and model load and 0.4 seconds of work per interaction, no caching makes each click 2.4 seconds and a 30-click demo 72 seconds; with caching it is 0.4 seconds and 12 seconds. st.form groups widgets so the script reruns once on submit instead of on every change.
Gradio's model is function-centred: you write fn(inputs) -> outputs, declare component types and Gradio builds the UI and an API. Events (a button click, a change) call functions, gr.Blocks gives layout and multi-step flows and a queue controls concurrency: by default each event runs one request at a time, so a 0.4-second function serves about 2.5 requests a second until you raise concurrency_limit. Gradio also exposes an automatic API for each function, which is convenient but means you must think about access control. Both frameworks run a single Python process, so heavy global state and multiple users need care.
No cache: 2.0 s load + 0.4 s predict = 2.4 s per interaction; 30 clicks = 72 s. With cache_resource and cache_data: 0.4 s per interaction; 30 clicks = 12 s. Memory with 50 sessions: shared model 480 MB versus 50 × 480 MB = 24 GB.
From demo to something others can use safely
Decide what the app is for. A stakeholder demo can run on a laptop or Hugging Face Space with synthetic data; an internal tool needs authentication (single sign-on or the host's auth), a defined data source with access controls and logging; a customer-facing product needs a proper front end and API, monitoring and an SLA. Don't expose a public share link to an app that loads real data or an unrestricted model. Restrict uploads (size, type), avoid executing user-supplied code or pickles, keep secrets in environment variables or the platform's secret store and log usage without storing sensitive inputs.
For production parity, have the app call the same prediction API that production uses rather than embedding a second copy of the model, which avoids divergence in preprocessing and versions. Deploy with a pinned Docker image (same dependencies every time), set resource limits and health checks and plan for concurrency: one Streamlit process serves many sessions but reruns each user's script independently, and CPU-heavy models can stall everyone, so offload heavy work to the API or a worker. Provide explanations (feature importance, example cases) and uncertainty alongside predictions, and add a short note on intended use and limitations so a convincing interface doesn't overstate the model's reliability. When traffic or stakes grow, graduate the app to a front end on top of the API and keep the Streamlit version as an internal analysis tool.
Docker image pinned to Python 3.11 and exact dependencies. Auth via SSO proxy. Model fetched from the registry at start (cache_resource). Data: anonymised sample only. Upload limit 5 MB. Calls /v1/predict on the production API. Health check on /_stcore/health. No public share link.
How it works, step by step
Step 1 of 41. Wrap the model in a function
Write a clear predict function with typed inputs and outputs that the UI will call.
- Keep
- logic out of UI code
When to use it & trade-offs
What it is
Streamlit and Gradio let data scientists turn a model or analysis into an interactive web app in a few dozen lines of Python, with no front-end code. Streamlit runs your script from top to bottom on every interaction: widgets such as sliders, selectboxes and file uploaders return values, and output calls such as st.dataframe, st.pyplot and st.metric render results; st.session_state keeps state between reruns, and caching decorators (st.cache_data for data, st.cache_resource for models and connections) avoid repeating expensive work. Gradio wraps a Python function with typed input and output components (gr.Interface or the layout-flexible gr.Blocks), adds a request queue and can share a temporary public link or be hosted on Hugging Face Spaces. Both are ideal for demos, internal tools and stakeholder feedback; neither replaces a proper API for high-traffic production use.
Why it matters: A model that stakeholders can't try gets little feedback. A quick app lets a product manager explore predictions, a domain expert spot failure cases and a recruiter see your portfolio work. The risk is mistaking a prototype for a service: reloading a model on every click, exposing private data, no authentication, one-request-at-a-time concurrency and no monitoring. Knowing how each framework runs your code (rerun-everything versus function-per-event) and how to cache and secure it keeps a demo responsive and safe.
When to reach for it
- Stakeholder demos and model exploration tools
- Internal dashboards behind single sign-on
- Portfolio projects that need a live interface
When to avoid or be careful
- Loading models inside the rerun path without caching
- Public share links on apps that load real data
- Using a demo app as the production serving layer
Frameworks for ML demos
Strengths: Simple script model; rich widgets and charts.
Watch out: Reruns the script every interaction; needs caching.
Strengths: Function-first; built-in queue and sharing; Spaces hosting.
Watch out: Less layout control; default concurrency of one.
Strengths: Full control; scales independently.
Watch out: More engineering effort.
Interview signals & numbers to know
When this topic comes up
- “How would you let stakeholders try your model?”
- Streamlit's rerun model and caching
- cache_data versus cache_resource
- Gradio queue and concurrency
- When a demo should become a real service
Benchmarks & rules of thumb
- 72 s vs 12 s
- 30 interactions without versus with caching in the example
- 480 MB vs 24 GB
- one shared cached model versus a per-session copy for 50 users
- ≈ 2.5 req/s
- Gradio throughput with concurrency 1 and 0.4 s per call
Common mistakes & follow-ups
Common interview mistakes
- Reading the dataset and loading the model on every rerun.
- Exposing the app to the internet without authentication.
- Treating the demo's local model copy as identical to production.
Likely interviewer follow-ups
- How would you secure this app for internal use?
- How do you keep a demo consistent with the production model?
- When would you rebuild it with a front-end framework?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Interactive ML Apps with Streamlit / Gradio with data science interview Q&A and hands-on practice.