Spring › Feature

Fixing JPA AuditorAware in async threads and scheduled jobs

Fix ScopeNotActiveException and missing SecurityContext errors in Spring Data JPA AuditorAware when persisting entities from schedulers and async threads.

Fixing JPA AuditorAware in async threads and scheduled jobs

Spring Data JPA Auditing runs every time an entity is persisted—not just during HTTP requests, but also inside @Scheduled jobs, @Async workers, and batch runners. Injecting a request-scoped HttpServletRequest proxy into AuditorAware crashes those background threads with ScopeNotActiveException. Here is why it happens and how I fixed it in demo-backend-server.


The problem: a batch job that worked locally crashed overnight

In demo-backend-server, I use Spring Data JPA Auditing to populate @CreatedBy, @LastModifiedBy, and @CreatedDate on every entity automatically.

During normal HTTP requests—such as an admin manually registering a court judgment or editing tags—AuditorAware combined the authenticated username with the client IP (X-Forwarded-For) and stored a clean audit string:

  • cmsong111 (192.168.1.15)

Everything passed during manual testing in the browser. Then the overnight @Scheduled crawler ran to pull new judgments from the external court API. The moment it called judgmentRepository.save(entity), the scheduler thread crashed with this stack trace:

Stack trace of ScopeNotActiveException in AuditorAware on a scheduler thread Figure 1. Scope 'request' is not active thrown when persisting an entity from a scheduler thread.

1
2
3
4
5
6
7
8
9
10
11
12
13
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.request':
Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean
if you intend to refer to it from a singleton;
nested exception is java.lang.IllegalStateException: No thread-bound request found:
Are you referring to request attributes outside of an actual web request,
or processing a request outside of the originally receiving thread?
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
    at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:323)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:163)
    at jdk.proxy2/jdk.proxy2.$Proxy118.getHeader(Unknown Source)
    at com.example.server.common.AuditorAwareImpl.getClientIp(AuditorAwareImpl.kt:28)
    at com.example.server.common.AuditorAwareImpl.getCurrentAuditor(AuditorAwareImpl.kt:19)
    at org.springframework.data.jpa.domain.support.AuditingEntityListener.touchForCreate(AuditingEntityListener.java:101)

All the batch job did was save an entity. Why did auditing blow up with a web request-scope exception?


Root cause: request-scoped proxies and ThreadLocal isolation

Looking at my original AuditorAwareImpl makes the bug obvious.

1. The broken implementation

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
// Before: unsafe AuditorAware implementation
@Component
class AuditorAwareImpl(
    private val request: HttpServletRequest // Request-scoped proxy injected into a singleton
) : AuditorAware<String> {

    override fun getCurrentAuditor(): Optional<String> {
        val authentication = SecurityContextHolder.getContext().authentication

        if (authentication == null || !authentication.isAuthenticated || authentication.name == "anonymousUser") {
            return Optional.of("SYSTEM (${getClientIp()})") // Still touches the request proxy!
        }

        return Optional.of("${authentication.name} (${getClientIp()})")
    }

    private fun getClientIp(): String {
        val xfHeader: String? = request.getHeader("X-Forwarded-For") // Crashes here outside HTTP threads
        return if (xfHeader == null) {
            request.remoteAddr
        } else {
            xfHeader.split(",")[0]
        }
    }
}

2. How the HttpServletRequest proxy works under the hood

When you constructor-inject HttpServletRequest into a singleton @Component, Spring doesn’t inject a real servlet request. It injects a JDK dynamic proxy ($Proxy...).

Every method call on that proxy delegates to RequestContextHolder.currentRequestAttributes(), which looks up the active ServletRequestAttributes bound to the current thread’s ThreadLocal.

sequenceDiagram
    autonumber
    participant App as AuditorAwareImpl (Singleton)
    participant Proxy as HttpServletRequest Proxy
    participant Holder as RequestContextHolder (ThreadLocal)
    Note over App,Holder: Case 1: Tomcat HTTP thread (http-nio-exec)
    App->>Proxy: request.getHeader("X-Forwarded-For")
    Proxy->>Holder: currentRequestAttributes()
    Holder-->>Proxy: Returns ServletRequestAttributes
    Proxy-->>App: Returns "192.168.1.15"
    Note over App,Holder: Case 2: Background scheduler thread (scheduling-1)
    App->>Proxy: request.getHeader("X-Forwarded-For")
    Proxy->>Holder: currentRequestAttributes()
    Holder-->>Proxy: null (no request bound to ThreadLocal)
    Proxy-->>App: Throws IllegalStateException / ScopeNotActiveException
  • HTTP servlet threads (http-nio-exec): DispatcherServlet binds the incoming request to RequestContextHolder, so proxy calls succeed.
  • Background threads (scheduling-1, @Async, batch workers): They never pass through DispatcherServlet. Their ThreadLocal has no request attributes attached.
  • Touching any method on the proxy (getHeader, getRemoteAddr) immediately throws IllegalStateException: No thread-bound request found.

3. SecurityContextHolder is also thread-local

SecurityContextHolder defaults to MODE_THREADLOCAL. Authentication details live on the servlet thread and do not propagate automatically to schedulers or async pools.

In a background thread, authentication is null. My fallback branch caught authentication == null and tried to return SYSTEM (${getClientIp()}), which still called request.getHeader(...) and triggered the exact same crash.


The fix: context-safe RequestUtils and defensive AuditorAware

Fixing this cleanly requires two changes:

  1. Remove the injected HttpServletRequest proxy from the singleton and read RequestContextHolder.getRequestAttributes() statically instead (unlike currentRequestAttributes(), getRequestAttributes() returns null rather than throwing).
  2. Fall back cleanly to a deterministic system auditor whenever either request or authentication is absent.

Step 1: Null-safe RequestUtils

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
// src/main/kotlin/com/example/server/utils/RequestUtils.kt
package com.example.server.utils

import jakarta.servlet.http.HttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

object RequestUtils {

    /**
     * Safely returns the HttpServletRequest bound to the current thread,
     * or null when invoked from a scheduler, @Async task, or batch thread.
     */
    val currentRequest: HttpServletRequest?
        get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request

    /**
     * Extracts the client IP behind reverse proxies (e.g. Nginx Proxy Manager).
     * Returns "unknown" outside of an HTTP request.
     */
    fun getClientIp(request: HttpServletRequest? = currentRequest): String {
        if (request == null) return "unknown"

        val xfHeader = request.getHeader("X-Forwarded-For")
        return if (xfHeader.isNullOrBlank()) {
            request.remoteAddr ?: "unknown"
        } else {
            // The leftmost entry is the original client IP when multiple proxies append headers
            xfHeader.split(",")[0].trim()
        }
    }
}

Casting RequestContextHolder.getRequestAttributes() with Kotlin’s safe cast (as? ServletRequestAttributes) returns null without triggering Spring’s scoped-proxy exception.

Step 2: Defensive AuditorAwareImpl

Now AuditorAwareImpl has zero web-layer constructor dependencies and works identically across HTTP threads, schedulers, and tests.

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
// src/main/kotlin/com/example/server/common/AuditorAwareImpl.kt
package com.example.server.common

import com.example.server.utils.RequestUtils
import java.util.Optional
import org.springframework.data.domain.AuditorAware
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component

@Component
class AuditorAwareImpl : AuditorAware<String> {

    override fun getCurrentAuditor(): Optional<String> {
        val authentication = SecurityContextHolder.getContext()?.authentication
        // Outside a web request (batch, scheduler, startup), currentRequest is null -> "unknown"
        val clientIp = RequestUtils.getClientIp()

        // 1. Unauthenticated request or background thread fallback
        if (authentication == null || !authentication.isAuthenticated || authentication.name == "anonymousUser") {
            return Optional.of("SYSTEM ($clientIp)")
        }

        // 2. Authenticated HTTP request (principal + client IP)
        return Optional.of("${authentication.name} ($clientIp)")
    }
}

