Skip to content

Make sure to avoid double refresh in background - #3

Merged
expl merged 5 commits into
expl:mainfrom
DoumanAsh:background_refresh_race_prevention
Sep 10, 2026
Merged

expl merged 5 commits into
expl:mainfrom
DoumanAsh:background_refresh_race_prevention

Conversation

@DoumanAsh

Copy link
Copy Markdown
Contributor

I was reviewing code and found potential race when performing background refresh.

So I modified test test_background_refresh_and_expire to try to simulate race between multiple tasks attempting to perform background refresh in parallel

Even under release build it is difficult to have exact reproduction

19:51 $ cargo test --release
warning: method `is_refreshing` is never used
  --> src/cache/mod.rs:96:14
   |
95 | impl JWKSCache {
   | -------------- method in this implementation
96 |     const fn is_refreshing(&self) -> bool {
   |              ^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: `jsonwebtoken-jwks-cache` (lib) generated 1 warning
warning: `jsonwebtoken-jwks-cache` (lib test) generated 1 warning (1 duplicate)
    Finished `release` profile [optimized] target(s) in 0.09s
     Running unittests src/lib.rs (target/release/deps/jsonwebtoken_jwks_cache-bb5944cb4e7a0136)

running 6 tests
test pem_set::test::test_pem_map ... ok
test cache::test::test_fetch_concurrent_from_empty ... ok
test cache::test::test_background_refresh_and_expire ... FAILED
test cache::test::test_reqwest_gcp_jwk_integration ... ok
test cache::test::test_timeout_policy ... ok
test cache::test::test_reqwest_gcp_pub_keys_integration ... ok

failures:

---- cache::test::test_background_refresh_and_expire stdout ----

thread 'cache::test::test_background_refresh_and_expire' (63294) panicked at src/cache/test.rs:161:5:
assertion `left == right` failed: Should have refreshed from IO once
  left: 4
 right: 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

I also added multiple parallel runs to test_timeout_policy to make sure it works ok under race friendly condition

@DoumanAsh

Copy link
Copy Markdown
Contributor Author

I also made safeguard to ensure refershing will not stuck and continue its attempts until JWKs get expired
dd0239c

@DoumanAsh

Copy link
Copy Markdown
Contributor Author

One more commit to introduce state guard when immediate cache update is performed to make sure state is reset even if future gets cancelled

Comment thread src/cache/mod.rs Outdated
@expl
expl merged commit 670ecd0 into expl:main Sep 10, 2026
1 check passed
@DoumanAsh
DoumanAsh deleted the background_refresh_race_prevention branch September 10, 2026 04:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants