Skip to content

Warning "Proactive closing of the session was missed - refinements are needed to TransactionSessionHandler related logic" appears #51131

Closed

Description

@mm-matthias

Before reporting an issue

  • I have read and understood the above terms for submitting issues, and I understand that my issue may be closed without action if I do not follow them.

Area

core

Describe the bug

Keycloak 26.7.0 spuriously logs the warning Proactive closing of the session was missed - refinements are needed to TransactionSessionHandler related logic. This warning is logged in the KeycloakBeanProducer.

Reproducing the error is quite hard as it seems to be related to the amount of load Keycloak receives. Performing logins etc. one-by-one does not pose a problem, but as soon as many requests are made simultaneously the warning starts to appear. The number of warnings is also varying. Sometimes the same set of requests produces 6 warnings, sometimes only 2. This seems to point to some sort of threading-related problem.
Right now we can reproduce it in a rather complex scenario with many different request types, but we still need to narrow it down to a simple test case (e.g. many simultaneous logins).

The warning message was only introduced recently in b8b5589 by @shawkins. The commit mentions "threadlocal" and "async" in commit message and code which seems to line up with the observed symptoms.

The criticality of the warning is currently unclear to us. Is it just a friendly reminder to close sessions proactively or could this potentially result in a temporary exhaustion of the DB connection pool?

Version

26.7.0

Regression

  • The issue is a regression

Expected behavior

There is no warning message.

Actual behavior

There is a warning message.

How to Reproduce?

A minimal reproducer is currently pending.

Anything else?

No response

Activity

  1. added
    kind/bug
    on Jul 24, 2026
  2. added theissue type on Jul 24, 2026
  3. added
    area/core
    on Jul 24, 2026
  4. shawkins commented on Jul 24, 2026

    @shawkins
    Contributor

    The warning message was only introduced recently in b8b5589 by @shawkins. The commit mentions "threadlocal" and "async" in commit message and code which seems to line up with the observed symptoms.

    Basically the logic performs proactive closing when the result is sent (CloseSessionFilter) or if we can see that the call was the initiator of an async request (TransactionalSessionHandler). So the warning means there's still something we're missing.

    The criticality of the warning is currently unclear to us. Is it just a friendly reminder to close sessions proactively or could this potentially result in a temporary exhaustion of the DB connection pool?

    While the session is ultimately getting cleaned up by the end of the session lifecycle, our current logic does leave the potential for the thread bound resources to be mis-associated with the worker thread.

    In the worst case if our transaction manager has left the transaction in a non-completed state, then it will wait for the transaction timeout to be cleaned up - and yes that could mean that any associated connections will be held until then.

  5. mm-matthias commented on Jul 24, 2026

    @mm-matthias
    Author

    So I think there are probably multiple places where this warning is being generated. I will post them each as far as I can reproduce them.

    1. RealmAdminResource

    Run multiple requests to PUT /admin/realms/some-realm in parallel. This will ultimately arrive here:

    throw ErrorResponse.exists("Realm with same name exists");
    because there is a duplicate key exception in the DB when simultaneously trying to update the same realm. Afterwards the warning will be logged (and a 409 Conflict will be returned).
    This is not a very useful real-world case, but I don't think the case matters much. There is a lot of structurally similar code in the RealmAdminResource that might be more relevant to real use cases and also trigger the warning.

  6. shawkins commented on Jul 24, 2026

    @shawkins
    Contributor

    That first case looks related to #50911 - but I would have expected the CloseSessionFilter to still been processed. I'll try to reproduce this.

  7. mm-matthias commented on Jul 24, 2026

    @mm-matthias
    Author

    2. Connection interrupted

    It seems the issue can also be reproduced when our e2e tests reload a page in the browser. This leads to requests being interrupted while still in-flight. In production the CloudFront in front of Keycloak reports 0 ClientConnError and the warning in Keycloak appears. However this doesn't happen every single time a request is interrupted, but just for a low percentage of all interruptions. Probably the exact point when the connection breaks matters (connection phase, request being sent, response being sent, ....).

    I'll continue working on a better reproducer to simulate the interrupted connections better. Maybe I'll also try to introduce some trace logging to see if there are any ClosedChannelException or such.

    @shawkins Might this be related to the issues you've worked on here?

  8. shawkins commented on Jul 26, 2026

    @shawkins
    Contributor

    @shawkins Might this be related to the issues you've worked on here?

    Based upon what you are describing, it's quite possible. Are you also then seeing a spike in CPU usage? When the work gets into that state it will continually be re-queued for more work.

  9. shawkins commented on Jul 26, 2026

    @shawkins
    Contributor

    I am not able to reproduce this situation from what you are describing in 1 - the ErrorRepresentation response always passes through the CloseSessionFilter.

    Do you have any providers jars installed? Or some additional context about how to reproduce?

  10. mm-matthias commented on Jul 27, 2026

    @mm-matthias
    Author

    Based upon what you are describing, it's quite possible. Are you also then seeing a spike in CPU usage? When the work gets into that state it will continually be re-queued for more work.

    So far I haven't been able to observe any CPU or mem spikes.

    I am not able to reproduce this situation from what you are describing in 1 - the ErrorRepresentation response always passes through the CloseSessionFilter.
    Do you have any providers jars installed? Or some additional context about how to reproduce?

    @shawkins

    After some debugging I figured out that case 1 above boils down to case 2, so for now the interrupted connection is the only issue remaining. In my original reproducer I had an asynchronous client and nginx producing 499s which gave the wrong impression this was related to the admin endpoint.

    Below's a python3 script (no libraries needed) that will reproduce two variants of the issue. One variant covers the case related to reading some form data (this sounds like quarkusio/quarkus#55116 to me). The other variant also produces the warning, but there are no accompanying HttpClosedException/ClosedChannelException exceptions.

    I have tested this against my current local Keycloak which does have some custom JARs/providers but that should not matter for now.

    It'd be great to know if both cases are addressed by the already open PRs.

    #!/usr/bin/env python3
    """Minimal reproducer for Keycloak's interrupted-request warning.
    
    Sends complete requests straight to the Keycloak backend (bypassing nginx),
    then closes each connection without reading the response -- the client goes away
    while Keycloak is still handling the request, the same situation nginx creates
    for its upstream when it logs a 499. Watch the Keycloak log for:
    
        WARN ... KeycloakBeanProducer: Proactive closing of the session was missed
    
    It runs two variants back to back, because the warning has two distinct
    triggers:
    
      nobody  GET with no request body. Keycloak opens a KeycloakSession to handle
              the request, the connection drops, and the normal session close is
              missed -> WARNING ONLY, no exception.
    
      body    POST with a form body. Same missed close, but additionally the worker
              thread does a *blocking read of the request body* (FormBodyHandler)
              which fails on the closed connection -> WARNING + an "Uncaught server
              error ... HttpClosedException" (io.IOException / ClosedChannelException).
    
    So `body` is the case where you see HttpClosedException; `nobody` reproduces the
    warning WITHOUT any HttpClosedException.
    
    Why this is timing-independent (no sleep to tune per machine): we close with a
    normal TCP FIN, not a RST. A FIN never discards the request bytes already in the
    server's receive buffer, and TCP guarantees it arrives *after* those bytes -- so
    Keycloak always reads the full request, then detects the client is gone during
    the request lifecycle. Not every connection in the burst warns (it's a race on
    how far the request has progressed), but a burst reproduces it unambiguously.
    
    Run:  python minimal_reproducer.py
    """
    
    import socket
    import threading
    
    HOST, PORT = "localhost", 54321  # Keycloak's HTTP port, published directly
    BASE = "/auth/realms/master/protocol/openid-connect"
    BURST = 40  # a burst reproduces it unambiguously; not every connection warns
    
    # nobody: GET, no request body -> no body read, so no HttpClosedException.
    NOBODY_REQUEST = (f"GET {BASE}/userinfo HTTP/1.1\r\nHost: {HOST}\r\nConnection: close\r\n\r\n").encode()
    
    # body: POST with a form body -> the failing blocking body read adds a
    # HttpClosedException on top of the warning.
    _BODY = b"grant_type=password&username=probe&password=probe&client_id=admin-cli"
    BODY_REQUEST = (
        f"POST {BASE}/token HTTP/1.1\r\n"
        f"Host: {HOST}\r\n"
        "Content-Type: application/x-www-form-urlencoded\r\n"
        "Connection: close\r\n"
        f"Content-Length: {len(_BODY)}\r\n"
        "\r\n"
    ).encode() + _BODY
    
    # Each variant: (request bytes, what to expect in the Keycloak log).
    VARIANTS = [
        ("nobody", NOBODY_REQUEST, "warning only (no HttpClosedException)"),
        ("body", BODY_REQUEST, "warning + HttpClosedException"),
    ]
    
    
    def abort_once(request: bytes):
        sock = socket.create_connection((HOST, PORT), timeout=10)
        sock.sendall(request)
        # Graceful close (FIN), no delay: the request is safely buffered at the
        # server and gets processed; we just never read the response.
        sock.close()
    
    
    def run_burst(request: bytes):
        threads = [threading.Thread(target=abort_once, args=(request,)) for _ in range(BURST)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
    
    
    if __name__ == "__main__":
        for mode, request, expect in VARIANTS:
            run_burst(request)
            print(f"[{mode}] sent + closed {BURST} requests; expect: {expect}")
  11. shawkins commented on Jul 27, 2026

    @shawkins
    Contributor

    Thank you for the reproducer. This does indeed look highly related to quarkusio/quarkus#55116, but I'm a little unsure as to why you wouldn't have seen the additional CPU usage.

    It'd be great to know if both cases are addressed by the already open PRs.

    Let me dig in more and see.

  12. mm-matthias commented on Jul 27, 2026

    @mm-matthias
    Author

    I have tested this against my current local Keycloak which does have some custom JARs/providers but that should not matter for now.

    FWIW; I tried without all the custom providers and I continue to see the WARN.

  13. shawkins commented on Jul 27, 2026

    @shawkins
    Contributor

    FWIW; I tried without all the custom providers and I continue to see the WARN.

    I am not able to reproduce the situation with the python script. I also never see the DiscardRemainingRunner running, which is the root of the problem for quarkusio/quarkus#55116

    Is there anything more you can share about how you are starting the server?

  14. 16 remaining items

  15. added a commit that references this issue on Jul 29, 2026
    1376942
  16. added a commit that references this issue on Aug 6, 2026
    849b66d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Fields

    No fields configured for bug.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions