An open source, non-profit web search engine
Prevent duplicate periodic background tasks on multiprocess startup
Daoud Clarke1ea4bf4f21f1
diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex dd2243e..51cb002 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -44,6 +44,11 @@ class MwmblConfig(AppConfig):create_index_db()self._schedule_background_tasks()+ # Cache key guarding the scheduling critical section below. Held just long+ # enough to cover a single deploy's worker-startup burst.+ _SCHEDULE_LOCK_KEY = "mwmbl:schedule_background_tasks_lock"+ _SCHEDULE_LOCK_TIMEOUT = 60+@staticmethoddef _schedule_background_tasks():"""@@ -65,6 +70,21 @@ class MwmblConfig(AppConfig):except RuntimeError:pass+ # The gunicorn server runs multiple worker processes, each of which calls+ # this method independently on startup. The "does a Task row already+ # exist?" checks below are plain reads with no transaction or unique+ # constraint backing them, so without this lock, workers starting at the+ # same time (every deploy/restart) can race past the check before any of+ # them commits its Task row, each creating its own duplicate periodic+ # task. cache.add() is atomic (same pattern as the rate limiter in+ # mwmbl.quota), so only the first worker to reach this point proceeds;+ # the rest skip immediately, and the lock's TTL simply bounds how long+ # a crashed winner blocks a retry by a later-starting worker.+ from django.core.cache import cache+ if not cache.add(MwmblConfig._SCHEDULE_LOCK_KEY, "1", timeout=MwmblConfig._SCHEDULE_LOCK_TIMEOUT):+ log.info("Skipping background task scheduling: another worker is already handling it.")+ return+try:from background_task.models import Taskfrom mwmbl.background import sync_search_counts, report_usage_to_polar@@ -81,5 +101,8 @@ class MwmblConfig(AppConfig):report_usage_to_polar(repeat=3600, repeat_until=None)except Exception:- # Don't prevent startup if background task scheduling fails+ # Don't prevent startup if background task scheduling fails. Release+ # the lock so a later-starting worker can retry instead of waiting+ # out the full TTL.log.exception("Failed to schedule background tasks")+ cache.delete(MwmblConfig._SCHEDULE_LOCK_KEY)diff --git a/test/test_apps_background_scheduling.py b/test/test_apps_background_scheduling.pynew file mode 100644index 0000000..f9dd4f6--- /dev/null+++ b/test/test_apps_background_scheduling.py@@ -0,0 +1,67 @@+"""+Tests for MwmblConfig._schedule_background_tasks().++Covers the cache-lock guard added to prevent duplicate periodic Task rows+when multiple gunicorn worker processes call AppConfig.ready() on startup.+"""++from unittest.mock import patch++import pytest+from background_task.models import Task+from django.core.cache import cache++from mwmbl.apps import MwmblConfig++SYNC_TASK = "mwmbl.background.sync_search_counts"+POLAR_REPORT_TASK = "mwmbl.background.report_usage_to_polar"++[email protected](autouse=True)+def clear_schedule_lock():+ cache.delete(MwmblConfig._SCHEDULE_LOCK_KEY)+ yield+ cache.delete(MwmblConfig._SCHEDULE_LOCK_KEY)+++def test_schedule_background_tasks_creates_both_tasks():+ MwmblConfig._schedule_background_tasks()++ assert Task.objects.filter(task_name=SYNC_TASK).count() == 1+ assert Task.objects.filter(task_name=POLAR_REPORT_TASK).count() == 1+++def test_schedule_background_tasks_skips_when_lock_already_held():+ """Simulates a second gunicorn worker starting while the first is scheduling."""+ assert cache.add(MwmblConfig._SCHEDULE_LOCK_KEY, "1", timeout=60)++ MwmblConfig._schedule_background_tasks()++ assert Task.objects.filter(task_name=SYNC_TASK).count() == 0+ assert Task.objects.filter(task_name=POLAR_REPORT_TASK).count() == 0+++def test_schedule_background_tasks_second_call_does_not_duplicate():+ MwmblConfig._schedule_background_tasks()+ cache.delete(MwmblConfig._SCHEDULE_LOCK_KEY) # as if a later worker acquires the lock next+ MwmblConfig._schedule_background_tasks()++ assert Task.objects.filter(task_name=SYNC_TASK).count() == 1+ assert Task.objects.filter(task_name=POLAR_REPORT_TASK).count() == 1+++def test_schedule_background_tasks_releases_lock_on_failure():+ with patch("mwmbl.background.sync_search_counts", side_effect=RuntimeError("boom")):+ MwmblConfig._schedule_background_tasks()++ assert Task.objects.filter(task_name=SYNC_TASK).count() == 0+ # Lock was released so a later-starting worker isn't blocked for the full TTL.+ assert cache.get(MwmblConfig._SCHEDULE_LOCK_KEY) is None++ MwmblConfig._schedule_background_tasks()+ assert Task.objects.filter(task_name=SYNC_TASK).count() == 1+ assert Task.objects.filter(task_name=POLAR_REPORT_TASK).count() == 1