Skip to content

Handle Netatmo API rate limit with token refresh and retry#167961

Draft
synchopate wants to merge 1 commit intohome-assistant:devfrom
synchopate:fix/netatmo-rate-limit-retry
Draft

Handle Netatmo API rate limit with token refresh and retry#167961
synchopate wants to merge 1 commit intohome-assistant:devfrom
synchopate:fix/netatmo-rate-limit-retry

Conversation

@synchopate
Copy link
Copy Markdown

Summary

  • Netatmo API rate limit is per-token (~500 requests per time window). When rate-limited, refreshing the OAuth token immediately resets the quota and allows requests to succeed.
  • Currently, ApiThrottlingError is not specifically handled: commands (light.turn_on, cover.open_cover, etc.) fail silently and polling degrades for hours until the rate limit window expires.
  • This PR adds automatic token refresh + retry in two places:
    • api.py (async_post_request): catches ApiThrottlingError, invalidates the token, refreshes it, and retries the request. This covers all user-initiated commands.
    • data_handler.py (async_fetch_data): catches ApiThrottlingError before the generic ApiError handler, forces a token refresh so subsequent polling cycles use a fresh token with a reset quota.

Details

The key insight is that Netatmo tracks rate limits per access token, not per user or IP. By forcing expires_at = 0 on the OAuth session and calling async_ensure_token_valid(), we obtain a new token with a fresh rate limit quota.

Changes

  1. homeassistant/components/netatmo/api.py:

    • Added async_post_request override to AsyncConfigEntryNetatmoAuth
    • On ApiThrottlingError: invalidate token, refresh, retry once
    • Added imports: logging, Any, ClientResponse
    • Added _LOGGER
  2. homeassistant/components/netatmo/data_handler.py:

    • Added specific except pyatmo.ApiThrottlingError block before the generic except (NoDeviceError, ApiError) handler
    • On rate limit: force token refresh so next polling cycle succeeds

Test plan

  • Verify existing Netatmo tests pass
  • Test with a Netatmo account that hits rate limits to confirm token refresh resolves the throttling
  • Confirm that after token refresh, commands and polling resume immediately

Notes

Tested in production on a Home Assistant instance with multiple Netatmo integrations (weather, cameras, thermostats). After hitting rate limits, token refresh consistently restored full functionality immediately rather than waiting hours for the rate limit window to expire.

🤖 Generated with Claude Code

Netatmo API rate limit is per-token (~500 requests per time window).
When rate-limited, refreshing the OAuth token immediately resets the
quota. This adds automatic token refresh and retry in both api.py
(covers all commands) and data_handler.py (covers polling).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings April 11, 2026 07:55
@synchopate synchopate requested a review from cgtobi as a code owner April 11, 2026 07:55
Copy link
Copy Markdown

@home-assistant home-assistant bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello @synchopate,

When attempting to inspect the commits of your pull request for CLA signature status among all authors we encountered commit(s) which were not linked to a GitHub account, thus not allowing us to determine their status(es).

The commits that are missing a linked GitHub account are the following:

Unfortunately, we are unable to accept this pull request until this situation is corrected.

Here are your options:

  1. If you had an email address set for the commit that simply wasn't linked to your GitHub account you can link that email now and it will retroactively apply to your commits. The simplest way to do this is to click the link to one of the above commits and look for a blue question mark in a blue circle in the top left. Hovering over that bubble will show you what email address you used. Clicking on that button will take you to your email address settings on GitHub. Just add the email address on that page and you're all set. GitHub has more information about this option in their help center.

  2. If you didn't use an email address at all, it was an invalid email, or it's one you can't link to your GitHub, you will need to change the authorship information of the commit and your global Git settings so this doesn't happen again going forward. GitHub provides some great instructions on how to change your authorship information in their help center.

    • If you only made a single commit you should be able to run
      git commit --amend --author="Author Name <email@address.com>"
      
      (substituting "Author Name" and "email@address.com" for your actual information) to set the authorship information.
    • If you made more than one commit and the commit with the missing authorship information is not the most recent one you have two options:
      1. You can re-create all commits missing authorship information. This is going to be the easiest solution for developers that aren't extremely confident in their Git and command line skills.
      2. You can use this script that GitHub provides to rewrite history. Please note: this should be used only if you are very confident in your abilities and understand its impacts.
    • Whichever method you choose, I will come by to re-check the pull request once you push the fixes to this branch.

We apologize for this inconvenience, especially since it usually bites new contributors to Home Assistant. We hope you understand the need for us to protect ourselves and the great community we all have built legally. The best thing to come out of this is that you only need to fix this once and it benefits the entire Home Assistant and GitHub community.

Thanks, I look forward to checking this PR again soon! ❤️

@home-assistant home-assistant bot added cla-error integration: netatmo Top 200 Integration is ranked within the top 200 by usage labels Apr 11, 2026
@home-assistant home-assistant bot marked this pull request as draft April 11, 2026 07:55
@home-assistant
Copy link
Copy Markdown

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant
Copy link
Copy Markdown

Hey there @cgtobi, mind taking a look at this pull request as it has been labeled with an integration (netatmo) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of netatmo can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant mark-draft Mark the pull request as draft.
  • @home-assistant ready-for-review Remove the draft status from the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign netatmo Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant update-branch Update the pull request branch with the base branch.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) on the pull request.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds Netatmo-specific handling for per-token rate limiting by forcing an OAuth token refresh and retrying requests/polling when ApiThrottlingError is raised.

Changes:

  • Add async_post_request override that refreshes the OAuth token and retries once on ApiThrottlingError
  • Add rate-limit exception handling during polling to force a token refresh for subsequent cycles

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
homeassistant/components/netatmo/api.py Retry POST requests once after forcing an OAuth token refresh on throttling
homeassistant/components/netatmo/data_handler.py Detect throttling during periodic fetch and force token refresh for later polls

Comment on lines +59 to +64
return await super().async_post_request(url, params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params)
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both calls pass params positionally into super().async_post_request(...). If the superclass signature differs (e.g., has additional positional args or uses a different second parameter), this can break at runtime. Prefer passing by keyword to make the call resilient to signature changes: call super().async_post_request(url, params=params) in both places.

Suggested change
return await super().async_post_request(url, params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params)
return await super().async_post_request(url, params=params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params=params)

Copilot uses AI. Check for mistakes.
Comment on lines +59 to +64
return await super().async_post_request(url, params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params)
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both calls pass params positionally into super().async_post_request(...). If the superclass signature differs (e.g., has additional positional args or uses a different second parameter), this can break at runtime. Prefer passing by keyword to make the call resilient to signature changes: call super().async_post_request(url, params=params) in both places.

Suggested change
return await super().async_post_request(url, params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params)
return await super().async_post_request(url, params=params)
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params=params)

Copilot uses AI. Check for mistakes.
Comment on lines +60 to +64
except pyatmo.ApiThrottlingError:
_LOGGER.warning("Rate limit hit, refreshing token and retrying: %s", url)
self._oauth_session.token["expires_at"] = 0
await self._oauth_session.async_ensure_token_valid()
return await super().async_post_request(url, params)
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Token refresh is performed without synchronization. If multiple concurrent commands hit the rate limit at the same time, they can race on self._oauth_session.token updates and trigger multiple refreshes, potentially causing unnecessary auth traffic and inconsistent token state. Consider guarding the refresh+retry path with an asyncio.Lock shared by the auth instance (and re-checking token validity after acquiring it) so only one refresh happens at a time.

Copilot uses AI. Check for mistakes.
Comment on lines +252 to +257
try:
self.auth._oauth_session.token["expires_at"] = 0
await self.auth._oauth_session.async_ensure_token_valid()
_LOGGER.info("Token refreshed successfully after rate limit")
except Exception:
_LOGGER.exception("Failed to refresh token after rate limit")
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Catching a bare Exception here will also catch asyncio.CancelledError (common during shutdown/unload), which can prevent proper task cancellation. Prefer either (a) explicitly re-raising asyncio.CancelledError, or (b) narrowing the except clause to the expected refresh-related exception types so cancellations and other control-flow exceptions propagate correctly.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla-error integration: netatmo Quality Scale: No score Top 200 Integration is ranked within the top 200 by usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants