Error using crawler: maximum recursion depth exceeded
I'm getting the maximum recursion depth exceeded error in the crawling application I have. See portion of the trace below (I'm only including a portion because the whole thing is insanely long, and the lines repeat over and over again, so not too useful).
Some important context:
- The application is running in a Docker container
- Within the app, there are 2 processes: one is triggered to occur every 1 hour; the second - every 1 minute.
What I tried:
- I set
thread_safeto True for both cases
Otherwise, I do not known how I can debug this.
I suspect that the issue could be caused by 2 crawl processes overlapping, which is supported by bigger picture I see in the logs, and specifically, that the 1-minute job starts and finishes successfully several times until the longer-running 1-hour job starts. At this point, the 1-minute job would hang, and after some time fail with lost connectivity message. Subsequent 1-minute jobs return the maximum recursion depth exceeded error. Would you say this suspicion is valid?
Example trace:
Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/wapaganda/webparse/source_update_service.py", line 38, in run_update
new_yield = await self.scanner.fetch_items()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/wapaganda/webparse/sources/infox_ru.py", line 57, in fetch_items
res = await self.fetch_page_items(url)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/wapaganda/webparse/sources/scanner.py", line 59, in fetch_page_items
async with AsyncWebCrawler(thread_safe=True) as crawler:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/crawl4ai/async_webcrawler.py", line 218, in __aenter__
return await self.start()
^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/crawl4ai/async_webcrawler.py", line 203, in start
await self.awarmup()
File "/usr/local/lib/python3.12/site-packages/crawl4ai/async_webcrawler.py", line 232, in awarmup
self.logger.info(f"Crawl4AI {crawl4ai_version}", tag="INIT")
File "/usr/local/lib/python3.12/site-packages/crawl4ai/async_logger.py", line 158, in info
self._log(LogLevel.INFO, message, tag, **kwargs)
File "/usr/local/lib/python3.12/site-packages/crawl4ai/async_logger.py", line 147, in _log
print(log_line)
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 47, in write
self.__convertor.write(text)
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 177, in write
self.write_and_convert(text)
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 202, in write_and_convert
self.write_plain_text(text, cursor, start)
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 210, in write_plain_text
self.wrapped.write(text[start:end])
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 47, in write
self.__convertor.write(text)
File "/usr/local/lib/python3.12/site-packages/colorama/ansitowin32.py", line 177, in write
I am also experiencing the same error. This issue occurs when calling multiple URLs more than 100 times within a short period. I also confirmed that more than 2000 zombie processes are created when checking the process. As a result, it returns a recursion error for all subsequent requests. The identified processes are as follows:
root 79610 79421 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79615 79470 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79635 79427 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79649 79452 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79651 79459 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79668 79465 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79669 79494 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79705 79439 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79707 79471 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79733 62099 3 14:20 ? 00:00:00 /usr/local/lib/python3.10/dist-packages/playwright/driver/node /usr/local/lib/python3.10/dist-packages/playwright/drive
root 79767 79496 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79796 79372 1 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --disable-field-trial-config --disable-background-networki
root 79804 79370 1 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --disable-field-trial-config --disable-background-networki
root 79810 79376 1 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --disable-field-trial-config --disable-background-networki
root 79831 79374 1 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --disable-field-trial-config --disable-background-networki
root 79853 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --monitor-self --monitor-self-annotation=
root 79854 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --monitor-self --monitor-self-annotation=
root 79855 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --monitor-self --monitor-self-annotation=
root 79859 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --no-periodic-tasks --monitor-self-annota
root 79860 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --no-periodic-tasks --monitor-self-annota
root 79861 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --no-periodic-tasks --monitor-self-annota
root 79865 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --monitor-self --monitor-self-annotation=
root 79868 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --no-periodic-tasks --monitor-self-annota
root 79872 79810 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-zygote-sandbox --no-sandbox --headless
root 79873 79804 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-zygote-sandbox --no-sandbox --headless
root 79874 79810 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-sandbox --headless --string-annotations
root 79875 79804 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-sandbox --headless --string-annotations
root 79877 79796 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-zygote-sandbox --no-sandbox --headless
root 79879 79796 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-sandbox --headless --string-annotations
root 79880 79831 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-zygote-sandbox --no-sandbox --headless
root 79881 79831 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-sandbox --headless --string-annotations
root 79954 79873 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79955 79872 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79956 79877 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79960 79880 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 79973 79804 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79974 79796 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79975 79810 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79979 79831 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root 79985 79875 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79986 79881 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79987 79874 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 79988 79879 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=storage.mojom.StorageSer
root 80115 79733 1 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --disable-field-trial-config --disable-background-networki
root 80117 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --monitor-self --monitor-self-annotation=
root 80119 1 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome_crashpad_handler --no-periodic-tasks --monitor-self-annota
root 80122 80115 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-zygote-sandbox --no-sandbox --headless
root 80123 80115 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=zygote --no-sandbox --headless --string-annotations
root 80143 80122 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=gpu-process --no-sandbox --disable-dev-shm-usage --
root 80147 80115 0 14:20 ? 00:00:00 /root/.cache/ms-playwright/chromium-1148/chrome-linux/chrome --type=utility --utility-sub-type=network.mojom.NetworkSer
root
This is pretty bad, actually. If left unattended, this would consume all the server memory.
Moreover, further observation show that overlapping may have nothing to do with it: I separated the 2 processes I described into 2 separate Docker containers, yet the issue continues to occur. For some time, the operations would continue successfully, then at some point, the recursion error occurs and never goes away until the app is restarted
@betterthanever2 @Liky98 Here are a few points that may be helpful. First, the Docker deployment is still in testing, and I am completely rewriting it in a new way that is very different from the current version. This time, I am building it specifically for scalability. The current crawling approach was just an immediate attempt to build a web server over the library, and it is not well optimized.
Based on the data I collected, I developed a better solution that does not require any form of web server wrapper around the crawler, allowing you to use it directly in your project without needing to communicate with Docker. It uses remote browser concepts and is currently under development. We are even testing it on a Raspberry Pi to ensure it can function in low-memory and resource-limited environments, and it is performing well. I hope to have the first version ready within a few weeks.
Another observation is that the way you use the library causes it to generate new browser instances of Chrome continuously. Remember, there are different ways to manage browser instances. You can create a new browser instance or lock one browser instance and create new pages within that instance. Additionally, when you perform sequential browsing, you can use a session ID to ensure you always use the same page. Ultimately, you should aim to have N browsers, with each one running a maximum of M processes, where MxN dynamically matches your available resources. The best approach is batch processing, which means creating one browser instance and then generating a certain number of pages or sessions, dividing your crawling process accordingly.
The good news is that while we work on this new Docker deployment, we are also creating a module that schedules the execution of the crawling. This module will dynamically read the available CPU and memory resources and adjust according to a standard scheduling algorithm to maximize performance based on the available hardware and resources. Therefore, please stay tuned and be patient with the library; those features will be available soon.
For the current Docker version, if you want to use it, make sure you are using it properly and not creating multiple instances of Chrome. Perhaps you can provide me with a simple code snippet of how you are working with it, and I will take a look.
Again, I prefer to release the new Docker version soon, designed with the insights and experiences I gained over the last two months based on reports and data collected from others.
Thank you so much. Please stay tuned. We are doing our best to develop an innovative way to launch this crawling engine at a production level scale. I close the issue, but you are most welcome to continue the conversation.
@unclecode thank you for your response The thing is, as far as I can tell there is very little difference between my code and what I saw in the documentation. Here's an example method
async def fetch_page_items(self, url: str) -> list[dict] | None:
async with AsyncWebCrawler(verbose=True) as crawler:
result = await crawler.arun(url=url,
extraction_strategy=self.extraction_strategy,
bypass_cache=True)
assert result.success
logfire.debug(f"Content {result.model_dump()} items")
items = json.loads(result.extracted_content)
return items
Certain options can be different (cache use, verbosity etc), but all in all nothing outlandish. I am sure you are correct about the numerous instances of browser being launched, but I haven't seen this in the docs.
Remember, there are different ways to manage browser instances. You can create a new browser instance or lock one browser instance and create new pages within that instance.
Can you point me in the direction of some documentation that describes how to do this?
@betterthanever2 Ok, I can see what we can do. By tomorrow or day after tomorrow, I will write a simple script that improves the crawling process. Additionally, I am updating all the documents, as some have become outdated. I made changes in version 0.4 that caused contradictions in the documents, and I am addressing all of them. Hopefully, we will resolve this within a few weeks plus releasing the new executor and docker. In the meantime, tomorrow or the day after, I will provide a short solution to help you handle it better.
hello, @unclecode. Any updates on this?
@betterthanever2 Please try version ~0.4.248~ 0.4.24y. I fixed the memory leak issue. Even with the current Docker, you shouldn't encounter any problems. I suggest you try the code below first to get yourself familiar. This is part of new documentation that I will upload soon:
import os
import sys
import psutil
import asyncio
__location__ = os.path.dirname(os.path.abspath(__file__))
__output__ = os.path.join(__location__, "output")
# Append parent directory to system path
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)
from typing import List
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
async def crawl_parallel(urls: List[str], max_concurrent: int = 3):
print("\n=== Parallel Crawling with Browser Reuse + Memory Check ===")
# We'll keep track of peak memory usage across all tasks
peak_memory = 0
process = psutil.Process(os.getpid())
def log_memory(prefix: str = ""):
nonlocal peak_memory
current_mem = process.memory_info().rss # in bytes
if current_mem > peak_memory:
peak_memory = current_mem
print(f"{prefix} Current Memory: {current_mem // (1024 * 1024)} MB, Peak: {peak_memory // (1024 * 1024)} MB")
# Minimal browser config
browser_config = BrowserConfig(
headless=True,
verbose=False,
extra_args=["--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox"],
)
crawl_config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS)
# Create the crawler instance
crawler = AsyncWebCrawler(config=browser_config)
await crawler.start()
try:
# We'll chunk the URLs in batches of 'max_concurrent'
success_count = 0
fail_count = 0
for i in range(0, len(urls), max_concurrent):
batch = urls[i : i + max_concurrent]
tasks = []
for j, url in enumerate(batch):
# Unique session_id per concurrent sub-task
session_id = f"parallel_session_{i + j}"
task = crawler.arun(url=url, config=crawl_config, session_id=session_id)
tasks.append(task)
# Check memory usage prior to launching tasks
log_memory(prefix=f"Before batch {i//max_concurrent + 1}: ")
# Gather results
results = await asyncio.gather(*tasks, return_exceptions=True)
# Check memory usage after tasks complete
log_memory(prefix=f"After batch {i//max_concurrent + 1}: ")
# Evaluate results
for url, result in zip(batch, results):
if isinstance(result, Exception):
print(f"Error crawling {url}: {result}")
fail_count += 1
elif result.success:
success_count += 1
else:
fail_count += 1
print(f"\nSummary:")
print(f" - Successfully crawled: {success_count}")
print(f" - Failed: {fail_count}")
finally:
print("\nClosing crawler...")
await crawler.close()
# Final memory log
log_memory(prefix="Final: ")
print(f"\nPeak memory usage (MB): {peak_memory // (1024 * 1024)}")
async def main():
urls = [
f"https://example.com/page{i}" for i in range(1, 21)
]
await crawl_parallel(urls, max_concurrent=4)
if __name__ == "__main__":
asyncio.run(main())
Take a look at the output:
=== Parallel Crawling with Browser Reuse + Memory Check ===
Before batch 1: Current Memory: 131 MB, Peak: 131 MB
After batch 1: Current Memory: 133 MB, Peak: 133 MB
Before batch 2: Current Memory: 133 MB, Peak: 133 MB
After batch 2: Current Memory: 134 MB, Peak: 134 MB
Before batch 3: Current Memory: 134 MB, Peak: 134 MB
After batch 3: Current Memory: 134 MB, Peak: 134 MB
Before batch 4: Current Memory: 134 MB, Peak: 134 MB
After batch 4: Current Memory: 135 MB, Peak: 135 MB
Before batch 5: Current Memory: 135 MB, Peak: 135 MB
After batch 5: Current Memory: 135 MB, Peak: 135 MB
Summary:
- Successfully crawled: 20
- Failed: 0
Closing crawler...
Final: Current Memory: 135 MB, Peak: 135 MB
Peak memory usage (MB): 135
As you can see the memory peak has been 135MB.
Thank you! Will try this asap.
Thank you for addressing the issue and offering a solution. I sincerely hope that the memory leak issue will be resolved moving forward.
Hi @unclecode @betterthanever2 @Liky98 can anyone help how I can update my current version to 0.4.248 . Do I need to take a pull of any branch locally and make a build ?
@psychicDivine @Liky98 @betterthanever2 Sorry, my mistake. You can already upgrade to version 0.4.247. It was a typo mistake when I mentioned 0.4.248, so if you install down the latest version pip install -U crawl4ai I hope everything works fine and there shouldn't be any memory leakage anymore. Please try it and let me know.
@unclecode just wanted to let you know, that after refactoring the app, and then observing it for a few hours in action, I can confirm that no memory issues occur. Thank you!
However, I am getting this other exception. I would probably create another issue, but wanted to put it here cause it seems like an internal thing.
Failed to fetch page https://www.infox.ru/archive/2023-9-14: Unexpected error in _crawl_web at line 585 in create_browser_context (../crawl4ai/async_crawler_strategy.py):
Error: 'NoneType' object has no attribute 'new_context'
Code context:
580 }
581 # Update context settings with text mode settings
582 context_settings.update(text_mode_settings)
583
584 # Create and return the context with all settings
585 → context = await self.browser.new_context(**context_settings)
586
587 # Apply text mode settings if enabled
588 if self.config.text_mode:
589 # Create and apply route patterns for each extension
590 for ext in blocked_extensions:
@betterthanever2 Glad to hear that, and regarding the second issue, are you able to replicate it, so I can focus on that? Please try it and then make a new issue.
@unclecode I think that specific issue occurred because I tried to crawl concurrently too many pages at once - with properly organized code, I can't replicate it. Thank you for the assist!
@betterthanever2 In just a few days, I will release a new version, and we have something very interesting. You're going to love it. It is designed to handle, and encapsulates all the difficulties of crawling theoretically infinite URLs simultaneously, depending on the available memory resources. I will record a good video and post it on my X account.
@unclecode Hello! We were facing the same maximum recursion depth exceeded error and tried your solution. Our goal is to crawl up to 250 pages, and we're using crawl4ai in our dockerized app (python:3.9-slim-bullseye).
Unfortunately, it seems that the crawler keeps the resources after each arun(..) call, consuming more and more memory, even though the process memory logs show only moderate values (<= 250mb). Is there a way to free the resources between arun(..) calls?
Additionally, what is the best approach for crawling a large number of pages in a long-running app? I understand that starting and closing the crawler manually is recommended, but are there any useful guides or best practices on this topic?
Regarding the original maximum recursion depth exceeded error, it seems like it occurs because of multiple colorama initializations, as discussed here.
@ruslankostiuk27 in 0.4.247 this is issue already resolved, can I see your code snippet? Btw today or tomorrow I release new version with a new update specifically for high quantity urls. Meantime check this https://docs.crawl4ai.com/advanced/multi-url-crawling/
However this page will be updated soon with the new method, however still its a valid document.
@unclecode Thank you for the reply! I mistyped the version when testing the fix, everything's OK now. Looking forward to the new release!
Awesome