Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(sync): configure the automatic bank sync minimum interval (#1283)

Superesty1fb11418da36
diff --git a/README.md b/README.md
index e39fd5e9..8d88bee0 100644
--- a/README.md
+++ b/README.md
@@ -71,6 +71,8 @@ PLUGGY_CLIENT_ID=your-client-id
PLUGGY_CLIENT_SECRET=your-client-secret
```
+See [automatic bank synchronization](docs/automatic-bank-sync.md) to configure the minimum polling interval (including PSD2 four-access-per-day limits).
+
### Enable Banking — European banks (PSD2)
Sign up at [enablebanking.com](https://enablebanking.com), create a Production application, and download its PEM private key. Save the PEM to `./secrets/` (gitignored), then add:
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 21a32098..bac3b395 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -1,4 +1,6 @@
+from datetime import datetime, timedelta, timezone
from functools import lru_cache
+from math import isfinite
from os import getenv
from pathlib import Path
@@ -128,6 +130,19 @@ class Settings(BaseSettings):
# Celery
redis_url: str = "redis://localhost:6379/0"
+ # Minimum age of a successful sync before automatic polling retries it.
+ # Set to 6 for banks limiting unattended account access to four times/day.
+ bank_sync_min_interval_hours: float = 4
+
+ @model_validator(mode="after")
+ def validate_bank_sync_interval(self):
+ if not isfinite(self.bank_sync_min_interval_hours) or self.bank_sync_min_interval_hours <= 0:
+ raise ValueError("BANK_SYNC_MIN_INTERVAL_HOURS must be finite and positive")
+ try:
+ datetime.now(timezone.utc) - timedelta(hours=self.bank_sync_min_interval_hours)
+ except OverflowError as exc:
+ raise ValueError("BANK_SYNC_MIN_INTERVAL_HOURS exceeds the supported date range") from exc
+ return self
# Reverse-proxy trust for client-IP-based rate limiting. 0 (default) means
# request.client.host is used as-is, which is only correct when nothing
diff --git a/backend/app/tasks/sync_tasks.py b/backend/app/tasks/sync_tasks.py
index ef74fdff..44258e17 100644
--- a/backend/app/tasks/sync_tasks.py
+++ b/backend/app/tasks/sync_tasks.py
@@ -20,7 +20,6 @@ from app.services import connection_service
logger = logging.getLogger(__name__)
-STALE_THRESHOLD = timedelta(hours=4)
PROVIDER_REFRESH_THRESHOLD = timedelta(hours=20)
@@ -47,7 +46,9 @@ async def _sync_all() -> int:
"""Find stale connections and sync each one."""
engine, session_maker = _make_session_maker()
try:
- cutoff = datetime.now(timezone.utc) - STALE_THRESHOLD
+ cutoff = datetime.now(timezone.utc) - timedelta(
+ hours=get_settings().bank_sync_min_interval_hours
+ )
synced = 0
async with session_maker() as session:
diff --git a/backend/app/worker.py b/backend/app/worker.py
index 6c490b99..cdb95035 100644
--- a/backend/app/worker.py
+++ b/backend/app/worker.py
@@ -21,7 +21,7 @@ celery_app.conf.update(
celery_app.conf.beat_schedule = {
"sync-all-connections-hourly": {
"task": "app.tasks.sync_tasks.sync_all_connections",
- "schedule": 60 * 60, # every hour; task itself skips connections synced < 4h ago
+ "schedule": 60 * 60, # hourly; task applies BANK_SYNC_MIN_INTERVAL_HOURS
},
"generate-recurring-daily": {
"task": "app.tasks.recurring_tasks.generate_all_recurring",
diff --git a/backend/tests/test_bank_sync_interval.py b/backend/tests/test_bank_sync_interval.py
new file mode 100644
index 00000000..9ed4b503
--- /dev/null
+++ b/backend/tests/test_bank_sync_interval.py
@@ -0,0 +1,67 @@
+"""Exercise automatic eligibility against the real SQL selection, with no bank IO."""
+import uuid
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock, patch
+from zoneinfo import ZoneInfo
+
+import pytest
+from pydantic import ValidationError
+
+from app.core.config import Settings
+from app.models.bank_connection import BankConnection
+from app.tasks.sync_tasks import _sync_all
+
+
+def test_default_interval_is_four_hours(monkeypatch):
+ monkeypatch.delenv("BANK_SYNC_MIN_INTERVAL_HOURS", raising=False)
+ assert Settings(_env_file=None, _secrets_dir=None).bank_sync_min_interval_hours == 4
+
+
[email protected]("value", ["6", "0.5"])
+def test_interval_from_environment(monkeypatch, value):
+ monkeypatch.setenv("BANK_SYNC_MIN_INTERVAL_HOURS", value)
+ assert Settings(_env_file=None, _secrets_dir=None).bank_sync_min_interval_hours == float(value)
+
+
[email protected]("value", ["0", "-1", "nan", "inf", "-inf", "invalid", "1e12", "1e8"])
+def test_invalid_intervals_rejected(monkeypatch, value):
+ monkeypatch.setenv("BANK_SYNC_MIN_INTERVAL_HOURS", value)
+ with pytest.raises(ValidationError):
+ Settings(_env_file=None, _secrets_dir=None)
+
+
[email protected]("hours", [4, 6])
+async def test_automatic_sync_honors_interval_and_status(
+ session, test_user, test_workspace, hours,
+):
+ now = datetime(2026, 1, 15, 12, tzinfo=timezone.utc)
+ rows = []
+ # At the exact boundary the existing strict-older-than behavior is retained.
+ cases = [(hours - 0.01, "active", False), (hours, "active", False),
+ (hours + 0.01, "active", True), (None, "active", True),
+ (hours + 1, "error", True), (hours + 1, "expired", False)]
+ for age, status, eligible in cases:
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ provider="test", external_id=str(uuid.uuid4()), institution_name="Test bank",
+ credentials={"synthetic": True}, status=status, created_at=now,
+ last_sync_at=now - timedelta(hours=age) if age is not None else None,
+ )
+ session.add(conn)
+ rows.append((conn.id, eligible))
+ await session.commit()
+ expected = {conn_id for conn_id, eligible in rows if eligible}
+ engine = AsyncMock()
+ sync_one = AsyncMock()
+ settings = Settings(bank_sync_min_interval_hours=hours, _env_file=None, _secrets_dir=None)
+ with patch("app.tasks.sync_tasks._make_session_maker", return_value=(engine, lambda: session)), \
+ patch("app.tasks.sync_tasks.get_settings", return_value=settings), \
+ patch("app.tasks.sync_tasks.get_timezone", new_callable=AsyncMock,
+ return_value=ZoneInfo("UTC")), \
+ patch("app.tasks.sync_tasks.datetime") as clock, \
+ patch("app.tasks.sync_tasks._sync_one", sync_one):
+ clock.now.return_value = now
+ assert await _sync_all() == len(expected)
+ assert {call.args[1] for call in sync_one.await_args_list} == expected
+ engine.dispose.assert_awaited_once()
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
index 1a702a6a..da32b546 100644
--- a/docker-compose.prod.yml
+++ b/docker-compose.prod.yml
@@ -44,6 +44,7 @@ x-backend-env: &backend-env
# client IP instead of nginx's own container address.
TRUSTED_PROXY_HOPS: ${TRUSTED_PROXY_HOPS:-1}
REDIS_URL: redis://redis:6379/0
+ BANK_SYNC_MIN_INTERVAL_HOURS: ${BANK_SYNC_MIN_INTERVAL_HOURS:-4}
STORAGE_LOCAL_PATH: /app/data/attachments
AGENTS_KNOWLEDGE_STORAGE_PATH: /app/data/agent_knowledge
# Agents/LLM feature, opt-in. Off by default so existing users pay
diff --git a/docker-compose.yml b/docker-compose.yml
index 5f49981a..e8870ec8 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -44,6 +44,7 @@ x-backend-env: &backend-env
OIDC_WORKSPACE_ROLE_MAP: ${OIDC_WORKSPACE_ROLE_MAP:-}
LOCAL_AUTH_ENABLED: ${LOCAL_AUTH_ENABLED:-true}
REDIS_URL: redis://redis:6379/0
+ BANK_SYNC_MIN_INTERVAL_HOURS: ${BANK_SYNC_MIN_INTERVAL_HOURS:-4}
OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}
FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}
TESOURO_DIRETO_ENABLED: ${TESOURO_DIRETO_ENABLED:-true}
diff --git a/docs/automatic-bank-sync.md b/docs/automatic-bank-sync.md
new file mode 100644
index 00000000..4a624523
--- /dev/null
+++ b/docs/automatic-bank-sync.md
@@ -0,0 +1,31 @@
+# Automatic bank synchronization
+
+`BANK_SYNC_MIN_INTERVAL_HOURS` controls how old the last successful bank sync
+must be before a connection is eligible for automatic synchronization.
+The default is **4 hours**, preserving the previous behavior. Any finite,
+positive number of hours within Python's supported date range is accepted;
+zero, negative/non-finite values and intervals that overflow the sync cutoff
+fail startup validation.
+
+Celery beat still checks hourly. Connections with no previous successful sync
+remain eligible, and manual/on-demand synchronization is unchanged. A connection
+is selected only when `last_sync_at` is strictly older than the cutoff, as before;
+therefore the actual period can be longer than the configured minimum by up to
+one polling tick (plus execution time). Startup-triggered automatic syncs use
+the same eligibility filter.
+
+## PSD2 unattended access
+
+Banks may limit unattended account-information access to **four times per day**
+under [Article 36(5)(b) of Delegated Regulation (EU) 2018/389](https://eur-lex.europa.eu/eli/reg_del/2018/389/oj).
+For those banks, set `BANK_SYNC_MIN_INTERVAL_HOURS=6` in the worker environment.
+The supplied development and production Compose files pass it through the shared
+backend environment to API/worker/beat processes. Restart processes after changing
+configuration. This setting applies to all bank providers, not just Enable Banking.
+
+This is a spacing policy, **not a strict rolling request quota**: failures and
+rate-limited runs do not advance `last_sync_at`, so they remain eligible on later
+hourly checks. Manual syncs, multiple connections to the same bank and paginated
+or retried provider requests may also consume access. A six-hour interval alone
+does not guarantee compliance with every bank's per-resource accounting policy.
+There is no change to provider refresh strategy or transaction fetch windows.