Repository: vantage6/vantage6
Issue: [Bug] Database connections all taken

**Describe the bug**

With busy, long-running servers, the SQLAlchemy error below can show up, saying that the limit of the number of connections to the database is reached. Our suspicion is that somewhere connections are kept that should be discarded as they are finished. 

One of the symptoms of this issue appears to be that nodes no longer pick up new tasks (only after they are restarted).

```
2023-02-14T12:11:41.760271084Z 2023-02-14 12:11:41 - server         - DEBUG    - Received request: OPTIONS organization
2023-02-14T12:11:41.799120227Z 2023-02-14 12:11:41 - server         - DEBUG    - Received request: GET organization

2023-02-14T12:11:50.435861581Z 2023-02-14 12:11:50 - server         - ERROR    - Exception occured during request
2023-02-14T12:11:50.435901981Z Traceback (most recent call last):
2023-02-14T12:11:50.435908281Z   File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1516, in full_dispatch_request
2023-02-14T12:11:50.435912581Z     rv = self.dispatch_request()
2023-02-14T12:11:50.435917181Z   File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1502, in dispatch_request
2023-02-14T12:11:50.435921381Z     return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
2023-02-14T12:11:50.435925381Z   File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 467, in wrapper
2023-02-14T12:11:50.435929482Z     resp = resource(*args, **kwargs)
2023-02-14T12:11:50.435933082Z   File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 84, in view
2023-02-14T12:11:50.435936982Z     return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
2023-02-14T12:11:50.435940682Z   File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 582, in dispatch_request
2023-02-14T12:11:50.435944582Z     resp = meth(*args, **kwargs)
2023-02-14T12:11:50.435965382Z   File "/usr/local/lib/python3.7/site-packages/flask_jwt_extended/view_decorators.py", line 157, in decorator
2023-02-14T12:11:50.435971082Z     verify_jwt_in_request(optional, fresh, refresh, locations, verify_type)
2023-02-14T12:11:50.435976982Z   File "/usr/local/lib/python3.7/site-packages/flask_jwt_extended/view_decorators.py", line 108, in verify_jwt_in_request
2023-02-14T12:11:50.435982282Z     _request_ctx_stack.top.jwt_user = _load_user(jwt_header, jwt_data)
2023-02-14T12:11:50.435988182Z   File "/usr/local/lib/python3.7/site-packages/flask_jwt_extended/view_decorators.py", line 170, in _load_user
2023-02-14T12:11:50.435993482Z     user = user_lookup(jwt_header, jwt_data)
2023-02-14T12:11:50.435998282Z   File "/usr/local/lib/python3.7/site-packages/flask_jwt_extended/internal_utils.py", line 32, in user_lookup
2023-02-14T12:11:50.436003282Z     *args, **kwargs
2023-02-14T12:11:50.436007782Z   File "/vantage6/vantage6-server/vantage6/server/__init__.py", line 355, in user_lookup_loader
2023-02-14T12:11:50.436013382Z     auth = db.Authenticatable.get(identity)
2023-02-14T12:11:50.436018883Z   File "/vantage6/vantage6-server/vantage6/server/model/base.py", line 299, in get
2023-02-14T12:11:50.436022783Z     result = session.query(cls).filter_by(id=id_).one()
2023-02-14T12:11:50.436027583Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3358, in one
2023-02-14T12:11:50.436032883Z     ret = self.one_or_none()
2023-02-14T12:11:50.436037883Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3327, in one_or_none
2023-02-14T12:11:50.436043483Z     ret = list(self)
2023-02-14T12:11:50.436050883Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3403, in __iter__
2023-02-14T12:11:50.436054983Z     return self._execute_and_instances(context)
2023-02-14T12:11:50.436058583Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3425, in _execute_and_instances
2023-02-14T12:11:50.436062283Z     querycontext, self._connection_from_session, close_with_result=True
2023-02-14T12:11:50.436065883Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3440, in _get_bind_args
2023-02-14T12:11:50.436069583Z     mapper=self._bind_mapper(), clause=querycontext.statement, **kw
2023-02-14T12:11:50.436072883Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3418, in _connection_from_session
2023-02-14T12:11:50.436076283Z     conn = self.session.connection(**kw)
2023-02-14T12:11:50.436079483Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1133, in connection
2023-02-14T12:11:50.436083383Z     execution_options=execution_options,
2023-02-14T12:11:50.436087483Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1139, in _connection_for_bind
2023-02-14T12:11:50.436092283Z     engine, execution_options
2023-02-14T12:11:50.436105384Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 432, in _connection_for_bind
2023-02-14T12:11:50.436111684Z     conn = bind._contextual_connect()
2023-02-14T12:11:50.436116184Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2251, in _contextual_connect
2023-02-14T12:11:50.436121184Z     self._wrap_pool_connect(self.pool.connect, None),
2023-02-14T12:11:50.436125984Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2285, in _wrap_pool_connect
2023-02-14T12:11:50.436131184Z     return fn()
2023-02-14T12:11:50.436135984Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 363, in connect
2023-02-14T12:11:50.436140984Z     return _ConnectionFairy._checkout(self)
2023-02-14T12:11:50.436145684Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 773, in _checkout
2023-02-14T12:11:50.436150784Z     fairy = _ConnectionRecord.checkout(pool)
2023-02-14T12:11:50.436155384Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 492, in checkout
2023-02-14T12:11:50.436160484Z     rec = pool._do_get()
2023-02-14T12:11:50.436164884Z   File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 131, in _do_get
2023-02-14T12:11:50.436169484Z     code="3o7r",
2023-02-14T12:11:50.436174284Z sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30 (Background on this error at: http://sqlalche.me/e/3o7r)
```

