crawl4ai icon indicating copy to clipboard operation
crawl4ai copied to clipboard

Memory Issues / Timeouts Running Docker Images on AWS

Open kylepatel opened this issue 1 year ago • 8 comments

Awesome project! Super helpful!

I'm just using the images right from docker hub for basic-amd64 and all-amd64.

I'm seeing some strange memory behavior when running as a docker container on AWS. When the crawl is running the memory utilization steadily climbs. If I let it go, it ends up going to 99+% and it gets super slow (or just starts timing out), so what I've been doing it every hour or so just rebooting the container to clear out the memory, but thats not the best practice. Curious whats going on with the memory management under the hood.

My typical crawl params:

            "crawler_params": {
                "headless": True,
                "simulate_user": True,
                "page_timeout": 3000,
                "remove_overlay_elements": True,
                "magic": True,
                "override_navigator": True,
            },

Example: At the beginning my crawl is running and memory is steadying being consumed. When the container is idling (for a solid 10 hours) memory isn't be released. At the end I just rebooted it to clear it out.

This machine has 32GB RAM, which should be plenty. image

Haven't had a chance yet to debug this locally myself.

kylepatel avatar Dec 19 '24 18:12 kylepatel

@kylepatel Thanks for trying Crawl4AI! Apologies for the delayed response—I’ve been busy updating documentation. Let’s address your issue:

  1. Optimization Recommendations:

    • Disable the GPU by passing --disable-gpu as a browser argument.
    • Reduce the viewport size to improve performance.
  2. Crawl Usage:

    • Please share your implementation details, especially your approach to creating instances of the AsyncWebCrawler class.
    • Avoid creating a new browser instance for each URL, this significantly impacts performance. Instead:
      • Create one browser instance and open new pages or tabs within it.
      • For sequential crawling, use a session ID to reuse the same tab rather than opening multiple tabs or processes.
  3. Next Steps:

    • Let me know how you’ve used Crawl4AI and share your code if possible. I can provide more specific guidance based on your setup.

I also share a coding snippet that explains the general approach. Let me know your thoughts.

"""
This example demonstrates optimal browser usage patterns in Crawl4AI:
1. Sequential crawling with session reuse
2. Parallel crawling with browser instance reuse
3. Performance optimization settings
"""

import asyncio
import os
from typing import List
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
from crawl4ai.content_filter_strategy import PruningContentFilter
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator

async def crawl_sequential(urls: List[str]):
    """
    Sequential crawling using session reuse - most efficient for moderate workloads
    """
    print("\n=== Sequential Crawling with Session Reuse ===")
    
    # Configure browser with optimized settings
    browser_config = BrowserConfig(
        headless=True,
        browser_args=[
            "--disable-gpu",              # Disable GPU acceleration
            "--disable-dev-shm-usage",    # Disable /dev/shm usage
            "--no-sandbox",               # Required for Docker
        ],
        viewport={'width': 800, 'height': 600}  # Smaller viewport for better performance
    )
    
    # Configure crawl settings
    crawl_config = CrawlerRunConfig(
        content_filter=PruningContentFilter(),
        markdown_generator=DefaultMarkdownGenerator(),
        screenshot=False  # Disable screenshots if not needed
    )
    
    # Create single crawler instance
    crawler = AsyncWebCrawler(config=browser_config)
    await crawler.start()
    
    try:
        session_id = "session1"  # Use same session for all URLs
        for url in urls:
            result = await crawler.arun(
                url=url,
                config=crawl_config,
                session_id=session_id  # Reuse same browser tab
            )
            if result.success:
                print(f"Successfully crawled {url}")
                print(f"Content length: {len(result.markdown_v2.raw_markdown)}")
    finally:
        await crawler.close()

async def crawl_parallel(urls: List[str], max_concurrent: int = 3):
    """
    Parallel crawling while reusing browser instance - best for large workloads
    """
    print("\n=== Parallel Crawling with Browser Reuse ===")
    
    browser_config = BrowserConfig(
        headless=True,
        browser_args=["--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox"],
        viewport={'width': 800, 'height': 600}
    )
    
    crawl_config = CrawlerRunConfig(
        content_filter=PruningContentFilter(),
        markdown_generator=DefaultMarkdownGenerator(),
        screenshot=False
    )
    
    # Create single crawler instance for all parallel tasks
    crawler = AsyncWebCrawler(config=browser_config)
    await crawler.start()
    
    try:
        # Create tasks in batches to control concurrency
        for i in range(0, len(urls), max_concurrent):
            batch = urls[i:i + max_concurrent]
            tasks = []
            
            for j, url in enumerate(batch):
                session_id = f"parallel_session_{j}"  # Different session per concurrent task
                task = crawler.arun(
                    url=url,
                    config=crawl_config,
                    session_id=session_id
                )
                tasks.append(task)
            
            # Wait for batch to complete
            results = await asyncio.gather(*tasks, return_exceptions=True)
            
            # Process results
            for url, result in zip(batch, results):
                if isinstance(result, Exception):
                    print(f"Error crawling {url}: {str(result)}")
                elif result.success:
                    print(f"Successfully crawled {url}")
                    print(f"Content length: {len(result.markdown_v2.raw_markdown)}")
    finally:
        await crawler.close()

