Spring › Feature

Preventing Refresh Token Rotation race conditions with Redis

Fix multi-tab Refresh Token Rotation race conditions using atomic Redis Lua scripts, theft detection, and client-side request serialization.

Preventing Refresh Token Rotation race conditions with Redis

Refresh Token Rotation (RTR) tightens JWT security, but concurrent API calls across browser tabs quickly turn it into a race condition that logs users out. This post walks through how I fixed those false-positive revocations using an atomic Redis Lua script, theft detection, and client-side serialization.


Why I moved from static refresh tokens to RTR

Every JWT-based authentication setup runs into the same tension between access token lifetime and refresh token exposure.

Even if you keep access tokens short-lived (15 to 60 minutes), a static refresh token valid for 14 or 30 days creates a wide attack window. If an attacker steals that token through XSS or a compromised device, they can mint fresh access tokens for weeks. Unless the server tracks every refresh token explicitly, you won’t even notice the compromise.

To narrow that window, I implemented Refresh Token Rotation (RTR).

sequenceDiagram
    autonumber
    actor Client as Browser (Client)
    participant Server as Auth Server (Spring Boot)
    participant Redis as Session Store (Redis)
    Client->>Server: POST /api/v1/auth/refresh (RT-1)
    Server->>Redis: Validate RT-1 and mark rotated
    Server->>Redis: Store new RT-2 metadata
    Server-->>Client: Return new AT-2 + RT-2
    Note over Client,Server: Subsequent requests must use RT-2

RTR follows one strict rule: a refresh token is single-use and gets replaced every time it’s exchanged.

Following the OAuth 2.0 Threat Model (RFC 6749) and OAuth 2.0 Security Best Current Practice, I paired rotation with reuse detection. If a client sends a refresh token that has already been rotated, the server treats it as a token theft attempt and revokes every active session for that user immediately.


The problem: multi-tab race conditions and false logouts

Everything worked fine during single-request local testing. The failure showed up as soon as I hooked up the frontend and tested real browsing patterns: multiple open tabs and parallel API calls on page load.

When a user opens the dashboard, the page fires three or four asynchronous API calls at once—profile, notifications, recent activity, and so on. If the access token just expired, all of those requests fail with 401 Unauthorized within the same millisecond and hit /api/v1/auth/refresh simultaneously with the exact same refresh token (RT-1).

sequenceDiagram
    autonumber
    actor TabA as Tab A (Request 1)
    actor TabB as Tab B (Request 2)
    participant Server as Spring Boot (Thread Pool)
    participant Redis as Redis
    TabA->>Server: POST /refresh (RT-1)
    TabB->>Server: POST /refresh (RT-1)

    Note over Server,Redis: Threads A and B race on Read-Modify-Write
    Server->>Redis: Thread A: read RT-1 -> valid
    Server->>Redis: Thread B: read RT-1 -> valid

    Server->>Redis: Thread A: mark RT-1 rotated & issue RT-2
    Server-->>TabA: 200 OK (AT-2 + RT-2)

    Server->>Redis: Thread B: attempts rotation -> already used
    Note over Server: Thread B flags RT-1 reuse as theft
    Server->>Redis: Trigger theft detection: Revoke All
    Server-->>TabB: 401 Unauthorized (REUSED_REFRESH_TOKEN)

A standard application-layer findById() → check → save() flow is a textbook Read-Modify-Write race. Threads interleave between the read and the write, so atomicity breaks down.

In practice, a normal user with two tabs open triggered the reuse detector. The second thread flagged the user as an attacker, wiped every session across all devices, and forced an unexpected logout.


Step 1: Atomic token consumption with a Redis Lua script

I considered using a distributed lock like Redisson here, but token refresh sits directly on the user’s critical path. Acquiring and releasing a separate lock adds extra network round trips and lock-contention overhead. Because Redis executes Lua scripts atomically on its single command thread, I can validate and mark a token as rotated in one round trip (1 RTT) with no external lock.

First, here is the Redis hash model for stored refresh tokens. I store only a one-way SHA-256 hash of the raw token so a Redis leak doesn’t expose usable credentials, and I keep a rotatedAt field to record when the token was consumed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/main/kotlin/com/example/server/auth/domain/RefreshToken.kt
package com.example.server.auth.domain

import java.time.Instant
import org.springframework.data.annotation.Id
import org.springframework.data.redis.core.RedisHash
import org.springframework.data.redis.core.TimeToLive
import org.springframework.data.redis.core.index.Indexed

@RedisHash("refreshToken")
class RefreshToken(
    @Id
    val tokenHash: String,

    @Indexed
    val userId: String,

    val userAgent: String?,
    val clientIp: String,
    val createdAt: Instant = Instant.now(),
    var rotatedAt: Instant? = null,

    val tokenVersion: String = "",

    @TimeToLive
    var ttlSeconds: Long,
)

Here is what the stored hash looks like in redis-cli:

Redis CLI showing refresh token hash metadata including tokenVersion and rotatedAt Figure 1. Refresh token hash fields stored in Redis, including tokenVersion and rotatedAt.

The design detail that makes theft detection work is not deleting the key immediately on rotation. Instead, the Lua script keeps the key and its remaining TTL intact while atomically setting rotatedAt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// src/main/kotlin/com/example/server/auth/application/TokenService.kt
package com.example.server.auth.application

import com.example.server.auth.AuthErrorCode
import com.example.server.auth.domain.RefreshToken
import com.example.server.auth.domain.RefreshTokenRepository
import com.example.server.auth.dto.response.TokenResponse
import com.example.server.common.BusinessException
import com.example.server.security.jwt.JwtProperties
import com.example.server.security.jwt.JwtProvider
import com.example.server.security.user.AuthUser
import com.example.server.user.domain.UserRepository
import java.security.MessageDigest
import java.time.Instant
import java.util.Base64
import java.util.UUID
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.script.DefaultRedisScript
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class TokenService(
    private val jwtProvider: JwtProvider,
    private val jwtProperties: JwtProperties,
    private val refreshTokenRepository: RefreshTokenRepository,
    private val userRepository: UserRepository,
    private val redis: StringRedisTemplate,
    private val tokenVersions: TokenVersionStore,
) {

    @Transactional(readOnly = true)
    fun rotate(refreshToken: String): TokenResponse {
        val tokenHash = hash(refreshToken)
        val stored = refreshTokenRepository.findById(tokenHash).orElse(null)
            ?: throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)

        if (stored.tokenVersion != tokenVersions.current(stored.userId)) {
            throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)
        }

        // Atomically verify existence and mark rotatedAt in a single Redis command
        when (redis.execute(ROTATE_SCRIPT, listOf("refreshToken:$tokenHash"), Instant.now().toString())) {
            1L -> Unit // First valid consumption succeeded
            2L -> {
                // Already rotated token reused -> trigger theft detection
                revokeAll(stored.userId)
                throw BusinessException(AuthErrorCode.REUSED_REFRESH_TOKEN)
            }
            else -> throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)
        }

        val user = userRepository.findById(UUID.fromString(stored.userId)).orElse(null)
            ?: throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)

        if (stored.tokenVersion != tokenVersions.forIssue(stored.userId)) {
            throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)
        }

        val tokens = issue(AuthUser.from(user), stored.tokenVersion)
        if (stored.tokenVersion != tokenVersions.current(stored.userId)) {
            revoke(tokens.refreshToken)
            throw BusinessException(AuthErrorCode.INVALID_REFRESH_TOKEN)
        }
        return tokens
    }

    private fun hash(token: String): String {
        val digest = MessageDigest.getInstance("SHA-256").digest(token.toByteArray())
        return Base64.getUrlEncoder().withoutPadding().encodeToString(digest)
    }

    companion object {
        private val ROTATE_SCRIPT = DefaultRedisScript(
            """
            if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
            if redis.call('HEXISTS', KEYS[1], 'rotatedAt') == 1 then return 2 end
            redis.call('HSET', KEYS[1], 'rotatedAt', ARGV[1])
            return 1
            """.trimIndent(),
            Long::class.javaObjectType,
        )
    }
}

The Lua script returns three deterministic codes:

  • 0: Key doesn’t exist in Redis (expired or unknown token).
  • 1: First-time rotation. Redis writes rotatedAt atomically and allows issuance to continue.
  • 2: rotatedAt is already set, meaning this token was rotated earlier and is now being replayed.

Even if 100 identical refresh requests arrive at the exact same instant, Redis guarantees that at most one request receives 1L, while the remaining 99 deterministically receive 2L.


Step 2: Theft detection and immediate global revocation

When the script returns 2L, the server knows a previously rotated token came back after a replacement was already issued. That happens in two threat scenarios: an attacker replayed a stolen older token, or an attacker rotated the token first and the legitimate user’s client just tried to refresh with the old copy.

In both cases, the safe response is to invalidate every active session for that user immediately:

1
2
3
4
5
// src/main/kotlin/com/example/server/auth/application/TokenService.kt (continued)
fun revokeAll(userId: String) {
    tokenVersions.revoke(userId)
    refreshTokenRepository.deleteAll(refreshTokenRepository.findAllByUserId(userId))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/main/kotlin/com/example/server/auth/application/TokenVersionStore.kt
package com.example.server.auth.application

import com.example.server.security.jwt.JwtProperties
import java.util.UUID
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component

@Component
class TokenVersionStore(
    private val redis: StringRedisTemplate,
    properties: JwtProperties,
) {
    private val ttl = maxOf(properties.refreshTokenTtl, properties.accessTokenTtl) + properties.clockSkew

    fun current(userId: String): String = redis.opsForValue().get(key(userId)) ?: ""

    fun forIssue(userId: String): String = redis.opsForValue().getAndExpire(key(userId), ttl) ?: ""

    fun revoke(userId: String) {
        redis.opsForValue().set(key(userId), UUID.randomUUID().toString(), ttl)
    }

    private fun key(userId: String): String = "token:version:$userId"
}

Calling revokeAll does three things at once:

  1. Overwrites token:version:<userId> in Redis with a fresh UUID. Any existing access token now carries a mismatched tokenVersion claim and fails validation immediately (see my post on instant stateless JWT revocation for the full validator setup).
  2. Deletes all stored refresh token hashes belonging to that user in Redis.
  3. Returns 401 Unauthorized with error code AUTH-006 (REUSED_REFRESH_TOKEN).

HTTP 401 response and server logs when reused refresh token triggers global revocation Figure 2. 401 Unauthorized response with AUTH-006 and server log confirming all sessions were revoked.

Notice the second tokenVersions.current(stored.userId) check after issue(...) in TokenService.rotate. If another request triggered revokeAll while issue was mid-flight, that trailing check catches the version bump and deletes the newly minted refresh token instead of leaking a valid session after revocation.


Step 3: Serializing refresh requests on the frontend

Atomic server-side rotation protects data integrity, but it doesn’t stop a chatty frontend from firing duplicate refresh calls. If two tabs still submit RT-1 at the same time, the server will rightly reject the second call with REUSED_REFRESH_TOKEN and log the user out.

You need client-side serialization as a second layer of defense.

Single-tab promise mutex in an Axios interceptor

When multiple API requests inside the same tab hit 401 simultaneously, let only the first failure call /refresh and make the rest await the shared promise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// frontend/src/api/client.ts
let refreshPromise: Promise<string> | null = null;

apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      if (!refreshPromise) {
        refreshPromise = requestNewTokens().finally(() => {
          refreshPromise = null;
        });
      }

      const newAccessToken = await refreshPromise;
      originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
      return apiClient(originalRequest);
    }
    return Promise.reject(error);
  }
);

Cross-tab synchronization with BroadcastChannel

Browser tabs don’t share JavaScript memory, so a single-tab promise mutex isn’t enough across windows. Use the BroadcastChannel API to broadcast the rotated access token to sibling tabs as soon as one tab completes a refresh:

1
2
3
4
5
6
7
8
9
10
11
12
13
// frontend/src/auth/tabSync.ts
const authChannel = new BroadcastChannel('auth_channel');

authChannel.onmessage = (event) => {
  if (event.data.type === 'TOKEN_ROTATED') {
    // Another tab already rotated the token; update local state immediately
    setStoredAccessToken(event.data.accessToken);
  }
};

export function notifyTokenRotated(accessToken: string) {
  authChannel.postMessage({ type: 'TOKEN_ROTATED', accessToken });
}

Together, the promise mutex and BroadcastChannel eliminate almost all duplicate refresh traffic at the browser boundary. If network latency still causes a rare overlap, the Redis Lua script guarantees consistent server-side behavior.


Verifying atomicity under concurrent load

To verify that only one request succeeds under contention, I wrote an integration test using CountDownLatch and an 8-thread pool. All 8 threads wait at the latch and call tokenService.rotate() with the same refresh token at the same instant, repeated 10 times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/test/kotlin/com/example/server/auth/RefreshTokenConcurrencyTest.kt
package com.example.server.auth

import com.example.server.auth.application.TokenService
import com.example.server.auth.dto.response.TokenResponse
import com.example.server.common.BusinessException
import com.example.server.security.user.AuthUser
import com.example.server.support.IntegrationTestSupport
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired

class RefreshTokenConcurrencyTest : IntegrationTestSupport() {
    @Autowired
    private lateinit var tokenService: TokenService

    @Test
    fun `at most one request succeeds when rotating the same refresh token concurrently`() {
        val user = createUser()
        Executors.newFixedThreadPool(8).use { executor ->
            repeat(10) {
                val first = tokenService.issue(AuthUser.from(user)).refreshToken
                val ready = CountDownLatch(8)
                val start = CountDownLatch(1)
                val futures = (1..8).map {
                    executor.submit<Result<TokenResponse>> {
                        ready.countDown()
                        check(start.await(5, TimeUnit.SECONDS))
                        runCatching { tokenService.rotate(first) }
                    }
                }
                check(ready.await(5, TimeUnit.SECONDS))
                start.countDown() // Release all 8 threads to call rotate simultaneously

                val results = futures.map { it.get(10, TimeUnit.SECONDS) }

                // At most one thread should succeed
                assertThat(results.count { it.isSuccess }).isLessThanOrEqualTo(1)
                assertThat(results.mapNotNull { it.exceptionOrNull() }).allMatch { it is BusinessException }
                tokenService.revokeAll(user.id.toString())
            }
        }
    }
}

Concurrency test console output showing atomic Lua script blocking duplicate refresh requests Figure 3. Integration test output confirming that exactly one thread wins rotation per round while the other seven fail cleanly.

Across all 10 iterations, exactly one thread won the rotation and the other seven were rejected atomically as BusinessException.


Trade-offs and production checklist

Strict zero-grace-period RTR works well when you control both the frontend and backend and can ship client-side serialization. It’s not a good fit if you support third-party mobile or flaky-network clients that can’t reliably deduplicate retries—in those environments, you’ll likely need a short grace window (2–5 seconds) where a recently rotated token returns the newly issued pair without triggering global revocation, trading a tiny reuse window for fewer false logouts.

Before shipping RTR to production, verify these four items:

  • Atomic rotation: Validate existence and set rotatedAt inside one Redis Lua script rather than separate read/write calls.
  • No immediate delete: Keep the rotated hash in Redis until its original TTL expires so late replay attempts are still caught.
  • Global revocation on reuse: Bump the user’s tokenVersion and delete all refresh tokens on 2L so both access and refresh tokens stop working immediately.
  • Client deduplication: Pair an in-tab promise mutex with BroadcastChannel (or the Web Locks API) so normal multi-tab browsing doesn’t trigger theft detection.
This post is licensed under CC BY 4.0 by the author.