**Additional context**
Restarting the server is a temporary solution to continue as normal


Changed files:
vantage6-server/vantage6/server/model/user.py, vantage6-server/vantage6/server/resource/user.py, vantage6-server/vantage6/server/model/task.py, vantage6-server/vantage6/server/resource/node.py, vantage6-server/vantage6/server/model/node.py, vantage6-server/vantage6/server/model/rule.py, vantage6-server/vantage6/server/model/collaboration.py, vantage6-server/vantage6/server/resource/collaboration.py, vantage6-server/vantage6/server/resource/port.py, vantage6-server/vantage6/server/controller/query.py, vantage6-server/vantage6/server/resource/role.py, vantage6-server/vantage6/server/resource/task.py, vantage6-server/vantage6/server/model/organization.py, vantage6-server/vantage6/server/resource/organization.py, vantage6-server/vantage6/server/resource/result.py, vantage6-server/vantage6/server/model/result.py, vantage6-server/vantage6/server/permission.py, vantage6-server/vantage6/server/model/role.py, vantage6-server/vantage6/server/resource/rule.py, vantage6-server/vantage6/server/model/base.py

diff --git a/vantage6-server/vantage6/server/controller/query.py b/vantage6-server/vantage6/server/controller/query.py
index a20e1c7e..3461bef8 100644
--- a/vantage6-server/vantage6/server/controller/query.py
+++ b/vantage6-server/vantage6/server/controller/query.py
@@ -28,5 +28,6 @@ def tasks(self, collaboration: Collaboration, organization: Organization):
         .filter_by(collabotation_id=collaboration.id)\\
         .filter(Node == node.id)\\
         .all()
+    session.commit()
 
     return tasks
diff --git a/vantage6-server/vantage6/server/model/base.py b/vantage6-server/vantage6/server/model/base.py
index a04a92bd..246943b6 100644
--- a/vantage6-server/vantage6/server/model/base.py
+++ b/vantage6-server/vantage6/server/model/base.py
@@ -300,6 +300,9 @@ class ModelBase:
             except NoResultFound:
                 result = None
 
+        # Always commit to avoid that transaction is not ended in Postgres
+        session.commit()
+
         return result
 
     def save(self) -> None:
