# Optimization

A crawl goes as fast as its slowest part allows. Find out which part that
is (see Finding the bottleneck) before changing any setting.

Broad crawls (see Speeding up broad crawls) have their own set of recommended
adjustments.

## Finding the bottleneck

The bottleneck depends on the spider: on the same machine, one crawl can be
limited by its own parsing code and another by the target website. So measure
the crawl that you want to optimize.

[`LogStats`](extensions.md) reports crawl speed every
[`LOGSTATS_INTERVAL`](settings.md) seconds:

```text
[scrapy.extensions.logstats] INFO: Crawled 1200 pages (at 60 pages/min), scraped 1150 items (at 58 items/min)
```

A rate that stays flat as you raise [`CONCURRENT_REQUESTS`](settings.md) means
something else is the limit.

### Reading the engine status

The [telnet console](telnetconsole.md) reports, through `est()`,
what every part of the engine is doing at a given moment:

```text
len(engine.downloader.active)                   : 16
len(engine.scheduler.mqs)                       : 92
len(engine.scraper.slot.active)                 : 0
engine.response_active_size                     : 1310720
```

A coding agent using the [Scrapy MCP server](agents.md "Using the MCP server") can also
retrieve these values directly.

Take a few readings at different points of the crawl:

- `len(engine.downloader.active)` stays at [`CONCURRENT_REQUESTS`](settings.md):
  the downloader is the limit. You are waiting on the network or on the
  target website. See Sending more requests at a time.
- `len(engine.downloader.active)` stays below
  [`CONCURRENT_REQUESTS`](settings.md) while the scheduler queues (`mqs`,
  `dqs`) hold requests: something throttles those requests before they
  reach the downloader, usually [`CONCURRENT_REQUESTS_PER_DOMAIN`](settings.md),
  [`DOWNLOAD_DELAY`](settings.md) or [AutoThrottle](autothrottle.md).
- Both the downloader and the scheduler queues stay near empty: your spider
  is not producing requests fast enough. A crawl that walks pagination one
  page at a time cannot use more concurrency than it creates. See
  Producing requests faster.
- [`engine.response_active_size`](api.md) approaches
  [`RESPONSE_MAX_ACTIVE_SIZE`](settings.md), or the
  [`request_backout_seconds/response_max_active_size`](stats.md) stat grows (see
  [Identifying crawl bottlenecks](practices.md)): responses arrive faster than your callbacks and
  [item pipelines](item-pipeline.md) handle them, or your code
  keeps responses in memory. The bottleneck is your own code.
- `len(engine.scheduler.mqs)` grows without settling: the crawl discovers
  requests faster than it downloads them. This is what makes long crawls run
  out of memory.

### Reading resource usage

CPU
: Scrapy runs in a single process, and everything except DNS resolution and
  code you explicitly move to a thread runs in a single thread. One CPU core
  is the ceiling; a process sitting at 100% of a core is CPU-bound no matter
  how many cores the machine has.
  <br/>
  The [event loop lag monitor](extensions.md) logs a warning when
  CPU-bound code blocks that single thread for too long; lower
  [`EVENT_LOOP_LAG_THRESHOLD`](settings.md) to catch shorter stalls.
  <br/>
  Use a sampling profiler, such as [py-spy](https://github.com/benfred/py-spy), to find out which code is
  spending that CPU. [Selectors](selectors.md) and item pipelines
  are the usual answer.

Memory
: The [memory usage extension](extensions.md) records
  [`memusage/startup`](stats.md) and [`memusage/max`](stats.md). A [`memusage/max`](stats.md)
  far above [`memusage/startup`](stats.md) is expected; what matters is whether it
  keeps growing for as long as the crawl runs.
  <br/>
  Growth that tracks `len(engine.scheduler.mqs)` is a scheduling problem,
  covered in Lowering memory usage. Growth that does not is a [memory
  leak](leaks.md).

Network
: Compare [`downloader/response_bytes`](stats.md) over the crawl time against your
  available bandwidth. Saturated bandwidth caps concurrency regardless of any
  setting.
  <br/>
  DNS resolution is separate: it runs on a thread pool of
  [`REACTOR_THREADPOOL_MAXSIZE`](settings.md) threads, and results are cached
  ([`DNSCACHE_ENABLED`](settings.md), [`DNSCACHE_SIZE`](settings.md)). It only becomes a
  limit of its own when there are many different domains to resolve, as in
  broad crawls (see Speeding up broad crawls), where it shows up as slow starts and
  DNS timeouts.

Disk
: [Feed exports](feed-exports.md) write to disk on most crawls,
  although item data is usually small enough for that not to matter. The ones
  to suspect are
  [`HttpCacheMiddleware`](downloader-middleware.md) and
  the [media pipelines](media-pipeline.md), which write whole
  responses, and [`JOBDIR`](settings.md), which writes every scheduled request.

## Sending more requests at a time

[`CONCURRENT_REQUESTS`](settings.md) caps how many requests are being downloaded at
any given moment, [`CONCURRENT_REQUESTS_PER_DOMAIN`](settings.md) caps how many of
those may target the same domain, and [`DOWNLOAD_DELAY`](settings.md) sets a minimum
wait between two consecutive requests to the same domain. A project generated by
[`startproject`](commands.md) gets one request per second per domain out of these.

Raise them to crawl a single website faster, and see
[broad-crawls-concurrency](https://docs.scrapy.org/en/latest/topics/optimize.md#broad-crawls-concurrency) to spread requests across many websites
instead.

Concurrency also drives how many connections stay open, which is capped
separately by [`CONCURRENT_CONNECTIONS_PER_HANDLER`](settings.md). See
[I get too many file descriptors in select() or Too many open files](../faq.md) if a crawl runs out of file descriptors.

The limit that matters, though, is the one the target website tolerates.
Exceeding it gets you throttled, served errors or banned, all of which make the
crawl slower than a lower concurrency would have been. To find that limit:

- Read the [robots.txt](downloader-middleware.md "RobotsTxtMiddleware") file of the website. Scrapy
  does not act on its `Crawl-delay` and `Request-rate` directives, so when
  they are present, translate them into [`DOWNLOAD_DELAY`](settings.md) and
  concurrency settings yourself.
- Check the traffic that the website already gets, using a service like
  [SimilarWeb](https://www.similarweb.com/) or [Cloudflare Radar](https://radar.cloudflare.com/). A rate that is a rounding error next
  to what the website serves anyway is unlikely to be a problem for it.
- Look for a documented way in. An API, a bulk export or a search endpoint is
  both faster for you and cheaper for the website than crawling its pages, and
  the terms of service may state a rate.
- Crawl when the website is idle, in its own timezone, so that the capacity
  you take is capacity nobody else wanted.
- Raise concurrency gradually and watch the website respond, changing it on
  the running crawl from the [telnet console](telnetconsole.md "Change concurrency and delays").
  [`downloader/response_status_count/{status_code}`](stats.md) counts for 429, 503
  or the ban page of the website, growing [`retry/count`](stats.md), or a
  [download latency](autothrottle.md) that climbs as you push harder,
  all mean you have gone past the limit.

## Producing requests faster

A spider that discovers its requests one response at a time keeps the
downloader idle no matter how high you set [`CONCURRENT_REQUESTS`](settings.md). To
put more requests in the scheduler earlier:

- Request every page at once when you can work out how many there are, e.g.
  from a page count or from a result count and a page size in the first
  response, instead of following a link to the next page on every response.
- Get URLs from a source that lists many of them at once, such as a sitemap
  or a search or export endpoint of the target website. For a crawl that
  needs nothing else, [`SitemapSpider`](spiders.md) reads sitemaps
  for you.
- Raise the [`priority`](request-response.md) of pagination requests, so that
  they are downloaded before the requests that they compete with, and
  discover the rest of the crawl sooner.

Each of these trades memory for speed: a request produced before the downloader
can take it waits in the scheduler, or on disk if you set [`JOBDIR`](settings.md).
Pushed far enough, they turn memory or disk into your new bottleneck, which is
why Lowering memory usage recommends the reverse of the last point.

## Keeping the event loop free

Your callbacks, [spider middlewares](spider-middleware.md),
[downloader middlewares](downloader-middleware.md) and [item
pipelines](item-pipeline.md) share a thread with the event loop. While any
of them runs, Scrapy neither sends requests nor reads responses, so every
download in flight waits for it.

That shows up as a [download latency](autothrottle.md) that grows
through the crawl, often into tens of seconds, while the target website answers
as fast as ever: the latency of a response covers the time until Scrapy gets
around to reading it, and every pending callback runs first.

Move the slow code to a thread so that downloads continue while it runs:

```python
import asyncio

from scrapy import Spider


class SlowParseSpider(Spider):
    name = "slow_parse"
    start_urls = ["https://toscrape.com"]

    async def parse(self, response):
        yield await asyncio.to_thread(self.extract_item, response)

    def extract_item(self, response):
        # CPU-heavy parsing
        ...
```

A thread does not give CPU-bound Python code more CPU to work with, since it
still competes for the GIL; it only keeps that code from holding up downloads.
See [Distributed crawls](practices.md) to use more than one core.

## Lowering resource usage

### Lowering memory usage

- Lower [`RESPONSE_MAX_ACTIVE_SIZE`](settings.md).
- Lower [`DOWNLOAD_MAXSIZE`](settings.md), which allows a single response to take up
  to 1 GiB of memory by default, multiplied by your concurrency. Set
  [`DOWNLOAD_WARNSIZE`](settings.md) first to find out whether the website actually
  serves responses that big.
- Lower the number of [scheduled requests](scheduler.md) held in
  memory:
  - Increase the [`priority`](request-response.md) of requests whose
    [`callback`](request-response.md) cannot yield additional requests.

    For example, the following spider uses a higher priority (1) for book
    requests than for pagination requests:
    ```python
    from scrapy import Spider


    class BooksToScrapeComSpider(Spider):
        name = "books_toscrape_com"
        start_urls = [
            "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html"
        ]

        def parse(self, response):
            next_page_links = response.css(".next a")
            yield from response.follow_all(next_page_links)
            book_links = response.css("article a")
            yield from response.follow_all(book_links, callback=self.parse_book, priority=1)

        def parse_book(self, response):
            yield {
                "name": response.css("h1::text").get(),
                "price": response.css(".price_color::text").re_first("£(.*)"),
                "url": response.url,
            }
    ```

    > [!NOTE]
    > If the number of request-yielding, low-priority requests
    > scheduled at any given time is lower than concurrency settings
    > ([`CONCURRENT_REQUESTS_PER_DOMAIN`](settings.md) or
    > [`CONCURRENT_REQUESTS`](settings.md)), as in the example above, this can
    > slow down your crawl by turning those requests into a bottleneck.
  - If you have many [start requests](spiders.md), consider
    [delaying their iteration](spiders.md "Delaying start request iteration").
  - Set [`JOBDIR`](settings.md) to offload all scheduled requests to disk.
- Set [`DUPEFILTER_CLASS`](settings.md) to
  [`DiskDupeFilter`](settings.md) to keep the fingerprint of
  every sent request on disk instead of in memory.
- Set [`MEDIA_CACHE_SIZE`](media-pipeline.md) if you use [media pipelines](media-pipeline.md).
- Be on the lookout for [memory leaks](leaks.md).

### Lowering network usage

- Enable [`HttpCacheMiddleware`](downloader-middleware.md)
  while developing your spider, so that re-runs do not download the same
  responses again.

### Lowering CPU usage

- Set [`LOG_LEVEL`](settings.md) to `"INFO"` or higher.
- Restrict what you parse. A [selector](selectors.md) over a
  smaller part of the response, or a single query whose result you reuse,
  beats repeated queries over the whole document.

### Other tips

- Try [using the asyncio reactor](asyncio.md "Installing the asyncio reactor") with [uvloop](https://github.com/MagicStack/uvloop) as
  [custom event loop](asyncio.md "Using custom asyncio loops"), i.e. setting
  [`ASYNCIO_EVENT_LOOP`](settings.md) to `"uvloop.Loop"`.
- Disable unused [components](components.md).

  For example, set [`COOKIES_ENABLED`](cookies.md) to `False` unless you need
  cookies.
- Split the crawl across separate processes to use more than one CPU core.
  See [Distributed crawls](practices.md).

## Speeding up broad crawls

While Scrapy is well suited for **broad crawls**, i.e. crawls that target many
websites, the default [settings](settings.md) are optimized for
crawls targeting a single website.

For broad crawls, consider these adjustments:

- Increase the global concurrency:
  - Set [`CONCURRENT_REQUESTS`](settings.md) as close to
    [`CONCURRENT_REQUESTS_PER_DOMAIN`](settings.md) × [number of target domains]
    (e.g. 8 × 10 domains = 80 concurrent requests) as your CPU and memory
    allow.
  - Increase [`RESPONSE_MAX_ACTIVE_SIZE`](settings.md) when increasing
    [`CONCURRENT_REQUESTS`](settings.md) stops making a difference.
- If memory is a bottleneck, see if [crawling in BFO order](scheduler.md) lowers
  memory usage.
- Improve DNS resolution speed:
  - Set up your own DNS server, with a local cache and upstream to a [large
    DNS server](https://en.wikipedia.org/wiki/Public_recursive_name_server#Notable_public_DNS_service_operators), to avoid slowing down your network.
  - Increase [`REACTOR_THREADPOOL_MAXSIZE`](settings.md) to the minimum value
    that avoids DNS resolution timeouts and makes a noticeable positive
    impact in crawl speed.
- Lower the negative impact of some responses:
  - Set [`RETRY_ENABLED`](downloader-middleware.md) to `False` or, if you need retries,
    consider lowering [`RETRY_TIMES`](downloader-middleware.md).
  - Lower [`DOWNLOAD_TIMEOUT`](settings.md) to a more reasonable value, to
    discard stuck requests more quickly.
  - Set [`REDIRECT_ENABLED`](downloader-middleware.md) to `False` unless you want to follow
    redirects.
