Remove token/sid associations when server is exiting#5802
Conversation
This allows existing tokens to reconnect to redis after a hot or cold reload of the app. Otherwise, the old associations for the token remain in place and when the same client reconnects, it is given a new_token, since the requested token is already "taken" in redis.
There was a problem hiding this comment.
Greptile Summary
This PR adds cleanup logic to properly handle token/session ID associations when the Reflex server shuts down. The changes introduce a new disconnect_all method to the TokenManager base class that clears all token-to-session mappings, and integrates this cleanup into the application lifespan management.
The core issue being addressed is that after server restarts (hot or cold reloads), existing client tokens would be rejected because their associations remained in Redis. When clients attempted to reconnect with valid tokens, the server would treat them as "already taken" and force clients to obtain new tokens, breaking session continuity.
The implementation works by:
- Adding a
disconnect_allmethod intoken_manager.pythat collects all token-sid pairs from both mapping dictionaries (token_to_sidandsid_to_token) and callsdisconnect_tokenfor each pair - Integrating this cleanup into the lifespan management in
lifespan.pyby callingdisconnect_all()during server shutdown with proper error handling
This change fits into Reflex's broader architecture by leveraging the existing lifespan mixin system for graceful shutdown procedures and building upon the established TokenManager pattern for session management. The cleanup ensures that Redis-backed deployments maintain proper session continuity across server restarts, which is crucial for production applications where users expect seamless reconnection experiences.
Confidence score: 3/5
- This PR addresses a real issue but has some implementation concerns that could cause partial cleanup failures
- Score reflects potential edge cases with the cleanup logic and placement outside the AsyncExitStack context manager
- Pay close attention to the error handling patterns and the token-sid pair collection logic in
token_manager.py
2 files reviewed, 1 comment
CodSpeed Performance ReportMerging #5802 will not alter performanceComparing Summary
|
This allows existing tokens to reconnect to redis after a hot or cold reload of the app. Otherwise, the old associations for the token remain in place and when the same client reconnects, it is given a new_token, since the requested token is already "taken" in redis.