async def main():
    # Example URLs
    urls = [
        "https://example.com/page1",
        "https://example.com/page2",
        "https://example.com/page3",
        "https://example.com/page4",
    ]
    
    # Demo sequential crawling
    await crawl_sequential(urls)
    
    # Demo parallel crawling
    await crawl_parallel(urls, max_concurrent=2)

if __name__ == "__main__":
    asyncio.run(main())

Looking forward to your details so I can assist further!

unclecode avatar Dec 25 '24 11:12 unclecode

Ah I see, I'm currently just posting to the docker instance you've shared via dockerhub. I brought up that instance in my ECS Cluster and I'm hitting it like this:

    def _get_headers(self) -> Dict[str, str]:
        if not CRAWL4AI_API_TOKEN:
            return {}
        return {"Authorization": f"Bearer {CRAWL4AI_API_TOKEN}"}

    def create_request(
        self,
        url: str,
        llm: bool = False,
        screenshot: bool = False,
        custom_extraction: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        request = {
            "urls": url,
            "priority": 10,
            "screenshot": screenshot,
            "crawler_params": {
                "headless": True,
                "browser_type": "chromium",
                "simulate_user": True,
                "page_timeout": 3000,
                "remove_overlay_elements": True,
                "magic": True,
                "verbose": True,
                "log_console": True,
                "override_navigator": True,
                "use_managed_browser": False,
            },
            "extra": {
                "word_count_threshold": 5,
                "process_iframes": False,
                "bypass_cache": False,
                "only_text": True,
                "exclude_external_links": True,
                "delay_before_return_html": 2.0,
            },
        }

        if llm:
            request["extraction_config"] = custom_extraction or {
                "type": "llm",
                "params": {
                    "provider": "openai/gpt-4o-mini",
                    "instruction": """
                    Analyze and extract the following from the webpage content for a RAG system.
                    """,
                },
            }

        return request

    def crawl(
        self,
        url: str,
        llm: bool = False,
        screenshot: bool = False,
        max_wait: int = 60,
        custom_extraction: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """
        Crawl a URL and wait for results

        Args:
            url: URL to crawl
            llm: Whether to use LLM extraction
            screenshot: Whether to take a screenshot
            max_wait: Maximum seconds to wait for completion
            custom_extraction: Custom extraction config to override default LLM config

        Returns:
            Dict containing crawl results including markdown content, extracted content if LLM used,
            links found, and content chunks
        """
        try:
            start_time = time.time()
            logging.info(f"Starting crawl request for {url}")

            request_data = self.create_request(url, llm, screenshot, custom_extraction)

            response = self.session.post(
                f"{self.base_url}/crawl", headers=self.headers, json=request_data
            )
            if response.status_code != 200:
                raise ValueError(f"Failed to submit crawl task: {response.text}")
            task_data = response.json()
            task_id = task_data["task_id"]

            while time.time() - start_time < max_wait:
                status_response = self.session.get(
                    f"{self.base_url}/task/{task_id}", headers=self.headers
                )
                if status_response.status_code != 200:
                    raise ValueError(f"Failed to get task status: {status_response.text}")
                status_data = status_response.json()

                if status_data.get("status") == "completed" and "result" in status_data:
                    endtime = time.time()
                    duration = round(endtime - start_time, 2)
                    logging.info(f"Finished crawl request for {url} after {duration} seconds")

                    return status_data["result"]
                elif status_data.get("status") == "failed":
                    raise ValueError(f"Task failed: {status_data.get('error', 'Unknown error')}")

            raise TimeoutError(f"Timeout after {max_wait} seconds")

        except requests.exceptions.RequestException as e:
            raise ValueError(f"Network error: {str(e)}")

I'm not instantiating anything myself directly, but posting to the docker instance and then polling for the response. Is this an advisable way to use the docker images?

I was following the instructions here: https://crawl4ai.com/mkdocs/basic/docker-deploymeny/

kylepatel avatar Dec 30 '24 05:12 kylepatel

@kylepatel I am planning to work on a different approach for Docker, and this new approach works much better than the previous one. It's sophisticated and fast; you can even run it on a Raspberry Pi. I'm developing a model to enable decentralized operation. Let me reach the endpoint, and I will provide a proper update. To answer your question, I don't think this is the best way to proceed, which is why this was a temporary experimental approach to see how it works with Docker. The new approach does not involve running a web server in Docker and releasing an endpoint. I will work on it, and hopefully, it will be ready by the end of this month.

unclecode avatar Jan 01 '25 12:01 unclecode

Same issue here. Deployment on aws with docker and using api endpoint makes RAM usage go higher and higher until no more available slots are left :(

prorid3r avatar Feb 11 '25 11:02 prorid3r

@prorid3r We are coming up with a brand new docker setup that's robust and easily deployable. Stay tuned on @unclecode's twitter handle for release updates.

aravindkarnam avatar Feb 12 '25 04:02 aravindkarnam

Is this issue fixed? because I am also facing same issue

Image

sparklineIT avatar Jun 26 '25 08:06 sparklineIT

I have the same problem with the Docker installation (0.7.0-r1). During a couple of hundreds single crawls, RAM usage steadily increases until the final crash.

rawinkler avatar Jul 20 '25 15:07 rawinkler

Are there any news on this? Seems closed and we are at 0.7.8 now and I'm facing the same issues described. Using docker service as api endpoint. Have I overseen any release notes regarding this issue?

Codinator007 avatar Jan 28 '26 19:01 Codinator007