Skip to content

How to Fix Python Streamlit Cache Not Updating

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about How to Fix Python Streamlit Cache Not Updating. We cover key concepts, practical examples, and best practices.

Streamlit cache returns stale data when the cache key does not change, the function arguments are mutable, or the cache TTL is too long.

The Wrong Way

import streamlit as st
import pandas as pd

@st.cache_data
def load_data():
    df = pd.read_csv('data.csv')
    return df

df = load_data()
st.dataframe(df)

If data.csv changes on disk, the old data is still shown because the cache never invalidates.

The Right Way

import streamlit as st
import pandas as pd
import os

@st.cache_data(ttl=300)
def load_data():
    df = pd.read_csv('data.csv')
    return df

df = load_data()
st.dataframe(df)

The cache expires after 300 seconds, reloading the CSV.

Prevention Tips

  • Set ttl (time-to-live) for data that changes periodically.
  • Use @st.cache_resource for non-data objects (models, connections).
  • Clear cache manually with st.cache_data.clear().
  • Use st.cache_data for DataFrames and st.cache_resource for connections.
  • Avoid using mutable objects as cache keys.

Common Mistakes with streamlit cache

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between st.cache_data and st.cache_resource?

@st.cache_data is for data objects (DataFrames, arrays). @st.cache_resource is for global resources (database connections, ML models). They use different caching strategies.

How do I force refresh the cache?

Use st.cache_data.clear() to clear all cached data. Use func.clear() to clear cache for a specific function. Add a refresh button in the UI that calls clear() and st.rerun().

Can I use Streamlit cache with unhashable arguments?

Set hash_funcs parameter: @st.cache_data(hash_funcs={pd.DataFrame: lambda df: hash(df.to_string())}). This provides a custom hash function for unhashable types.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro