> For the complete documentation index, see [llms.txt](https://help.tahua.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.tahua.io/product-news/2026/july/automatically-expire-stale-xero-connections-after-55-days-of-inactivity.md).

# Automatically expire stale Xero connections after 55 days of inactivity

## Problem

Xero refresh tokens expire after 60 days of non-use. Once a refresh token has expired, the application can no longer obtain a new access token, which means the Xero connection silently fails. Worse, by that point the API call needed to formally revoke the connection (`DELETE /connections/{id}`) cannot be made because it requires a valid access token — creating a situation where the connection cannot be cleaned up through the API at all.

## Solution

A daily background job proactively disconnects Xero connections that have been unused for 55 days — 5 days before the refresh token expires — while the token is still valid. This allows the app to formally revoke the connection on Xero's side and clean up local credentials in an orderly way.

## How it works

1. **Activity tracking**: Every successful Xero API call now updates a `xero_last_used_at` timestamp on the organisation. To avoid excessive database writes, this is throttled to once per hour.
2. **Daily expiry job** (`FundingSystem::Xero::ExpireStaleConnectionsJob`): Runs nightly at 3am. Finds all organisations where:
   * `xero_last_used_at` is populated (organisations connected before this feature was introduced are skipped as a safe default)
   * `xero_last_used_at` is older than 55 days
   * Xero OAuth2 tokens are still present
3. **Disconnection**: For each stale organisation, the job:
   * Attempts a proper API disconnect (`DELETE https://api.xero.com/connections/{id}`)
   * Clears all stored OAuth2 credentials regardless of whether the API call succeeded
   * Logs a `xero_connection_expired` security event (visible in Admin → Settings → Security Events)

Organisations whose Xero connection is cleared will see the standard "not connected" status in the Xero integration settings and can reconnect at any time.

## Deployment note

The `expire_stale_xero_connections` schedule must be added to `config/sidekiq.yml` in each host app. See CHANGELOG.md for the required configuration snippet.
