Skip to content

Commit 125e867

Browse files
authored
Add database connection health check (baserow#5170)
1 parent fa3829d commit 125e867

3 files changed

Lines changed: 37 additions & 0 deletions

File tree

backend/src/baserow/config/celery.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,30 @@ def clear_local(*args, **kwargs):
2727
clear_db_state()
2828

2929

30+
def close_old_db_connections(sender, **kwargs):
31+
"""
32+
Close old or unusable database connections around each Celery task.
33+
34+
Calling `close_old_connections()` on both `task_prerun` and `task_postrun`
35+
ensures Django's own connection lifecycle is applied to Celery tasks, matching the
36+
documented recommendation for long-running processes.
37+
38+
Eager tasks (used in tests) are skipped because they run inside the
39+
caller's process and share its database connection/transaction.
40+
"""
41+
42+
if getattr(sender.request, "is_eager", False):
43+
return
44+
45+
from django.db import close_old_connections
46+
47+
close_old_connections()
48+
49+
3050
signals.task_prerun.connect(clear_local)
51+
signals.task_prerun.connect(close_old_db_connections)
3152
signals.task_postrun.connect(clear_local)
53+
signals.task_postrun.connect(close_old_db_connections)
3254

3355

3456
@signals.worker_process_init.connect

backend/src/baserow/config/settings/base.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,12 @@
283283

284284
DATABASE_READ_REPLICAS.append(db_key)
285285

286+
# Enable connection health checks for all database connections. This makes Django
287+
# verify that a database connection is still usable before each request/task, which
288+
# prevents "connection already closed" errors when connections are dropped by the
289+
# server, a load balancer, or a connection pooler.
290+
for _db_key in DATABASES:
291+
DATABASES[_db_key].setdefault("CONN_HEALTH_CHECKS", True)
286292

287293
DATABASE_ROUTERS = ["baserow.config.db_routers.ReadReplicaRouter"]
288294

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"type": "bug",
3+
"message": "Add database connection health check.",
4+
"issue_origin": "github",
5+
"issue_number": null,
6+
"domain": "core",
7+
"bullet_points": [],
8+
"created_at": "2026-04-12"
9+
}

0 commit comments

Comments
 (0)