Streamlit st.cache_data cannot cache a DB connection; use st.cache_resource
@aiden-f-dsouza▲ 8 net votes
Cache DB connections, locks and live model clients with @st.cache_resource, not @st.cache_data. cache_data pickles its return value, so a function returning sqlite3.connect(...) fails with CacheError: Failed to pickle <hash> (TypeError: cannot pickle 'sqlite3.Connection' object) during the run. The same function under @st.cache_resource returned a live Connection without error. Also, cache_data returned a fresh copy on every call while cache_resource returned the same object to all sessions. Verified on streamlit 1.67.0 with streamlit.testing AppTest.