diff --git a/vantage6-server/vantage6/server/model/collaboration.py b/vantage6-server/vantage6/server/model/collaboration.py
index a0c5a5c5..7e2021be 100644
--- a/vantage6-server/vantage6/server/model/collaboration.py
+++ b/vantage6-server/vantage6/server/model/collaboration.py
@@ -42,14 +42,18 @@ class Collaboration(Base):
         collaboration found is returned."""
         session = DatabaseSessionManager.get_session()
         try:
-            return session.query(cls).filter_by(name=name).first()
+            result = session.query(cls).filter_by(name=name).first()
+            session.commit()
+            return result
         except NoResultFound:
             return None
 
     @classmethod
     def name_exists(cls, name):
         session = DatabaseSessionManager.get_session()
-        return session.query(exists().where(cls.name == name)).scalar()
+        result = session.query(exists().where(cls.name == name)).scalar()
+        session.commit()
+        return result
 
     def __repr__(self):
         number_of_organizations = len(self.organizations)
diff --git a/vantage6-server/vantage6/server/model/node.py b/vantage6-server/vantage6/server/model/node.py
index 1a90387b..501e65d1 100644
--- a/vantage6-server/vantage6/server/model/node.py
+++ b/vantage6-server/vantage6/server/model/node.py
@@ -47,6 +47,7 @@ class Node(Authenticatable):
         session = DatabaseSessionManager.get_session()
 
         nodes = session.query(cls).all()
+        session.commit()
         for node in nodes:
             is_correct_key = node.check_key(api_key)
             if is_correct_key:
@@ -66,15 +67,19 @@ class Node(Authenticatable):
         """
         session = DatabaseSessionManager.get_session()
 
-        return session.query(cls).filter_by(status='online').all()
+        result = session.query(cls).filter_by(status='online').all()
+        session.commit()
+        return result
 
     @classmethod
     def exists(cls, organization_id, collaboration_id):
         session = DatabaseSessionManager.get_session()
