When caching heavyweight clients or connections, treat authentication identity (tokens/secret_arn/derived ARN) as part of cache correctness—not just cache performance.
Standards: 1) Separate lifecycle vs performance caches
2) Cache keys must include auth identity
secret_arn (or resolved ARN chain), the cache entry must be keyed on that value (or equivalent). Otherwise, different-secret reconnects will overwrite or reuse the wrong live handle.3) Resolve-and-compare before lookup when identity is derived
4) Refresh auth right before use
5) Keep cache hits truly “offline”
6) Eviction/replace must clean up
set().Example (pattern):
# Pseudocode: secret_arn-aware cache with resolve-before-lookup
resolved_secret_arn = resolve_secret_arn(config_or_rds_metadata())
cached = conn_cache.get(key_without_secret_id, secret_arn=resolved_secret_arn)
if cached is not None:
return cached # cache hit stays correct
# cache miss (or wrong secret): create fresh connection
conn = create_db_connection(secret_arn=resolved_secret_arn)
validate_or_open(conn) # optional, but if you do it, evict on failure
conn_cache.set(key_without_secret_id, secret_arn=resolved_secret_arn, conn=conn)
return conn
Apply these rules to any in-process caching of boto3 clients, DB connections/pools, or auth-derived resources to prevent stale-credential behavior and resource leaks while preserving the performance benefits of caching.