Problem with multi-user filtering

Hi everyone,
I’m building a Streamlit app that connects to a PostgreSQL database and uses @st.cache_resource to cache the database connection. The app displays data across multiple tabs, with various filters applied to each data table (e.g., by Client ID, Name, Date Range, etc.).

Here’s my issue: when multiple users access the app simultaneously, the filter selections don’t work independently. If one user applies filters, it seems to override the filters for others, resetting filter selections for other users.

Has anyone faced a similar issue or can offer best practices for handling this?

Thanks in advance!

I have seen some people facing issues like this due to bugs in their code. Best practice is avoiding mixing application-scoped state and session-scoped state, which is in itself quite a broad topic. I don’t think more specific advice can be provided based on your high level description.

Maybe it helps

My function for fetching data from DB

def get_clients():
    clients_dao = ClientsDAO()
    data = clients_dao.get_clients()
    return data


def load_clients():
    clients = get_clients()
    client_data_to_skip = {"outbound_file_types", "inbound_file_types", "transactions", "subscription"}
    clients_data = [c.to_dict() for c in clients]
    clients_data = [{k: v for k, v in data.items() if k not in client_data_to_skip} for data in clients_data]

    clients_df = pd.DataFrame(clients_data)
    clients_df["id"] = clients_df["id"].astype(int)
    clients_df = clients_df.sort_values(by="created_at", ascending=False)

    return clients_df, clients

My code for rendering page

def render_clients_tab(clients_df: pd.DataFrame):
    st.header("Clients")

    if not clients_df.empty:
        # Add filters
        client_ids = st.multiselect("Filter by Client ID", options=clients_df["id"].unique())
        client_names = st.multiselect("Filter by Client Name", options=clients_df["client_name"].unique())
        start_date = st.date_input(
            "Start Date", value=pd.to_datetime(clients_df["created_at"].min()).date(), key="clients_start_date"
        )
        end_date = st.date_input(
            "End Date", value=pd.to_datetime(clients_df["created_at"].max()).date(), key="clients_end_date"
        )

        # Apply filters
        filtered_clients_df = clients_df.copy()
        filters = {
            "id": client_ids,
            "client_name": client_names,
        }
        filtered_clients_df = apply_filters(filtered_clients_df, filters)
        filtered_clients_df = apply_date_filter(filtered_clients_df, "created_at", start_date, end_date)

        # Display table
        if not filtered_clients_df.empty:
            st.dataframe(filtered_clients_df)
        else:
            st.write("No clients found with the applied filters.")
    else:
        st.write("No clients found.")


# Load data
clients_df, clients = load_clients()

# Create tabs
clients_tab, subscriptions_tab, inbound_tab, outbound_tab, client_info_tab = st.tabs(
    ["Clients", "Subscriptions", "Inbound File Types", "Outbound File Types", "Client Info"]
)

# Render tabs
with clients_tab:
    render_clients_tab(clients_df)

What is apply_filters?

def apply_filters(df, filters: dict[str, list]) -> pd.DataFrame:
    for column, values in filters.items():
        if values and column in df.columns:
            df = df[df[column].isin(values)]

    return df

def apply_date_filter(
    df,
    date_column: str,
    start_date: DateWidgetReturn,
    end_date: DateWidgetReturn,
) -> pd.DataFrame:
    if date_column in df.columns:
        mask = (pd.to_datetime(df[date_column]).dt.date >= start_date) & (
            pd.to_datetime(df[date_column]).dt.date <= end_date
        )

        return df.loc[mask]
    else:
        return df

I ran your code with my own implementation of ClientsDAO and was unable to reproduce the issue. The filters selected in different sessions remain separated, as well as the filtered data.

For me, this problem only happens when two users filter at the same time.

That is the scenario I tested. Well, unless I am misunderstanding what you mean by “two users filter at the same time” . Because filtering is a matter of a click, if you mean two users clicking the same widget within the same tenth of a second, then no. Should I?

Yes, at the same moment in time. When two users start working with a multiselect filter at the same time. User1 starts selecting items in the multiselect and at the same time user2 starts selecting. In my case, user2’s filters just reset from time to time

No way. It works as expected for me even when two users are changing the same multiselect at the same time. Furthermore, I don’t see how the code you posted can possibly cause the issue.

One thing that might make the widgets reset is changing the data while the app is being used, but the application doesn’t do that so it would be unrelated to simultaneous users of the application.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.