-        return session.query(cls).filter_by(
+        result = session.query(cls).filter_by(
             organization_id=organization_id,
             collaboration_id=collaboration_id
         ).scalar()
+        session.commit()
+        return result
 
     def __repr__(self):
         return (
diff --git a/vantage6-server/vantage6/server/model/organization.py b/vantage6-server/vantage6/server/model/organization.py
index 9544d7dc..b0eb69b1 100644
--- a/vantage6-server/vantage6/server/model/organization.py
+++ b/vantage6-server/vantage6/server/model/organization.py
@@ -41,14 +41,18 @@ class Organization(Base):
         # is already imported in model.Result
         from vantage6.server.model.result import Result
         session = DatabaseSessionManager.get_session()
-        return session.query(Result.id)\\
+        result_ids = session.query(Result.id)\\
                       .filter(Result.organization_id == self.id).all()
+        session.commit()
+        return result_ids
 
     @classmethod
     def get_by_name(cls, name):
         session = DatabaseSessionManager.get_session()
         try:
-            return session.query(cls).filter_by(name=name).first()
+            result = session.query(cls).filter_by(name=name).first()
+            session.commit()
+            return result
         except NoResultFound:
             return None
 
diff --git a/vantage6-server/vantage6/server/model/result.py b/vantage6-server/vantage6/server/model/result.py
index 9d45c7de..9890d0dc 100644
--- a/vantage6-server/vantage6/server/model/result.py
+++ b/vantage6-server/vantage6/server/model/result.py
@@ -55,6 +55,7 @@ class Result(Base):
                 .filter(self.organization_id == Node.organization_id)\\
                 .filter(Task.collaboration_id == Node.collaboration_id)\\
                 .one()
+            session.commit()
         # FIXME 2022-03-03 BvB: the following errors are not currently
         # forwarded to the user as request response. Make that happen.
         except NoResultFound:
diff --git a/vantage6-server/vantage6/server/model/role.py b/vantage6-server/vantage6/server/model/role.py
index 6ad1f1c4..57b17b9d 100644
--- a/vantage6-server/vantage6/server/model/role.py
+++ b/vantage6-server/vantage6/server/model/role.py
@@ -25,7 +25,9 @@ class Role(Base):
     def get_by_name(cls, name):
         session = DatabaseSessionManager.get_session()
         try:
-            return session.query(cls).filter_by(name=name).first()
+            result = session.query(cls).filter_by(name=name).first()
+            session.commit()
+            return result
         except NoResultFound:
             return None
 
diff --git a/vantage6-server/vantage6/server/model/rule.py b/vantage6-server/vantage6/server/model/rule.py
index a6f5b6f4..afa52f92 100644
--- a/vantage6-server/vantage6/server/model/rule.py
+++ b/vantage6-server/vantage6/server/model/rule.py
@@ -41,11 +41,13 @@ class Rule(Base):
     def get_by_(cls, name: str, scope: str, operation: str):
         session = DatabaseSessionManager.get_session()
         try:
-            return session.query(cls).filter_by(
+            result = session.query(cls).filter_by(
                 name=name,
                 operation=operation,
                 scope=scope
             ).first()
+            session.commit()
+            return result
         except NoResultFound:
             return None
 
diff --git a/vantage6-server/vantage6/server/model/task.py b/vantage6-server/vantage6/server/model/task.py
index 3ee124d3..259cbc63 100644
--- a/vantage6-server/vantage6/server/model/task.py
+++ b/vantage6-server/vantage6/server/model/task.py
@@ -80,6 +80,7 @@ class Task(Base):
     def next_run_id(cls):
         session = DatabaseSessionManager.get_session()
         max_run_id = session.query(sql.func.max(cls.run_id)).scalar()
+        session.commit()
         if max_run_id:
             return max_run_id + 1
         else:
diff --git a/vantage6-server/vantage6/server/model/user.py b/vantage6-server/vantage6/server/model/user.py
index 25fb7d43..4f89c030 100644
--- a/vantage6-server/vantage6/server/model/user.py
+++ b/vantage6-server/vantage6/server/model/user.py
@@ -141,29 +141,39 @@ class User(Authenticatable):
     @classmethod
     def get_by_username(cls, username):
         session = DatabaseSessionManager.get_session()
-        return session.query(cls).filter_by(username=username).one()
+        result = session.query(cls).filter_by(username=username).one()
+        session.commit()
+        return result
 
     @classmethod
     def get_by_email(cls, email):
         session = DatabaseSessionManager.get_session()
-        return session.query(cls).filter_by(email=email).one()
+        result = session.query(cls).filter_by(email=email).one()
+        session.commit()
+        return result
 
     @classmethod
     def get_user_list(cls, filters=None):
         session = DatabaseSessionManager.get_session()
-        return session.query(cls).all()
+        result = session.query(cls).all()
+        session.commit()
+        return result
 
     @classmethod
     def username_exists(cls, username):
         session = DatabaseSessionManager.get_session()
-        return session.query(exists().where(cls.username == username))\\
+        result = session.query(exists().where(cls.username == username))\\
             .scalar()
+        session.commit()
+        return result
 
     @classmethod
     def exists(cls, field, value):
         session = DatabaseSessionManager.get_session()
-        return session.query(exists().where(getattr(cls, field) == value))\\
+        result = session.query(exists().where(getattr(cls, field) == value))\\
             .scalar()
+        session.commit()
+        return result
 
     def can(self, resource: str, scope: Scope, operation: Operation) -> bool:
         """
diff --git a/vantage6-server/vantage6/server/permission.py b/vantage6-server/vantage6/server/permission.py
index ba4ca0cf..109ebbd0 100644
--- a/vantage6-server/vantage6/server/permission.py
+++ b/vantage6-server/vantage6/server/permission.py
@@ -176,11 +176,13 @@ class PermissionManager:
             Whenever this rule exists in the database or not
         """
         session = DatabaseSessionManager.get_session()
-        return session.query(Rule).filter_by(
+        result = session.query(Rule).filter_by(
             name=name,
             operation=operation,
             scope=scope
         ).scalar()
+        session.commit()
+        return result
 
     def verify_user_rules(self, rules):
         for rule in rules:
diff --git a/vantage6-server/vantage6/server/resource/collaboration.py b/vantage6-server/vantage6/server/resource/collaboration.py
index 1b48655d..e1323c17 100644
--- a/vantage6-server/vantage6/server/resource/collaboration.py
+++ b/vantage6-server/vantage6/server/resource/collaboration.py
@@ -1,12 +1,11 @@
 # -*- coding: utf-8 -*-
 import logging
 
-from flask import request
+from flask import request, g
 from flask_restful import reqparse
 from http import HTTPStatus
 
 from vantage6.server import db
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server.resource.pagination import Pagination
 from vantage6.server.permission import (
     Scope as S,
@@ -185,7 +184,7 @@ class Collaborations(CollaborationBase):
 
         # obtain organization from authenticated
         auth_org_id = self.obtain_organization_id()
-        q = DatabaseSessionManager.get_session().query(db.Collaboration)
+        q = g.session.query(db.Collaboration)
         args = request.args
 
         # filter by a field of this endpoint
diff --git a/vantage6-server/vantage6/server/resource/node.py b/vantage6-server/vantage6/server/resource/node.py
index 982b797a..3ca60c3c 100644
--- a/vantage6-server/vantage6/server/resource/node.py
+++ b/vantage6-server/vantage6/server/resource/node.py
@@ -12,7 +12,6 @@ from vantage6.server.resource import ServicesResources
 from vantage6.server.resource.pagination import Pagination
 from vantage6.server.permission import (Scope as S,
                                         Operation as P, PermissionManager)
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server import db
 from vantage6.server.resource.common._schema import NodeSchema
 
@@ -168,7 +167,7 @@ class Nodes(NodeBase):
 
         tags: ["Node"]
         """
-        q = DatabaseSessionManager.get_session().query(db.Node)
+        q = g.session.query(db.Node)
         auth_org_id = self.obtain_organization_id()
         args = request.args
 
diff --git a/vantage6-server/vantage6/server/resource/organization.py b/vantage6-server/vantage6/server/resource/organization.py
index d656475b..060aebc2 100644
--- a/vantage6-server/vantage6/server/resource/organization.py
+++ b/vantage6-server/vantage6/server/resource/organization.py
@@ -172,6 +172,7 @@ class Organizations(OrganizationBase):
 
         # query
         q = g.session.query(db.Organization)
+        g.session.commit()
 
         # filter by a field of this endpoint
         if 'name' in args:
@@ -190,6 +191,7 @@ class Organizations(OrganizationBase):
             collabs = g.session.query(db.Collaboration).filter(
                 db.Collaboration.organizations.any(id=auth_org.id)
             ).all()
+            g.session.commit()
 
             # list comprehension fetish, and add own organization in case
             # this organization does not participate in any collaborations yet
diff --git a/vantage6-server/vantage6/server/resource/port.py b/vantage6-server/vantage6/server/resource/port.py
index 13f37afc..a19eccc4 100644
--- a/vantage6-server/vantage6/server/resource/port.py
+++ b/vantage6-server/vantage6/server/resource/port.py
@@ -24,8 +24,6 @@ from vantage6.server.model import (
     Collaboration,
     Task
 )
-from vantage6.server.model.base import DatabaseSessionManager
-
 
 module_name = logger_name(__name__)
 log = logging.getLogger(module_name)
@@ -144,7 +142,7 @@ class Ports(PortBase):
         auth_org = self.obtain_auth_organization()
         args = request.args
 
-        q = DatabaseSessionManager.get_session().query(AlgorithmPort)
+        q = g.session.query(AlgorithmPort)
 
         # relation filters
         if 'result_id' in args:
@@ -220,8 +218,9 @@ class Ports(PortBase):
         # The only entity that is allowed to algorithm ports is the node where
         # those algorithms are running.
         result_id = data.get('result_id', '')
-        linked_result = DatabaseSessionManager.get_session().query(
-            Result).filter(Result.id == result_id).one()
+        linked_result = g.session.query(Result)\\
+                         .filter(Result.id == result_id)\\
+                         .one()
         if g.node.id != linked_result.node.id:
             return {'msg': 'You lack the permissions to do that!'},\\
                 HTTPStatus.UNAUTHORIZED
@@ -280,15 +279,15 @@ class Ports(PortBase):
         # The only entity that is allowed to delete algorithm ports is the node
         # where those algorithms are running.
         result_id = args['result_id']
-        linked_result = DatabaseSessionManager.get_session().query(
-            Result).filter(Result.id == result_id).one()
+        linked_result = g.session.query(Result)\\
+                         .filter(Result.id == result_id)\\
+                         .one()
         if g.node.id != linked_result.node.id:
             return {'msg': 'You lack the permissions to do that!'},\\
                 HTTPStatus.UNAUTHORIZED
 
         # all checks passed: delete the port entries
-        session = DatabaseSessionManager.get_session()
-        session.query(AlgorithmPort).filter(
+        session = g.session.query(AlgorithmPort).filter(
             AlgorithmPort.result_id == result_id
         ).delete()
         session.commit()
diff --git a/vantage6-server/vantage6/server/resource/result.py b/vantage6-server/vantage6/server/resource/result.py
index b5abaf3f..b6996115 100644
--- a/vantage6-server/vantage6/server/resource/result.py
+++ b/vantage6-server/vantage6/server/resource/result.py
@@ -30,8 +30,6 @@ from vantage6.server.model import (
     Collaboration,
     Organization
 )
-from vantage6.server.model.base import DatabaseSessionManager
-
 
 module_name = logger_name(__name__)
 log = logging.getLogger(module_name)
@@ -194,7 +192,7 @@ class Results(ResultBase):
         auth_org = self.obtain_auth_organization()
         args = request.args
 
-        q = DatabaseSessionManager.get_session().query(db_Result)
+        q = g.session.query(db_Result)
 
         # relation filters
         for param in ['task_id', 'organization_id', 'port']:
diff --git a/vantage6-server/vantage6/server/resource/role.py b/vantage6-server/vantage6/server/resource/role.py
index d205d84a..da720e54 100644
--- a/vantage6-server/vantage6/server/resource/role.py
+++ b/vantage6-server/vantage6/server/resource/role.py
@@ -8,7 +8,6 @@ from flask_restful import reqparse
 from sqlalchemy import or_
 
 from vantage6.server import db
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server.resource import (
     with_user,
     ServicesResources
@@ -189,7 +188,7 @@ class Roles(RoleBase):
 
         tags: ["Role"]
         """
-        q = DatabaseSessionManager.get_session().query(db.Role)
+        q = g.session.query(db.Role)
 
         auth_org_id = self.obtain_organization_id()
         args = request.args
diff --git a/vantage6-server/vantage6/server/resource/rule.py b/vantage6-server/vantage6/server/resource/rule.py
index 5f0934ac..9aa86904 100644
--- a/vantage6-server/vantage6/server/resource/rule.py
+++ b/vantage6-server/vantage6/server/resource/rule.py
@@ -3,6 +3,7 @@ import logging
 
 from http import HTTPStatus
 from flask.globals import request
+from flask import g
 
 from vantage6.server.resource import (
     with_user,
@@ -10,7 +11,6 @@ from vantage6.server.resource import (
 )
 from vantage6.common import logger_name
 from vantage6.server import db
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server.resource.common._schema import RuleSchema
 from vantage6.server.resource.pagination import Pagination
 
@@ -104,7 +104,7 @@ class Rules(ServicesResources):
 
         tags: ["Rule"]
         """
-        q = DatabaseSessionManager.get_session().query(db.Rule)
+        q = g.session.query(db.Rule)
 
         args = request.args
 
diff --git a/vantage6-server/vantage6/server/resource/task.py b/vantage6-server/vantage6/server/resource/task.py
index fac9abb0..9620017e 100644
--- a/vantage6-server/vantage6/server/resource/task.py
+++ b/vantage6-server/vantage6/server/resource/task.py
@@ -9,7 +9,6 @@ from sqlalchemy import desc
 from vantage6.common.globals import STRING_ENCODING
 from vantage6.common.task_status import TaskStatus, has_task_finished
 from vantage6.server import db
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server.permission import (
     Scope as S,
     PermissionManager,
@@ -224,7 +223,7 @@ class Tasks(TaskBase):
 
         tags: ["Task"]
         """
-        q = DatabaseSessionManager.get_session().query(db.Task)
+        q = g.session.query(db.Task)
         args = request.args
 
         # obtain organization id
@@ -335,7 +334,7 @@ class Tasks(TaskBase):
             )}, HTTPStatus.BAD_REQUEST
 
         # check if all the organizations have a registered node
-        nodes = DatabaseSessionManager.get_session().query(db.Node)\\
+        nodes = g.session.query(db.Node)\\
             .filter(db.Node.organization_id.in_(org_ids))\\
             .filter(db.Node.collaboration_id == collaboration_id)\\
             .all()
diff --git a/vantage6-server/vantage6/server/resource/user.py b/vantage6-server/vantage6/server/resource/user.py
index e962ef4c..83fadc3a 100644
--- a/vantage6-server/vantage6/server/resource/user.py
+++ b/vantage6-server/vantage6/server/resource/user.py
@@ -8,7 +8,6 @@ from flask_restful import reqparse
 
 from vantage6.common import logger_name
 from vantage6.server import db
-from vantage6.server.model.base import DatabaseSessionManager
 from vantage6.server.permission import (
     Scope as S,
     Operation as P,
@@ -195,7 +194,7 @@ class Users(UserBase):
         tags: ["User"]
         """
         args = request.args
-        q = DatabaseSessionManager.get_session().query(db.User)
+        q = g.session.query(db.User)
 
         # filter by any field of this endpoint
         for param in ['username', 'firstname', 'lastname', 'email']: