# Python Script Crashes After One Hour: Spotify Token
##
- A Python script using the Spotipy library unexpectedly crashes after approximately one hour of runtime.
- The crash occurs because Spotify access tokens expire after **60 minutes** per Spotify API policy.
- Without token refresh logic, subsequent API calls fail once the token expires, causing the script to terminate.
## Root
- Spotify API tokens have a fixed **60-minute lifespan** by default.
- Initial token acquisition in the script uses `spotipy.util.prompt_for_user_token`, but the script:
- Does not implement automatic token
- Reuses the same expired token indefinitely
- Result: When the token expires (~1 hour post-authentication), any subsequent API request returns `401 Unauthorized`, crashing the script.
## Why This Happens in Real
- Token expiry is inherent to OAuth2 security protocols (used by Spotify) to minimize risks of credential leakage.
- Long-running scripts requiring continuous API access must:
- Explicitly handle token refresh workflow
- Monitor token expiration
- Infrastructure limitations prevent persistent sessions beyond token lifespan.
- Engineers often overlook token management in test/prototype code that later moves to production.
## Real-World
- **Service disruption**: Scripts fail hourly, requiring manual restart.
- **Data loss**: Mid-operation crashes lead to partial/unsaved results.
- **Operational overhead**: Continuous monitoring/intervention needed for long jobs.
- **Delayed reporting**: Automated processes (e.g., daily analytics) become unreliable.
- **User impact**: If script serves live users, expired tokens cause abrupt session termination.
## Example or
BROKEN: Token expires after 60 minutes, causing
import
from spotipy.oauth2 import
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE))
Works initially, fails after 1 hour:
results = sp.current_user_saved_tracks() # Succeeds at t=0m, throws 401 at t=
Fixed approach (adding refresh capability):
FIXED: Leverage built-in token auto-refresh via
auth_manager = SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE,
cache_handler=spotipy.MemoryCacheHandler(), # Enable token
auto_refresh=True # Critical! Automatically refresh expired
)
sp = spotipy.Spotify(auth_manager=auth_manager)
Now calls automatically refresh tokens when expired:
sp.current_user_saved_tracks() # Works
## How Senior Engineers Fix
1. **Leverage auto-refresh features**: Use `auto_refresh=True` in `SpotifyOAuth`.
2. **Cache tokens securely**: Implement disk/memory caching via `cache_handler` to persist tokens across sessions.
3. **Monitor expiration**: Programmatically check `token_info['expires_at']` against current time.
4. **Preemptive refresh**: Refresh tokens at 85-90% of lifespan (e.g., at minute 50) to avoid cliff-edge failures.
5. **Add retry logic**: Wrap API calls with exponential backoff to handle temporary token issues.
6. **Error handling**: Catch `spotipy.SpotifyException` (status 401) and trigger explicit refresh.
7. **Reuse sessions**: Persist token data to disk when script restarts to avoid re-authentication.
## Why Juniors Miss
- **Focus on functionality over longevity**: Testing scripts under 1 hour doesn’t expose the issue.
- **Ambiguous documentation**: Spotipy auto-refresh behavior isn't always highlighted to beginners.
- **OAuth unfamiliarity**: Novices treat tokens as "set-and-forget" credentials without understanding time limits.
- **No production hardening**: Prototypes rarely address long-term edge cases like token expiry.
- **Lack of error anticipation**: Not considering API failure modes beyond connectivity/data issues.
- **Copied tutorial code**: Many samples omit token refresh for brevity, inheriting flawed patterns.