Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Deployment and Customization

Performance and Security Checklist

Find slow spots in a Streamlit app with timing, then fix them with caching, smaller data and fragments. Add passwords, validate input and avoid common security holes.

A Streamlit app that works for you can still be slow for ten users, or expose something you did not intend. This lesson gives you a practical checklist. The first half is performance: how to measure, and the handful of fixes that solve most problems. The second half is security: who can reach your app, what they can send it, and what the app can reveal.

Both halves rest on facts you already know. The script reruns on every interaction, caches are shared, session state is per user, and the server holds a connection for every open tab.

Streamlit does not run on this site, so app code is read-only. The runnable examples use plain Python timing and password-checking code, which you can use inside a real app unchanged.

Performance: measure first

Guessing where time goes wastes effort. Time the sections of your script and look at the numbers. A tiny decorator does the job:

Python
import time
import streamlit as st

def timed(label):
    def wrap(func):
        def inner(*args, **kwargs):
            start = time.perf_counter()
            result = func(*args, **kwargs)
            st.sidebar.caption(f"{label}: {time.perf_counter() - start:.2f}s")
            return result
        return inner
    return wrap

Run it on your suspect functions and keep the sidebar readout while developing. The same measurement can run anywhere, as in the TryIt below, which compares an uncached and a cached load by counting actual work with a simulated delay.

Python Measure the effect of caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The uncached version pays 0.2 s on every rerun; the cached one only on the first. With ten users and a slider, that gap is the difference between smooth and sluggish.

The performance checklist

  1. Cache expensive loads. @st.cache_data for data, @st.cache_resource for models and connections (see Caching). Set ttl and max_entries.
  2. Load less. Read only the columns you use (usecols= in read_csv), push filters and aggregations into SQL, and show head(100) instead of a million rows. A browser struggles to render huge tables.
  3. Use efficient formats. Parquet loads much faster than CSV and keeps types. Convert once, offline.
  4. Shrink memory. Downcast numbers (astype("float32")), use category for repeated strings, and drop columns early. Memory is per process, and each cache entry and session adds to it.
  5. Do not recompute on every rerun. Put expensive derived values behind cached functions keyed by their inputs.
  6. Rerun less. Group inputs in st.form, and use @st.fragment so one chart's controls do not rerun the whole page (Callbacks, Forms and Fragments).
  7. Limit what you draw. Hundreds of widgets or thousands of chart points make the browser slow, whatever the server does. Aggregate or sample before plotting.
  8. Avoid slow things at import time. Heavy imports (TensorFlow, large models) at the top of the file are paid again after every code change in development, and once per server start in production. Import lazily inside the function that needs them if the page often does not.
  9. Move long work out. Anything over a few seconds belongs in a background job or scheduled pipeline, with the app reading the finished result.

Memory and shared state

Because cache_resource objects are shared by all users, they must be safe to use from several threads. A shared dictionary that sessions mutate needs a lock:

Python
import threading

@st.cache_resource
def get_counter():
    return {"lock": threading.Lock(), "visits": 0}

counter = get_counter()
with counter["lock"]:
    counter["visits"] += 1

Without the lock, two sessions can read the same value and both write back the same increment, losing a count. Shared mutable state is a reason to prefer a database for anything important.

Security: who can reach your app

Streamlit has no login by default. Anyone with the URL can use the app and see everything it shows. Decide how to protect it:

  • Do nothing only when the content is public and harmless.
  • Platform access control. Community Cloud can restrict an app to invited email addresses, and company platforms offer identity-aware proxies.
  • Built-in authentication. Recent Streamlit versions support OpenID Connect providers (st.login, st.user) configured in secrets.toml. Check the current documentation for the setup.
  • A password gate for small private tools (below). It is basic protection, not a user management system.

A password check needs care. Compare in constant time, keep the password in secrets, and remember the result in session state:

Python
import hmac
import streamlit as st

def check_password() -> bool:
    if st.session_state.get("authenticated"):
        return True
    entered = st.text_input("Password", type="password")
    if entered:
        if hmac.compare_digest(entered, st.secrets["app_password"]):
            st.session_state.authenticated = True
            st.rerun()
        else:
            st.error("Wrong password.")
    return False

if not check_password():
    st.stop()

st.write("Secret dashboard")      # only reached after login

The st.stop() is essential: it makes sure nothing below the gate runs for an unauthenticated visitor, including data loading. Test the helper in isolation:

Python Constant-time password check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

After three wrong guesses the correct password is no longer accepted in this example; that lockout is only as strong as where the counter lives. A per-session counter can be bypassed by refreshing the page, so real protection needs a server-side store or an authenticating proxy. Know what your gate is worth.

Security: what the app does with input

Everything a user types, uploads or selects is untrusted:

  • SQL: always use parameters, never f-strings (SQL Databases).
  • Files: validate type and size, never unpickle or eval uploads (Files, CSV and Excel). Do not use user-supplied names as paths.
  • HTML: st.markdown(..., unsafe_allow_html=True) and st.html render HTML. Putting user text into them allows script injection. Escape it with html.escape() or avoid unsafe HTML entirely.
  • Shell and code execution: never pass user text to subprocess with shell=True, os.system, eval or exec.
  • Paths: if users choose a file by name, resolve it and confirm it is inside the allowed folder; otherwise ../../etc/passwd style input walks out of it.
  • Outbound requests: if users supply a URL for your server to fetch, they can point it at internal addresses (server-side request forgery). Allow-list hosts or block private ranges.

The next TryIt shows two small defenses: escaping text before it goes into HTML, and a safe path check.

Python Escape HTML and confine paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real app, use Path(...).resolve() and is_relative_to(base); the idea is the same: after resolving, the path must still be inside the allowed folder.

Security: what the app reveals

  • Errors: set client.showErrorDetails = "none" in production so visitors do not see stack traces (Configuration and Themes). Log details on the server instead.
  • Secrets: keep them in st.secrets, never in the repository, never printed, never in cache keys.
  • Data exposure: a table of customers shown to everyone is a data leak. Filter by the logged-in user on the server, not by hiding columns in the browser.
  • Caches are shared: a cached function that returns private data keyed only by its arguments can hand one user's data to another. Include the user identity in the arguments, or do not cache it.
  • Dependencies: pin versions, rebuild regularly and watch security advisories for packages you use.
  • Usage statistics and analytics: tell users what you collect.

A release checklist

Before going live, tick each line:

  • Dependencies pinned, app starts from a clean virtual environment.
  • No secrets in the repository or image.
  • Access control decided and tested (try the URL in a private window).
  • Errors hidden from visitors, logs available to you.
  • Heavy loads cached, large tables paginated.
  • Upload limits set (server.maxUploadSize, proxy body size).
  • Queries parameterized; user text never reaches HTML, shell or file paths unchecked.
  • Health check, memory limit and restart policy configured.

Common mistakes

  • Putting the data load above the login gate.
  • Comparing passwords with == and storing them in code.
  • Caching private data under a key that does not include the user.
  • Rendering user text with unsafe_allow_html=True.
  • Optimizing without measuring first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the first step in fixing a slow Streamlit app?

    Timing sections of the script shows which load or computation to cache or reduce, instead of guessing.
  2. 2. Why is st.stop() important in a password gate?

    Without it the script continues and may load or show protected data even though the user has not logged in.
  3. 3. Which approach prevents a script-injection attack when showing a user's comment with unsafe HTML?

    Escaping turns special characters into harmless text so the browser does not run injected markup.
  4. 4. A cached function returns a user's private report, keyed only by the report id. What is the risk?

    Caches are shared across sessions. Include the user in the arguments or do not cache private data.

Summary

  • Measure, then fix: cache loads, load less data, use efficient formats, rerun less and keep long work out of the app.
  • Shared cached objects need thread safety; prefer a database for important shared state.
  • Streamlit has no login by default: use platform access control, built-in authentication or at least a gated password check followed by st.stop().
  • Treat all input as untrusted: parameterize SQL, escape HTML, confine file paths, never execute user text.
  • Hide error details, keep secrets in st.secrets, and never cache private data under a shared key.

Next: Project: Expense Tracker