Skip to content

No way to close OpenAiChatModel — rebuilding it at runtime leaks openai-java client threads (DefaultSleeper) #7155

Open

Description

@donyxu

Environment

  • Spring AI 2.0.1 (spring-ai-openai)
  • JDK 25

Description

Since the OpenAI Java SDK transition, each OpenAiChatModel instance constructs
its own com.openai.client.OpenAIClient / OpenAIClientAsync and holds them in
private final fields.

OpenAiChatModel is final, implements only ChatModel, and exposes neither
close() nor any accessor to the underlying clients — so once an instance is
replaced, there is no way to release its resources through the public API.

This matters for applications that change connection settings (base URL / API
key) at runtime through an admin UI and rebuild the model instead of restarting
the process:

  • Every build leaves 2 daemon threads named DefaultSleeper (created by the
    underlying SDK) plus executor plumbing behind. No API call is needed — the
    threads appear on construction alone.
  • The leaked threads are not reclaimed after a forced full GC: a class
    histogram shows the old model instances collected while all leaked
    DefaultSleeper instances stay alive (after ~20 rebuilds: 1 live model,
    ~40 live sleepers).

For reference, the underlying SDK's README recommends
"Don't create more than one client in the same application" (each client owns
connection and thread pools) and provides withOptions() to vary per-request
configuration while sharing those pools. Neither the shared-client pattern nor
the client's close() is reachable through OpenAiChatModel.

Reproduction

List<OpenAiChatModel> models = new ArrayList<>();
for (int i = 0; i < 20; i++) {
    models.add(OpenAiChatModel.builder()
        .options(OpenAiChatOptions.builder()
            .baseUrl("http://127.0.0.1:1/v1")
            .apiKey("dummy")
            .build())
        .build());
}
jcmd <pid> Thread.print | grep -c DefaultSleeper     # grows by 2 per build
models.clear(); System.gc();                          # or: jcmd <pid> GC.class_histogram
jcmd <pid> GC.class_histogram | grep DefaultSleeper  # count unchanged

Suggestion

  • Implement AutoCloseable on OpenAiChatModel (closing the underlying
    sync/async clients), or expose a dispose hook / client accessor.
  • Alternatively, support sharing one underlying client across model instances
    (per-request options / withOptions()), matching the SDK's own guidance.

Workaround

Cache and reuse the OpenAiChatModel while connection-relevant options
(base URL, API key) are unchanged — model name and timeout can be supplied per
request via OpenAiChatOptions on the Prompt.

Activity

  1. CryoThrust commented on Oct 14, 2026

    @CryoThrust
    Contributor

    One useful distinction for the fix: externally owned clients are already supported in 2.0.1. The public builder has both openAiClient(...) and openAiClientAsync(...), and build() only creates each client when that particular one wasn't supplied. Passing only the sync client still constructs an async client, so both need to be supplied to avoid that fallback. An application retaining those references can manage their lifecycle outside the model; the internally constructed-client case still lacks a model disposal API.

    If a disposal hook is added, I'd make ownership explicit per client: close internally created clients, preserve borrowed clients used by other models, and handle mixed owned/borrowed construction. A blanket close of both fields would break the existing sharing path. Regression coverage should also ensure that failure while closing one owned resource does not leave the other unclosed, and that repeated disposal is safe.

    This is a source check against the 2.0.1 tag and current main, not an independent reproduction of the reported thread counts or GC behavior.

  2. Emryswu commented on Oct 14, 2026

    @Emryswu

    I'd like to work on this.

    Plan: make OpenAiChatModel implement AutoCloseable and track ownership per client — close only the clients build() created itself, never the ones passed via openAiClient(...)/openAiClientAsync(...). Both owned clients get closed even if one fails (suppressed exceptions), and repeated close() is a no-op. Tests would cover owned, borrowed, mixed and double-close cases.

    Two questions before I start:

    1. The same pattern exists in the other SDK-based models (Embedding, Image, Moderation, AudioSpeech, AudioTranscription, ResponsesChat). Should this PR cover all of them, or stay scoped to OpenAiChatModel?
    2. The auto-configuration builds the clients itself and passes them in, so under this rule they'd be treated as borrowed and not closed on context shutdown. Should the auto-config hand ownership to the model instead?
  3. added a commit that references this issue on Oct 14, 2026
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

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions