nicegui: Server side memory leak when clearing ui.code()

First Check

  • I added a very descriptive title here.
  • This is not a Q&A. I am sure something is wrong with NiceGUI or its documentation.
  • I used the GitHub search to find a similar issue and came up empty.

Example Code

from nicegui import ui

row = ui.row()
i = 0

def more_code():
    global i
    row.clear()
    with row:
        for k in range(50):
            ui.code(language='xml', content=f'<data>{i}</data>')
            i += 1

ui.timer(callback=more_code, interval=1)
ui.run()

Description

I noticed that when I create, clear and re-create a bunch of ui.code() elements, memory usage on the server creeps up. The given example creeps by 1 MB every 1-3 seconds. A real life example reached 4 gigs before becoming so slow that it had to be restarted. Tested in real life on Linux and the minimal example tested on Windows.

NiceGUI Version

2.20.0

Python Version

Python 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 15:28:43) [MSC v.1943 64 bit (ARM64)] on win32

Browser

Chrome

Operating System

Windows

Additional Context

No response

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 23 (13 by maintainers)

Commits related to this issue

Most upvoted comments

You guys are really fast and professional! Thanks for a great product 😀

Some insights:

  • The leak for ui.code seems to be caused by timer(0.1, self._update_copy_button).
  • The leak for ui.header and ui.left_drawer/ui.right_drawer seems to be caused by the line with context.client.layout:. No, I didn’t delete elements from client.layout but only from client.content.
  • In ui.header I noticed add_body_html being called again and again which we should avoid.

My test script:

from nicegui import ui
import tracemalloc
tracemalloc.start()


row = ui.row()
i = 0

def more_code():
    global i
    row.clear()
    with row:
        for k in range(50):
            ui.code(language='xml', content=f'<data>{i}</data>')
            # ui.label(f'<data>{i}</data>').style('font-family: monospace;')
            i += 1

def print_tracemalloc_top_n(n=10):
    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('lineno')
    print(f'Top {n} memory usage:')
    for stat in top_stats[:n]:
        print(stat)

ui.timer(callback=more_code, interval=0.1)
ui.timer(callback=lambda: print_tracemalloc_top_n(10), interval=5)
ui.run()

Notable things:

  1. Element number is expected to skyrocket. This issue is about why memory is leaked when we repeatedly create new elements and throw the old ones away (notice how we don’t keep any reference to the ui.code instances)
  2. Preliminary tracemalloc indicates: self.client.on_connect in ui.code will append to Client.connect_handlers. That list gets longer and longer, and so the memory is leaked from there (investigating axing that and see if memory still grows to the same degree)

@evnchn: It’s ui.code!!! (Not ui.code_mirror.) 😉