Skip to content

memory leak, consumes entire system after just days of usage #1181

Closed

Description

@pseudotensor

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • This is an issue with the Python library

Describe the bug

Progressive memory leak despite use of close(). Leads to eventually OOM on even large memory systems after just a few days.

Related: #820

To Reproduce

I'm using 1.12.0 and still hit this issue.

Using text completion. I'm also using close() in a try-finally, so close() does not help. A global client connection doesn't make sense to enforce. The old client pre 1.x had global attributes that made the API poor. I presume there are some legacy parts still in place.

In h2oGPT, we use OpenAI client for OpenAI or vLLM connections, and I see a 5GB memory leak for every 6000 connections. This happens whether I yield the generator for streaming or just exit after creating the completion.

Normally connections are not as intense, but this was easily reproducible by bisecting the OpenAI creation/generation parts of the code. For typical workloads this leads to OOM on a 256GB system after just few days of usage.

Here is repro. Please choose the to be some endpoint that you have setup like vLLM or TGI or gpt3.5 turbo so not expensive. Choose api_key and model accordingly.

import os
import psutil
from openai import OpenAI

for i in range(6000):

    client_args = dict(base_url='<choose>', api_key="EMPTY")
    client = OpenAI(**client_args)

    responses = client.completions.create(
        model='h2oai/h2ogpt-4096-llama2-13b-chat',
        prompt="Say exactly one word.",
        stream=True,
    )
    client.close()
    p = psutil.Process(os.getpid())
    print(p.memory_full_info())

The memory consumed is not increasing every step in loop, but it does monotonically increase from pss=48523264 to pss=107862016 within a few minutes (i.e. doubled) and continues this indefinitely.

The problem seems to be even stronger when doing concurrent requests in multi-threaded setup, as if the clean-up is not thread safe. I'm trying to put together a repro that would showcase the 5GB after 6000 connections that only takes half hour to run. But perhaps the above is sufficient.

Code snippets

No response

OS

ubuntu 22

Python version

Python v3.10

Library version

openai v1.12.0

Activity

  1. added
    bug
    on Feb 23, 2024
  2. pseudotensor commented on Feb 23, 2024

    @pseudotensor
    Author

    Note that the fix in 1.3.9 helped this issue to be a leak of 5GB to about 1GB, but it's still a large leak.

    #820 (comment)

  3. rattrayalex commented on Feb 23, 2024

    @rattrayalex
    Contributor

    You need to call response.close() if you stream a request without reading its body.

    Please try this:

    import os
    import psutil
    from openai import OpenAI
    
    for i in range(6000):
    
        client_args = dict(base_url='<choose>', api_key="EMPTY")
        client = OpenAI(**client_args)
    
        response = client.completions.create(
            model='h2oai/h2ogpt-4096-llama2-13b-chat',
            prompt="Say exactly one word.",
            stream=True,
        )
        response.close()
        client.close()
        p = psutil.Process(os.getpid())
        print(p.memory_full_info())
  4. pseudotensor commented on Feb 23, 2024

    @pseudotensor
    Author

    Ok thanks, will try that.

  5. pseudotensor commented on Feb 23, 2024

    @pseudotensor
    Author

    I see same thing with the added close. Note that this is just trying to mimic a leak seen in similar circumstances with much larger code base.

    base_url = <fill me>
    model = <fill me>
    api_key = <fill me>
    
    
    import os
    import psutil
    from openai import OpenAI
    
    for i in range(6000):
    
        client_args = dict(base_url=base_url, api_key=api_key)
        client = OpenAI(**client_args)
    
        responses = client.completions.create(
            model=model,
            prompt="Say exactly one word.",
            stream=True,
        )
        responses.close()
        client.close()
        p = psutil.Process(os.getpid())
        print(p.memory_full_info())
    

    i.e. I still see it go from pss=52678656 to pss=110225408 within few minutes, about 50MB, and it keeps growing indefinitely.

  6. rattrayalex commented on Feb 23, 2024

    @rattrayalex
    Contributor

    Got it, thanks for the report & repro script. We'll look into it.

  7. pseudotensor commented on Feb 23, 2024

    @pseudotensor
    Author

    One can do a more attack style with multi-threading to get things to happen faster:

    base_url = <fill me>
    model = <fill me>
    api_key = <fill me>
    
    import concurrent.futures
    import os
    import psutil
    from openai import OpenAI
    
    
    def get_mem():
        p = psutil.Process(os.getpid())
        print(p.memory_full_info())
    
    
    def do_something(i):
        client_args = dict(base_url=base_url, api_key=api_key)
        client = OpenAI(**client_args)
    
        responses = client.completions.create(
            model=model,
            prompt='\n'.join(["Say exactly one word."] * 300),
            stream=True,
        )
        responses.close()
        client.close()
        get_mem()
    
    
    # Create a thread pool with 4 worker threads.
    tasks = 6000
    #tasks = 600
    futures = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
        for i in range(tasks):
            futures.append(executor.submit(do_something, i))
    
            # Wait for all tasks to complete.
            for f1 in futures:
                if f1.done():
                    result = f1.result()
                    print(result)
    get_mem()
    

    I'll open new issue if I'm able to repro the larger code base more accurately with its larger leak for this block.

  8. rattrayalex commented on Feb 23, 2024

    @rattrayalex
    Contributor

    This issue is fine for this leak, no need to open another new one :)

  9. shivenmian commented on Feb 25, 2024

    @shivenmian

    @rattrayalex facing the same issue at 01. Repro-d on an M2 Macbook Pro with openai version 1.12.0. Things were working fine yesterday, but now program execution runs into out-of-memory errors every time I run it.

    I did a memray memory profile for 01 here. Looks like the use of Pydantic is taking up an excessive amount of memory. @pseudotensor perhaps you can also do a memprof and see if you see the same thing.

    cc @KillianLucas

  10. shivenmian commented on Feb 25, 2024

    @shivenmian

    Looks like the root cause of this issue (atleast on my end) is Pydantic. openai-python uses Pydantic and thus the memory profile shows the usage as high. Related issues on Pydantic repo are pydantic/pydantic#8709 and pydantic/pydantic#8785.

  11. shivenmian commented on Feb 27, 2024

    @shivenmian

    Pydantic fixed pydantic/pydantic#8709 and released v2.6.3. @pseudotensor maybe see if that fixes things for you

  12. pseudotensor commented on Feb 27, 2024

    @pseudotensor
    Author
    import gc
    
    base_url = 'https://gpt-internal-2.h2o.ai:5000/v1'
    model = 'h2oai/h2ogpt-4096-llama2-13b-chat]'
    api_key = '62224bfb-c832-4452-81e7-8a4bdabbe164'
    
    
    import os
    import psutil
    from openai import OpenAI
    
    for i in range(6000):
    
        client_args = dict(base_url=base_url, api_key=api_key)
        client = OpenAI(**client_args)
    
        responses = client.completions.create(
            model=model,
            prompt="Say exactly one word.",
            stream=True,
        )
        responses.close()
        client.close()
        gc.collect()
        p = psutil.Process(os.getpid())
        print(p.memory_full_info())
    

    Yes, this looks stable now.

  13. shivenmian commented on Feb 27, 2024

    @shivenmian

    @pseudotensor awesome! Was it the pydantic bump that fixed it?

  14. rattrayalex commented on Feb 28, 2024

    @rattrayalex
    Contributor

    Terrific, thank you for investigating and reporting back!

  15. pseudotensor commented on Feb 28, 2024

    @pseudotensor
    Author

    Yes, pydantic was last piece of smaller leak for me. Now rock solid.

  16. shivenmian commented on Feb 28, 2024

    @shivenmian

    Awesome! @rattrayalex Perhaps the Pydantic version should be pinned to 2.6.3 in the requirements.lock and requirements-dev.lock?

  17. RobertCraigie commented on Feb 28, 2024

    @RobertCraigie
    Contributor

    @shivenmian note that those version pins are just pins for our internal development environment, they don't effect users of openai. The actual dep constraints are here:

    dependencies = [

  18. JHart96 commented on Dec 10, 2025

    @JHart96

    I'm getting this issue again on 2.12.5. Pinning to 2.6.3 as suggested above works perfectly. Has the Pydantic bug regressed again?

  19. hcglhcgl commented on Jan 14, 2026

    @hcglhcgl

    We have found the latest working version of pydantic to be 2.10.6

  20. Viicos commented on Jan 15, 2026

    @Viicos

    @JHart96 @hcglhcgl (speaking as a Pydantic maintainer) are you able to reproduce with the same MRE provided in the OP?

  21. JHart96 commented on Jan 15, 2026

    @JHart96

    @Viicos I've only had chance to run the MRE for a few minutes, but yes I'm seeing a leak on Pydantic 2.12.5, and no leak on 2.10.6 (as @hcglhcgl suggested above).

  22. Viicos commented on Jan 18, 2026

    @Viicos

    I'm not able to reproduce the leak. I do see a slight increase in memory usage over time, but it seems unrelated to pydantic:

    Image Image

    If you can manage to provide a memray report, I could investigate further (memray run -o openai.bin repro.py && memray flamegraph -o openai.html openai.bin).

  23. hcglhcgl commented on Jan 19, 2026

    @hcglhcgl

    In our experience the issue also only happens when running tasks in celery with gevent. I'll try to make an MRE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions