Right way to manage same user opening multiple sessions

Hi everyone,

I wanted to get your advice/thoughts on what is the right way to deal with the following:

  • Context: I am building an internal Streamlit app with authentication, in which users have to sign in first, and then can perform some operations on their user-specific data in a database.

  • Problem: Sometimes these operations take a few seconds/minutes, so I want to avoid “concurrency” issues when the same user opens multiple sessions (for example, in two different browser tabs), and runs operations in parallel on these different sessions.

  • Question: What is the right way of managing this behavior? Is there any way to do this exclusively with Streamlit (e.g., singletons), or do I need to rely on external resources that provide the “minimum necessary backend”?

Thanks in advance. And excuse me if my framing of the problem is shortsighted, I started programming recently :slight_smile: .

1 Like

Hi @marduk -

This isn’t a shortsighted question at all! But it is a difficult one. Streamlit isn’t well-suited for this type of problem out of the box, as the implicit design is that sessions will be independent of one another. However, depending on the database, if you use st.experimental_singleton with a userid keyword argument to the function, a user in different sessions with the same userid would re-use the same database connection. In that sense, they could be blocked by themselves, which is one solution.

On a database level, some operations cause a table-lock, such that two processes can’t operate independently. So depending on what you want to do in the sessions, you could be protected in that case as well.

Unfortunately, because these problems tend to be highly use-case and technology-specific, I’m not sure I can provide more detail than that how to solve it, but if you’d to post more details I can try.

Best,
Randy

1 Like

Hi again @randyzwitch !

Thanks for your explanation and for nudging me in what I think is the right direction, appreciate it.

Sharing below a solution that combines (1) session tokens and (2) st.experimental_singleton in order to expire any old sessions for a given user - whenever that user opens a new session.

Follow-up question: This seems to work locally even across browsers, but would this work when deployed? Am i missing anything that should be obvious? Also if you or anyone else have ideas to improve this logic, it would be great to read them :slight_smile: Thanks again!

Code:

import streamlit as st
import datetime as dt

# Example list of users
USER_LIST = ['Barbara','Christopher']


# Updates the active session for a given user
@st.experimental_singleton
def get_active_session(username):
    return st.session_state.session_id


# App when logged out
if 'session_id' not in st.session_state:
    st.warning('You are currently logged out')

    #Login form
    with st.form('Login form'):
        username = st.text_input('Username (try "Barbara" or "Christopher")')
        sign_in = st.form_submit_button('Sign In')
    if sign_in and username in USER_LIST:
        st.session_state.user_id = username
        st.session_state.session_id = username + '_' + str(dt.datetime.now())
        get_active_session.clear()
        aux_active_session = get_active_session(st.session_state.user_id)
        st.experimental_rerun()


# App when logged in and session active
elif st.session_state.session_id == get_active_session(st.session_state.user_id):
    st.success('You are currently logged in')
    st.write('Session ID: ',st.session_state.session_id)
    st.button('Useless button')

    # Logout button
    if st.button('Logout'):
        for key in st.session_state.keys():
            del st.session_state[key]
        st.experimental_rerun()


# App when session expired
else:
    st.info('Your session has expired')
    for key in st.session_state.keys():
        del st.session_state[key]
    st.button('Return to homepage')
3 Likes

Updated version by @IndigoJay:

Replacing the deprecated @st.experimental_singleton with @st.cache_resource() st.cache_resource - Streamlit Docs

import streamlit as st
import datetime as dt

# Example list of users
USER_LIST = ['Barbara','Christopher']

# Updates the active session for a given user
#@st.experimental_singleton
#def get_active_session(username):
#    return st.session_state.session_id

@st.cache_resource()
def get_active_session(username):
    return st.session_state.session_id

# App when logged out
if 'session_id' not in st.session_state:
    st.warning('You are currently logged out')

    #Login form
    with st.form('Login form'):
        username = st.text_input('Username (try "Barbara" or "Christopher")')
        sign_in = st.form_submit_button('Sign In')
    if sign_in and username in USER_LIST:
        st.session_state.user_id = username
        st.session_state.session_id = username + '_' + str(dt.datetime.now())
        get_active_session.clear()
        aux_active_session = get_active_session(st.session_state.user_id)
        st.experimental_rerun()

# App when logged in and session active
elif st.session_state.session_id == get_active_session(st.session_state.user_id):
    st.success('You are currently logged in')
    st.write('Session ID: ',st.session_state.session_id)
    st.button('Useless button')

    # Logout button
    if st.button('Logout'):
        for key in st.session_state.keys():
            del st.session_state[key]
        st.experimental_rerun()

# App when session expired
else:
    st.info('Your session has expired')
    for key in st.session_state.keys():
        del st.session_state[key]
    st.button('Return to homepage')