﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35672	Using database connection pooling, threads do not return the connection	André S. Hansen		"I am testing the new db connection pooling, which increased the performance greatly, typically lowering api response times from 30ms -> 20ms on my dev env.

**However, after a while i started getting** 
{{{
psycopg_pool.PoolTimeout : couldn't get a connection after 30.00 sec
}}}

Further investigation shows the reason was a Threaded Middleware orm interaction, like this simplified code. My theory is that the thread request and receives a connection from the pool, but do not return it.

{{{
class TimeMonitorMiddleware(object):
    batched_logs: List[RequestLog] = []

    def __call__(self, request: WSGIRequest) -> HttpResponse:
        # ...
  
        # Save batched logs
        if len(self.batched_logs) >= 50:
            Thread(target=RequestLog.objects.bulk_create, args=(batched_logs,)).start()

        return response
}}}





**Using settings**
{{{
{
   ""ENGINE"": os.environ.get(""DB_ENGINE"", ""django.db.backends.postgresql""),
   ""OPTIONS"": {""pool"": True}
}
}}}

**Extra info:**
- Python 3.12.1
- Django 5.1
- psycopg 3.2.1
- psycopg-pool 3.2.2
- Local docker image hosted postgresql database using image ""postgres"""	Bug	closed	Database layer (models, ORM)	5.1	Normal	invalid		Florian Apolloner	Unreviewed	0	0	0	0	0	0
