15 KiB
Request to Response Lifecycle
This document explains how a :class:`~scrapy.Request` flows through Scrapy's internals, from creation in a spider to the delivery of a :class:`~scrapy.http.Response` back to a spider callback. Understanding this lifecycle helps when debugging, optimizing performance, or extending Scrapy with custom components.
System Message: ERROR/3 (<stdin>, line 7); backlink
Unknown interpreted text role "class".System Message: ERROR/3 (<stdin>, line 7); backlink
Unknown interpreted text role "class".For a high-level component overview, see :ref:`topics-architecture`. This page focuses on the detailed sequence of operations.
System Message: ERROR/3 (<stdin>, line 13); backlink
Unknown interpreted text role "ref".Lifecycle overview
A request passes through these main phases:
Creation: A spider yields a :class:`~scrapy.Request`
System Message: ERROR/3 (<stdin>, line 23); backlink
Unknown interpreted text role "class".
Scheduling: The engine passes the request to the scheduler for queuing
Downloading: The scheduler returns the request to the engine, which sends it to the downloader
Response handling: The downloader returns a response to the engine
Spider processing: The engine passes the response to the spider for callback execution
Output processing: Items go to pipelines; new requests return to step 2
The following sections describe each phase in detail.
The engine as orchestrator
The :ref:`execution engine <component-engine>` controls all data flow between Scrapy components. It does not process requests or responses itself; instead, it coordinates when each component acts and manages the transitions between phases.
System Message: ERROR/3 (<stdin>, line 37); backlink
Unknown interpreted text role "ref".The engine's responsibilities include:
- Obtaining start requests from the spider and passing them to the scheduler
- Requesting the next request from the scheduler when capacity is available
- Sending requests to the downloader and receiving responses
- Passing responses to the scraper for spider callback execution
- Routing callback output (items and new requests) to the appropriate components
- Monitoring idle conditions and initiating spider closure
The engine implements backpressure by checking whether the downloader or scraper can accept more work before dequeuing additional requests from the scheduler. This prevents memory exhaustion when spiders generate requests faster than they can be processed.
Backpressure conditions
The engine pauses request processing when any of these conditions are true:
The downloader has reached its concurrency limit (:setting:`CONCURRENT_REQUESTS`)
System Message: ERROR/3 (<stdin>, line 60); backlink
Unknown interpreted text role "setting".
The scraper's active response size exceeds its threshold (:setting:`SCRAPER_SLOT_MAX_ACTIVE_SIZE`)
System Message: ERROR/3 (<stdin>, line 61); backlink
Unknown interpreted text role "setting".
The engine is shutting down
Request scheduling and duplicate filtering
When the engine receives a request (from start requests or spider callbacks), it passes the request to the :ref:`scheduler <component-scheduler>`.
System Message: ERROR/3 (<stdin>, line 69); backlink
Unknown interpreted text role "ref".Scheduling process
The engine emits the :signal:`request_scheduled` signal
System Message: ERROR/3 (<stdin>, line 74); backlink
Unknown interpreted text role "signal".
If a signal handler raises :exc:`~scrapy.exceptions.IgnoreRequest`, the request is dropped
System Message: ERROR/3 (<stdin>, line 75); backlink
Unknown interpreted text role "exc".
The scheduler checks for duplicates using the configured duplicate filter
If the request is a duplicate (and dont_filter=False), it is rejected
Otherwise, the request is added to the scheduler's queue
Duplicate filtering
The default duplicate filter (:class:`~scrapy.dupefilters.RFPDupeFilter`) uses request fingerprints to identify duplicates. A fingerprint is computed from the request's URL, method, and body. The filter maintains a set of seen fingerprints and rejects requests whose fingerprint already exists.
System Message: ERROR/3 (<stdin>, line 82); backlink
Unknown interpreted text role "class".To bypass duplicate filtering for a specific request, set dont_filter=True when creating the request:
yield scrapy.Request(url, dont_filter=True)
For custom duplicate filtering logic, implement a class following the :class:`~scrapy.dupefilters.BaseDupeFilter` interface and configure it via the :setting:`DUPEFILTER_CLASS` setting.
System Message: ERROR/3 (<stdin>, line 92); backlink
Unknown interpreted text role "class".System Message: ERROR/3 (<stdin>, line 92); backlink
Unknown interpreted text role "setting".Queue structure
The default scheduler maintains two queues:
- Memory queue: Stores requests in memory for fast access
- Disk queue: Persists requests to disk when a job directory is configured
When dequeuing, the scheduler checks the memory queue first, then falls back to the disk queue. This design supports :ref:`pausing and resuming crawls <topics-jobs>`.
System Message: ERROR/3 (<stdin>, line 103); backlink
Unknown interpreted text role "ref".For more details on the scheduler, see :ref:`topics-scheduler`.
System Message: ERROR/3 (<stdin>, line 107); backlink
Unknown interpreted text role "ref".Downloading
When the engine determines it has capacity for more downloads, it requests the next request from the scheduler and passes it to the :ref:`downloader <component-downloader>`.
System Message: ERROR/3 (<stdin>, line 114); backlink
Unknown interpreted text role "ref".Download process
The engine calls the downloader with the request
The request passes through the :ref:`downloader middleware chain <component-downloader-middleware>` (process_request methods)
System Message: ERROR/3 (<stdin>, line 121); backlink
Unknown interpreted text role "ref".
If no middleware returns a response, the request reaches a download handler
The download handler performs the actual HTTP request
The response passes back through the downloader middleware chain (process_response methods)
The final response returns to the engine
Downloader middleware integration
Downloader middlewares can intercept requests before they reach the network and responses before they reach the spider. Common uses include:
- Setting headers (User-Agent, cookies, authentication)
- Handling redirects and retries
- Caching responses
- Returning synthetic responses without making network requests
Each middleware's process_request method can:
Return None to continue to the next middleware
Return a :class:`~scrapy.http.Response` to skip remaining middlewares and the download handler
System Message: ERROR/3 (<stdin>, line 140); backlink
Unknown interpreted text role "class".
Return a :class:`~scrapy.Request` to reschedule a different request
System Message: ERROR/3 (<stdin>, line 141); backlink
Unknown interpreted text role "class".
Raise :exc:`~scrapy.exceptions.IgnoreRequest` to abort the request
System Message: ERROR/3 (<stdin>, line 142); backlink
Unknown interpreted text role "exc".
For details on writing downloader middlewares, see :ref:`topics-downloader-middleware`.
System Message: ERROR/3 (<stdin>, line 144); backlink
Unknown interpreted text role "ref".Concurrency and delays
The downloader enforces concurrency limits at two levels:
Global: :setting:`CONCURRENT_REQUESTS` limits total simultaneous downloads
System Message: ERROR/3 (<stdin>, line 151); backlink
Unknown interpreted text role "setting".
Per-domain or per-IP: :setting:`CONCURRENT_REQUESTS_PER_DOMAIN` or :setting:`CONCURRENT_REQUESTS_PER_IP` limit downloads to each target
System Message: ERROR/3 (<stdin>, line 152); backlink
Unknown interpreted text role "setting".
System Message: ERROR/3 (<stdin>, line 152); backlink
Unknown interpreted text role "setting".
Download delays can be configured via :setting:`DOWNLOAD_DELAY`. When set, the downloader waits at least this many seconds between consecutive requests to the same domain. The :setting:`RANDOMIZE_DOWNLOAD_DELAY` setting adds randomization to make request timing less predictable.
System Message: ERROR/3 (<stdin>, line 154); backlink
Unknown interpreted text role "setting".System Message: ERROR/3 (<stdin>, line 154); backlink
Unknown interpreted text role "setting".Signals emitted during download
:signal:`request_reached_downloader`: When a request enters the downloader's active set
System Message: ERROR/3 (<stdin>, line 161); backlink
Unknown interpreted text role "signal".
:signal:`response_downloaded`: When the download handler returns a response
System Message: ERROR/3 (<stdin>, line 162); backlink
Unknown interpreted text role "signal".
:signal:`request_left_downloader`: When processing for a request completes
System Message: ERROR/3 (<stdin>, line 163); backlink
Unknown interpreted text role "signal".
:signal:`bytes_received`: When data chunks arrive during download
System Message: ERROR/3 (<stdin>, line 164); backlink
Unknown interpreted text role "signal".
:signal:`headers_received`: When HTTP headers are received
System Message: ERROR/3 (<stdin>, line 165); backlink
Unknown interpreted text role "signal".
Spider callback execution
After the engine receives a response from the downloader, it passes the response to the scraper, which manages spider callback execution.
Callback execution process
The response enters the scraper's queue
The response passes through :ref:`spider middleware <component-spider-middleware>` (process_spider_input methods)
System Message: ERROR/3 (<stdin>, line 178); backlink
Unknown interpreted text role "ref".
The spider's callback method is invoked with the response
The callback's output (an iterable of items and requests) passes through spider middleware (process_spider_output methods)
Items and requests are extracted from the processed output
Callback selection
The callback is determined by the request that generated the response:
- If request.callback is set, that function is called
- Otherwise, the spider's default _parse method (which calls parse) is used
If the download resulted in an error and the request has an errback, that function is called instead with a :class:`~twisted.python.failure.Failure` object.
System Message: ERROR/3 (<stdin>, line 190); backlink
Unknown interpreted text role "class".Spider middleware integration
Spider middlewares can process responses before they reach the callback and filter or transform the callback's output. Common uses include:
- Filtering responses (e.g., by HTTP status code or content type)
- Handling spider exceptions
- Modifying the items or requests yielded by callbacks
For details on writing spider middlewares, see :ref:`topics-spider-middleware`.
System Message: ERROR/3 (<stdin>, line 203); backlink
Unknown interpreted text role "ref".Signals emitted during spider processing
:signal:`response_received`: When the engine receives a response (before spider processing)
System Message: ERROR/3 (<stdin>, line 207); backlink
Unknown interpreted text role "signal".
:signal:`spider_error`: When a spider callback raises an exception
System Message: ERROR/3 (<stdin>, line 208); backlink
Unknown interpreted text role "signal".
Item pipeline processing
When a spider callback yields an item (a dict, :class:`~scrapy.Item`, or dataclass), the scraper passes it to the :ref:`item pipeline <component-pipelines>`.
System Message: ERROR/3 (<stdin>, line 215); backlink
Unknown interpreted text role "class".System Message: ERROR/3 (<stdin>, line 215); backlink
Unknown interpreted text role "ref".Pipeline execution
The item passes to the first pipeline's process_item method
If the pipeline returns an item, it passes to the next pipeline
This continues until all pipelines have processed the item
If any pipeline raises :exc:`~scrapy.exceptions.DropItem`, processing stops
System Message: ERROR/3 (<stdin>, line 224); backlink
Unknown interpreted text role "exc".
Pipeline configuration
Pipelines are enabled via the :setting:`ITEM_PIPELINES` setting, which maps pipeline classes to integer priority values. Lower values execute first.
System Message: ERROR/3 (<stdin>, line 228); backlink
Unknown interpreted text role "setting".Signals emitted during item processing
:signal:`item_scraped`: When an item successfully passes through all pipelines
System Message: ERROR/3 (<stdin>, line 233); backlink
Unknown interpreted text role "signal".
:signal:`item_dropped`: When a pipeline raises :exc:`~scrapy.exceptions.DropItem`
System Message: ERROR/3 (<stdin>, line 234); backlink
Unknown interpreted text role "signal".
System Message: ERROR/3 (<stdin>, line 234); backlink
Unknown interpreted text role "exc".
:signal:`item_error`: When a pipeline raises an unexpected exception
System Message: ERROR/3 (<stdin>, line 235); backlink
Unknown interpreted text role "signal".
For details on writing item pipelines, see :ref:`topics-item-pipeline`.
System Message: ERROR/3 (<stdin>, line 237); backlink
Unknown interpreted text role "ref".New request handling
When a spider callback yields a :class:`~scrapy.Request`, the scraper extracts it from the callback output and passes it back to the engine. The engine then schedules the request, and the lifecycle repeats from the scheduling phase.
System Message: ERROR/3 (<stdin>, line 244); backlink
Unknown interpreted text role "class".This recursive flow continues until:
- The scheduler has no pending requests
- All active downloads have completed
- The spider's start iterator is exhausted
- The scraper has no active responses
When all these conditions are met, the spider is considered idle.
Error handling
Scrapy handles errors at multiple points in the lifecycle.
Download errors
When a download fails (network error, timeout, etc.):
- The error passes through downloader middleware process_exception methods
- If a middleware returns a response or request, normal processing continues
- Otherwise, if the request has an errback, it is called with the failure
- If no errback exists, the error is logged
The :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware` handles retries for failed requests. It reschedules requests that fail due to connection errors, timeouts, or certain HTTP status codes, up to a configurable limit (:setting:`RETRY_TIMES`).
System Message: ERROR/3 (<stdin>, line 273); backlink
Unknown interpreted text role "class".System Message: ERROR/3 (<stdin>, line 273); backlink
Unknown interpreted text role "setting".Spider callback errors
When a spider callback raises an exception:
The error passes through spider middleware process_spider_exception methods
If a middleware yields items or requests, those are processed normally
The :signal:`spider_error` signal is emitted
System Message: ERROR/3 (<stdin>, line 284); backlink
Unknown interpreted text role "signal".
If the exception is :exc:`~scrapy.exceptions.CloseSpider`, the spider shuts down
System Message: ERROR/3 (<stdin>, line 285); backlink
Unknown interpreted text role "exc".
Item pipeline errors
When a pipeline's process_item raises an exception:
:exc:`~scrapy.exceptions.DropItem`: The item is dropped (normal behavior)
System Message: ERROR/3 (<stdin>, line 291); backlink
Unknown interpreted text role "exc".
Other exceptions: The :signal:`item_error` signal is emitted and the error is logged
System Message: ERROR/3 (<stdin>, line 292); backlink
Unknown interpreted text role "signal".
Spider idle and closure
The engine periodically checks whether the spider is idle. A spider is considered idle when:
- The scraper has no responses being processed
- The downloader has no active requests
- The start request iterator is exhausted
- The scheduler has no pending requests
When the spider becomes idle:
The engine emits the :signal:`spider_idle` signal
System Message: ERROR/3 (<stdin>, line 309); backlink
Unknown interpreted text role "signal".
Signal handlers can schedule new requests to keep the spider running
If a handler raises :exc:`~scrapy.exceptions.DontCloseSpider`, the spider remains open
System Message: ERROR/3 (<stdin>, line 311); backlink
Unknown interpreted text role "exc".
Otherwise, the engine initiates spider closure
The closure reason is "finished" by default, but can be customized by raising :exc:`~scrapy.exceptions.CloseSpider` with a reason argument.
System Message: ERROR/3 (<stdin>, line 314); backlink
Unknown interpreted text role "exc".Customization points
This section summarizes where you can customize the request lifecycle.
Component replacement
These settings allow replacing core components with custom implementations:
:setting:`SCHEDULER`: Custom scheduler class
System Message: ERROR/3 (<stdin>, line 328); backlink
Unknown interpreted text role "setting".
:setting:`DUPEFILTER_CLASS`: Custom duplicate filter
System Message: ERROR/3 (<stdin>, line 329); backlink
Unknown interpreted text role "setting".
:setting:`DOWNLOADER`: Custom downloader class
System Message: ERROR/3 (<stdin>, line 330); backlink
Unknown interpreted text role "setting".
Middleware chains
These settings configure middleware that processes requests and responses:
:setting:`DOWNLOADER_MIDDLEWARES`: Modify requests before download and responses after
System Message: ERROR/3 (<stdin>, line 336); backlink
Unknown interpreted text role "setting".
:setting:`SPIDER_MIDDLEWARES`: Process responses before callbacks and output after
System Message: ERROR/3 (<stdin>, line 337); backlink
Unknown interpreted text role "setting".
Pipeline chain
:setting:`ITEM_PIPELINES`: Process items after extraction
System Message: ERROR/3 (<stdin>, line 341); backlink
Unknown interpreted text role "setting".
Signal handlers
:ref:`Signals <topics-signals>` allow reacting to lifecycle events without modifying core components. Extensions typically connect to signals to implement cross-cutting functionality.
System Message: ERROR/3 (<stdin>, line 345); backlink
Unknown interpreted text role "ref".Per-request customization
Individual requests support these customization options:
- callback: Function to process the response
- errback: Function to handle download errors
- dont_filter: Skip duplicate filtering
- priority: Influence dequeue order in the scheduler
- meta: Pass data between middlewares and callbacks
For the complete request API, see :ref:`topics-request-response`.
System Message: ERROR/3 (<stdin>, line 359); backlink
Unknown interpreted text role "ref".Lifecycle sequence diagram
The following diagram illustrates the request lifecycle:
Spider Engine Scheduler Downloader Scraper | | | | | |---Request-------->| | | | | |---enqueue--------->| | | | | | | | | |<--next_request-----| | | | | | | | | |-------Request------|-----------------> | | | | | [Downloader Middlewares] | | | | [Download Handler] | | | | | | | |<------Response-----|-------------------| | | | | | | | |------Response------|------------------- |---------------->| | | | | | | | | | [Spider Middlewares] | | | | [Callback] | |<---items,requests-|--------------------|------------------- |-----------------| | | | | | | | [Items to Pipeline, Requests to Scheduler] | | | | | |
This cycle repeats until the spider is idle and no handlers prevent closure.