I have created a flask application that open up Database connections and stores some data in global variables. The data in these global variables is used by subsequent ajax requests in the page. However I am running into serious issues with concurrency. I tried using both uwsgi and gunicorn to run the flask application(and got the same results with both). This has been my configuration in both the runs
1) 4 workers
2) multithreaded = True in flask.
When 2 users use the application(the data returned is specific to a few options that the user inputs), what happens is that sometimes data from what was requested by another user comes in my application instance and sometimes the reverse.
My hypothesis is that the worker from which my application gets its data keeps changing. I am not very sure about the worker model in gunicorn and uwsgi. Can someone tell me how I would ensure that the user gets only the data that he has requested for?(Reminder: the data that he is requesting for is stored in a global variable in python and on an ajax request, this object is passed to the html). Any help will be really appreciated.
I have read about request contexts but am completely lost with how to go about this
@app.route("/"):
def redir():
global a;
#assume this is only for post(from a ajax call)
a = #some data built from a database based on the options from the page where the post was made
return jsondumps({'data':a[0:100]});
@app.route("/next100")
def next100():
global a;
# return the next 100 records of the global variable a.
return jsondumps({'data':a[100:200]});
What is expected is that a user makes the first ajax request to the redir() function and then on a different ajax call the next100() is called and it returns the data. The above happens without any issues when there is only one user.
When there are 2 users and they both have called redir() and when they keep calling next100() both the users randomly get data from the global "a" variable(sometimes from user1's context and sometimes from user2's)