Does the use of global variables in a flask application which handles concurrent requests at the same time creates any issue?
Asked
Active
Viewed 132 times
-1
-
2Yes, the global variables will be shared across user sessions and thus create race condition if used. – Rahul Bharadwaj Mar 25 '20 at 13:56
-
2Does this answer your question? [Are global variables thread safe in flask? How do I share data between requests?](https://stackoverflow.com/questions/32815451/are-global-variables-thread-safe-in-flask-how-do-i-share-data-between-requests) – Rahul Bharadwaj Mar 25 '20 at 13:57
-
1More specifically, *unguarded access* to the globals can cause race conditions. – chepner Mar 25 '20 at 13:57
-
Is there any way to avoid such race conditions? – NITHIN Mar 25 '20 at 13:59
-
2@chepner even guarded globals can lead to race condition-type scenarios when using workers e.g. user connects to a worker, global is updated, next request the user connects to an other worker where the global is not updated or a completely different value – Masklinn Mar 25 '20 at 14:00
-
@Masklinn Good point, though in my (possibly oversimplified) mental model, assigning a request to a worker without considering the consistency of the workers is an example of unguarded access. – chepner Mar 25 '20 at 14:08
-
@chepner fair enough – Masklinn Mar 25 '20 at 14:35
1 Answers
0
Depends how the globals are used. If they're constants, it doesn't matter. If they're actual variables (mutable objects or values which get set) however you can have
- incoherent states when using multithreaded server
- information leaks when using multithreaded server (one user seeing data from a different user)
- partially-visible changes and rollbacking changes when using multiprocessing servers (e.g. gunicorn workers) as the global would be updated on a per-worker basis, and users can "jump" from worker to worker
Why do you want to have globals, exactly?

Masklinn
- 34,759
- 3
- 38
- 57