Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions backend/src/baserow/config/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,30 @@ def clear_local(*args, **kwargs):
clear_db_state()


def close_old_db_connections(sender, **kwargs):
"""
Close old or unusable database connections around each Celery task.

Calling `close_old_connections()` on both `task_prerun` and `task_postrun`
ensures Django's own connection lifecycle is applied to Celery tasks, matching the
documented recommendation for long-running processes.

Eager tasks (used in tests) are skipped because they run inside the
caller's process and share its database connection/transaction.
"""

if getattr(sender.request, "is_eager", False):
return

from django.db import close_old_connections

close_old_connections()


signals.task_prerun.connect(clear_local)
signals.task_prerun.connect(close_old_db_connections)
signals.task_postrun.connect(clear_local)
signals.task_postrun.connect(close_old_db_connections)


@signals.worker_process_init.connect
Expand Down
6 changes: 6 additions & 0 deletions backend/src/baserow/config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,12 @@

DATABASE_READ_REPLICAS.append(db_key)

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

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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"type": "bug",
"message": "Add database connection health check.",
"issue_origin": "github",
"issue_number": null,
"domain": "core",
"bullet_points": [],
"created_at": "2026-04-12"
}
Loading