`enqueue=True` causes unbounded memory growth with slow sinks (missing backpressure)
I’ve identified a memory safety issue when using enqueue=True with sinks that cannot keep up with the log volume (e.g., slow disk I/O, network sinks, or blocked stdout).
Because the internal queue is unbounded, a slow consumer causes log records to buffer in memory indefinitely. In long-running processes, this leads to massive RSS growth and eventual OOM, even if the application logic itself is memory-efficient.
Minimal Reproduction
I isolated this by simulating a slow sink (50ms latency) against a fast producer.
Environment:
- Python 3.14.0 / Loguru 0.7.3 / WSL2
psutilused for RSS sampling
import time
import psutil
from loguru import logger
logger.remove()
class SlowSink:
def write(self, message):
time.sleep(0.05) # Simulate slow I/O
def run(enqueue: bool) -> None:
logger.add(SlowSink(), level="SUCCESS", enqueue=enqueue)
proc = psutil.Process()
# 5MB payload to make the leak obvious
payload = "X" * (5 * 1024 * 1024)
print(f"=== Running with enqueue={enqueue} ===")
for i in range(200):
logger.success(payload)
if i % 50 == 0:
rss = proc.memory_info().rss / (1024 * 1024)
print(f"i={i:4d} rss={rss:7.1f} MB")
print("Logging done, sleeping 5s to drain...")
time.sleep(5)
rss = proc.memory_info().rss / (1024 * 1024)
print(f"Final rss={rss:7.1f} MB\n")
run(enqueue=False)
logger.remove()
run(enqueue=True)
Output
=== Running with enqueue=False ===
i= 0 rss= 23.5 MB
i= 50 rss= 28.4 MB
i= 100 rss= 28.4 MB
Final rss= 28.4 MB
=== Running with enqueue=True ===
i= 0 rss= 44.3 MB
i= 50 rss= 74.5 MB
i= 100 rss= 69.5 MB
Final rss= 69.5 MB
With enqueue=False, the producer is blocked by the sink, so backpressure is implicit; memory stays flat (~28MB).
With enqueue=True, the producer dumps 5MB chunks into the queue faster than the thread can drain them. RSS spikes and stays high because the queue holds references to the objects, and CPython's allocator high-water mark keeps the memory mapped even after the queue eventually drains.
Root Cause
I ran tracemalloc on the reproduction script, which pinpointed the allocation site:
.../multiprocessing/queues.py:0: size=2064 KiB, count=348
It seems logger.add(..., enqueue=True) relies on multiprocessing.SimpleQueue (even for threads). This queue has no maxsize or capacity limit.
Suggested Fixes
Right now, enqueue=True is dangerous in production if there's any risk of the sink stalling (e.g., logging to a database or generic http endpoint).
- Documentation: At a minimum, the docs should explicitly warn that
enqueue=Truelacks backpressure and can OOM the process if the sink is slow. - Bounded Queue: Ideally,
enqueueshould accept aqueue_sizeint. If the queue is full, it needs a strategy (block the caller or drop the log with a warning to stderr).
Is there an existing workaround to enforce a queue limit without rewriting the threading logic manually?
Transparency: Findings are human-generated; text drafting assisted by AI.
I'd like to work on this issue if that's okay!
Based on the discussion, I'm planning to implement the following approach:
Proposal:
- Extend the
enqueueparameter to accept additional options:enqueue=True- existing behavior (unbounded queue, backward compatible)enqueue={"size": N}- bounded queue with max size Nenqueue={"size": N, "overflow": "block|drop"}- configurable overflow policy
Overflow policies:
"block"(default): Block the logging call until queue has space (backpressure)"drop": Drop the log message when queue is full
This would involve replacing SimpleQueue with Queue(maxsize=N) internally when a size limit is specified.
Would this direction work for you? I'm happy to adjust the API design based on your feedback before starting implementation.
Hi @TheRealMkadmi.
The example you shared does not actually seem to reproduce any memory leak / unbounded memory growth. The memory used increases up to a certain threshold but then stops growing, even using an infinite loop.
This is expected: Loguru indeed uses a SimpleQueue(), but even though it does not have a maxsize, it is in practice bounded in size by the OS. That is, on Linux, it's implemented using a pipe which is limited to 64 KB. Attempting to put data while it is full will block until more space is available. It works similarly in Windows, if I'm not mistaken.
Now, blocking si arguably as bad as a memory leak since it can slow down the application. This is something I'm aware of and I worked on it a long time ago, but I wasn't able to merge my new implementation yet. But it's among the priorities for the next release.
I'll make sure to handle this case, and provide a way for the users to have more control on the queue constraints they decide.
@GangEunzzang / @Lee-Gang-Eun Thank you for your interest in helping to resolve this issue.
As I said in my previous message, there is something I've been working on but never fully finished (f13a08a9abe63f478b06e42f3a1ee086edf44db4). It's a problem with lots of edge cases to consider.
Replacing SimpleQueue with Queue seems to be a natural choice, but I did the opposite move many years ago due to internal problems with the Queue implementation: 74a418a0558b9dee02ae14cb36bc38c5065ea436
I no longer have the details in mind, and maybe it's fixed.
But care must be taken that there is no deadlock that could occur, and I know that some parts of CPython have their own bugs that unfortunately can cause such issues.
That is why initially I wanted to implement a custom RecordQueue class, but I might reconsider this and leverage built-in multiprocessing.Queue if it proves to works better than before. I need to test it extensively, though.
I'm not a fan of the enqueue={"size": N, "overflow": "block|drop"} to be honest. But if multiprocessing.Queue is usable, I'm thinking maybe we could deprecate enqueue and replace it with a new queue argument. The user would be responsible to provide the implementation of the queue it desires, which could be bounded and non-blocking. This would also has the nice side-effects of allowing non-multiprocessing queues to be used, which is a feature that was asked for already.
Hi @Delgan , thanks a lot for the thoughtful feedback
Your point about the API design (and the past issues around Queue) makes a lot of sense. The idea of letting users pass their own queue implementation does feel like a cleaner and more flexible direction, especially if it can address several feature requests at once.
Since you already have work in progress on this (f13a08a) and a clearer direction in mind, I’m totally happy to adjust. I can either:
Close this PR and let you continue with your approach, or
Rework this PR to follow the queue-argument pattern, if that would still be helpful
I definitely don’t want to duplicate work or push in a direction that doesn’t fit the project’s vision. Just let me know what would be most useful.
And thanks again for maintaining such a great library 🙌