Skip to content

Bug: Token expiration buffer causes premature refreshes #41

@knowlen

Description

@knowlen

Description

As identified in PR #32 review, the conservative token expiration logic (60-second buffer) could cause unnecessary token refreshes, especially for long-lived tokens.

Current Implementation

@property
def is_expired(self) -> bool:
    if not self.expires_at:
        return True
    # Conservative approach - consider expired 60 seconds before actual expiry
    return datetime.now(UTC) >= (self.expires_at - timedelta(seconds=60))

Problems

  1. 60-second buffer may be too conservative for tokens with long lifetimes
  2. Could cause unnecessary API calls for token refresh
  3. Fixed buffer doesn't account for token lifetime

Proposed Solutions

1. Configurable Buffer

TOKEN_EXPIRY_BUFFER = int(os.getenv('ESOLOGS_TOKEN_EXPIRY_BUFFER', '60'))

@property
def is_expired(self) -> bool:
    if not self.expires_at:
        return True
    buffer = timedelta(seconds=TOKEN_EXPIRY_BUFFER)
    return datetime.now(UTC) >= (self.expires_at - buffer)

2. Smart Buffer Based on Token Lifetime

@property
def is_expired(self) -> bool:
    if not self.expires_at:
        return True
    
    # Calculate buffer as percentage of token lifetime
    token_lifetime = self.expires_at - self.created_at
    # Use 5% of lifetime or 60 seconds, whichever is smaller
    buffer_seconds = min(token_lifetime.total_seconds() * 0.05, 60)
    buffer = timedelta(seconds=buffer_seconds)
    
    return datetime.now(UTC) >= (self.expires_at - buffer)

3. Add Methods for Different Use Cases

def is_expired(self, buffer_seconds: int = 60) -> bool:
    '''Check if token is expired with configurable buffer'''
    
def will_expire_soon(self, seconds: int = 300) -> bool:
    '''Check if token will expire within specified seconds'''
    
def time_until_expiry(self) -> Optional[timedelta]:
    '''Get remaining token lifetime'''

Benefits

  • Reduced unnecessary token refreshes
  • More flexible for different use cases
  • Better performance for long-running applications

Testing Considerations

  • Test with various token lifetimes
  • Test edge cases (very short/long tokens)
  • Test clock skew scenarios

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions