Skip to content

Commit

Permalink
Add jitter to backup start time to avoid thundering herd (#135065)
Browse files Browse the repository at this point in the history
  • Loading branch information
emontnemery authored and bramkragten committed Jan 9, 2025
1 parent b8b7daf commit 42cdd25
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
7 changes: 7 additions & 0 deletions homeassistant/components/backup/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta
from enum import StrEnum
import random
from typing import TYPE_CHECKING, Self, TypedDict

from cronsim import CronSim
Expand All @@ -28,6 +29,10 @@
CRON_PATTERN_DAILY = "45 4 * * *"
CRON_PATTERN_WEEKLY = "45 4 * * {}"

# Randomize the start time of the backup by up to 60 minutes to avoid
# all backups running at the same time.
BACKUP_START_TIME_JITTER = 60 * 60


class StoredBackupConfig(TypedDict):
"""Represent the stored backup config."""
Expand Down Expand Up @@ -329,6 +334,8 @@ async def _create_backup(now: datetime) -> None:
except Exception: # noqa: BLE001
LOGGER.exception("Unexpected error creating automatic backup")

next_time += timedelta(seconds=random.randint(0, BACKUP_START_TIME_JITTER))
LOGGER.debug("Scheduling next automatic backup at %s", next_time)
manager.remove_next_backup_event = async_track_point_in_time(
manager.hass, _create_backup, next_time
)
Expand Down
2 changes: 2 additions & 0 deletions tests/components/backup/test_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -1345,6 +1345,7 @@ async def test_config_update_errors(
),
],
)
@patch("homeassistant.components.backup.config.BACKUP_START_TIME_JITTER", 0)
async def test_config_schedule_logic(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
Expand Down Expand Up @@ -1787,6 +1788,7 @@ async def test_config_schedule_logic(
),
],
)
@patch("homeassistant.components.backup.config.BACKUP_START_TIME_JITTER", 0)
async def test_config_retention_copies_logic(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
Expand Down

0 comments on commit 42cdd25

Please sign in to comment.