AuditorAware can legally return Optional.empty(), but if your @CreatedBy column has a NOT NULL constraint, returning empty causes a DataIntegrityViolationException on insert. Returning an explicit fallback like SYSTEM (unknown) keeps inserts safe and makes batch writes easy to distinguish in audit logs.

Step 3: JPA Auditing config and BaseEntity

1
2
3
4
5
6
7
8
9
// src/main/kotlin/com/example/server/config/JpaAuditConfig.kt
package com.example.server.config

import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaAuditing

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAwareImpl")
class JpaAuditConfig
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
// src/main/kotlin/com/example/server/common/BaseEntity.kt
package com.example.server.common

import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import jakarta.persistence.Version
import java.time.Instant
import org.hibernate.annotations.ColumnDefault
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener

@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity(
    @CreatedDate
    @Column(updatable = false, nullable = false)
    var createdAt: Instant = Instant.now(),

    @LastModifiedDate
    @Column(nullable = false)
    var updatedAt: Instant = Instant.now(),

    @CreatedBy
    @Column(updatable = false, nullable = false, length = 100)
    var createdUser: String? = null,

    @LastModifiedBy
    @Column(nullable = false, length = 100)
    var updatedUser: String? = null,

    @Version
    @ColumnDefault("0")
    var version: Long = 0,
)

Verification: testing both background and web contexts

I added an integration test that clears SecurityContextHolder and persists an entity outside any mock web request:

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/test/kotlin/com/example/server/common/AuditorAwareIntegrationTest.kt
@SpringBootTest
class AuditorAwareIntegrationTest @Autowired constructor(
    private val judgmentRepository: JudgmentRepository,
    private val auditorAware: AuditorAware<String>
) {

    @Test
    @DisplayName("Persists with SYSTEM fallback outside a web request")
    fun persistOutsideWebRequest() {
        // Given: simulate a background thread with no SecurityContext or RequestContext
        SecurityContextHolder.clearContext()

        // When
        val auditor = auditorAware.currentAuditor
        val judgment = judgmentRepository.save(
            Judgment(caseNumber = "2026No1842", courtName = "Seoul High Court")
        )

        // Then
        assertThat(auditor).contains("SYSTEM (unknown)")
        assertThat(judgment.createdUser).isEqualTo("SYSTEM (unknown)")
        assertThat(judgment.updatedUser).isEqualTo("SYSTEM (unknown)")
    }
}

1. Test execution logs

Safe AuditorAware fallback logs on scheduler and HTTP threads Figure 2. Integration test logs. The scheduler thread (scheduling-1) falls back to SYSTEM (unknown), while the HTTP thread (http-nio-exec-1) records the authenticated user and client IP.

2. Persisted audit columns in PostgreSQL

Inspecting the judgment table in DataGrip confirms that manual admin entries and overnight crawler inserts are cleanly distinguished:

PostgreSQL judgment table showing admin IP vs SYSTEM (unknown) in created_user Figure 3. PostgreSQL judgment table. Manual admin inserts store username (IP), while scheduled crawler inserts store SYSTEM (unknown).


Caveats and checklist

What if you actually want an @Async task spawned by a user’s HTTP request to record that user’s identity rather than SYSTEM? Do not rely on RequestContextHolder across threads—Tomcat recycles the HttpServletRequest as soon as the HTTP response finishes, which causes race conditions or corrupted headers in child threads. Instead, wrap your TaskExecutor with DelegatingSecurityContextAsyncTaskExecutor (for SecurityContext propagation) or pass the user ID explicitly as a method argument.

Production checklist:

  • Never constructor-inject HttpServletRequest into singleton beans invoked by JPA listeners, schedulers, or async workers.
  • Use RequestContextHolder.getRequestAttributes() (null-safe) instead of currentRequestAttributes() (throws).
  • Return an explicit fallback string (e.g. SYSTEM (unknown)) when @CreatedBy / @LastModifiedBy columns are NOT NULL.
  • Add at least one @SpringBootTest that clears SecurityContextHolder and saves an entity without MockMvc so regressions fail in CI before hitting production.
This post is licensed under CC BY 4.0 by the author.