

Concurrent usage of any in multiple threads will lead to race conditions. However, both the Connection object and the Session object are not thread-safe. See Using Thread-Local Scope with Web Applications. Within a web application, it is common practice to associate the management of a session with the lifetime of the web request. Most of the time in a web application, you would want to share the pool with all the threads in the same process, so that the maximum number of opened connections doesn’t depend on the number of threads configured in your WSGI server. By extension, an engine will also be thread-safe. This means that 2 threads requesting a connection simultaneously will checkout 2 different connections. An object or a function is said to be thread-safe if concurrent access or modification by different threads is possible and the behavior is still normal.Įvery pool implementation in SQLAlchemy is thread safe, including the default QueuePool. Threads in python share memory: so if an object is modified in a thread, this change is reflected in the other. When the same connection is accessed by more than one of these objects, this is when things go wrong. The important point is that Session, QueuePool and Engine are simple python objects, which ultimately hold onto DBAPI connections (database connections). This is why SQLAlchemy uses this kind of connection pooling by default: it will not use any more resources than actually requested by the application. This means that if no concurrent connections are needed, only one connection will ever be open in the database.

A subsequent query using the same engine would use the same connection. The connection is then in ‘idle’ state, because we haven’t yet reached pool_size, and it’s ready to be reused. close ()Ī connection is established using the underlying engine and added to the pool.
