# Pace your requests: add a delay and time what it costs | Spider

Add a pause between requests to the course script, fetch three practice pages with no pause and with two seconds, and compare the two wall times.

Canonical: https://spider.cloud/learn/course/pace-your-requests/

To scrape a website politely, ask for one page at a time, wait a fixed pause after each answer before you send the next request, and decide before you start how many pages you will fetch. The gap between two of your requests is then the time the last fetch took plus your pause, and the job ends when your list does.

This lesson leaves you with `pace.py`, a script that fetches a short list of pages with a pause of your choosing between them, and with two wall times you measured yourself: three practice pages fetched with no pause, and the same three with a two second pause.

This clip draws both recorded runs.

What a pause costs a run. 1 min 11 s, no sound. The words are on screen, and the captions button shows them at your own text size.

Read the transcript

What a pause costs a run. Three pages, timed with no pause and with 2 seconds.

With a pause of 0, each request still waits for the answer before it. A time line of one recorded run, with a pause of 0 s: requests 1 to 3 start at 0 s, 2 s and 3.9 s, each after the answer before it, and the run ends at 6.3 s. 3: requests, one at a time. 0 s: of pauses. 6.3 s: for the whole run.

With a pause of 2 s, the wait starts once the answer has arrived. A time line of one recorded run, with a pause of 2 s: requests 1 to 3 start at 0 s, 4.3 s and 7.8 s, each after the answer before it, and the run ends at 9.3 s. 3: requests, one at a time. 4 s: asked for, in 2 pauses. 9.3 s: for the whole run.

A gap is the fetch time plus the pause. Only the pause is yours to set. 4.3 s: 2.3 s fetch, 2 s pause. 3.5 s: 1.5 s fetch, 2 s pause.

The pauses asked for 4 s, but the run ended only 3 s later. 6.3 s: pause of 0 s. 9.3 s: pause of 2 s. 3 s: later, for 4 s of pauses.

A list of 100 pages makes 100 fetches and 99 pauses. Estimate before you start. 100: fetches. 99: pauses of 2 s. 6 to 7 min: at 1.5 to 2.3 s a fetch.

Read the full lesson. The page is at spider.cloud/learn/course/pace-your-requests.

## Where the script stood

Lesson 3 ended with [read_robots.py](/learn/course/read-robots-txt/). Its second run got a 404 for robots.txt on quotes.toscrape.com, so robots.txt sets no limit on the listing pages this lesson asks for. The site's terms of use are a separate check, and neither tells you how often to ask.

`pace.py` goes back to the request from [lesson 2](/learn/course/write-the-script/). Two parts of lesson 2 carry over: the key check, which exits 1 when `SPIDER_API_KEY` is empty, and the status check, which turns any page status other than 200 into exit 1. The word check does not, so there is no exit 2 here. The new parts are the `DELAY` argument, the loop, the `time.sleep(delay)` before every request after the first, the clock and the `total:` line.

The list of addresses is the page limit. Three addresses means three requests, and nothing in the script follows a link you did not list.

## The script

The script reads your API key from the `SPIDER_API_KEY` environment variable and uses only the standard library. Save it as `pace.py`. Both runs below, on 2026-11-20, used this file unchanged.

```python
"""Fetch a few pages one after another through the Spider API, waiting DELAY seconds between them.

    python3 pace.py DELAY URL [URL ...]

Prints when each request started, counted from the first, and the status it got.
Exit 0: every page answered 200.
Exit 1: the key is missing, or a page answered something else.
"""
import json
import os
import sys
import time
import urllib.request

API = "https://api.spider.cloud/scrape"


def fetch(url: str, key: str) -> int:
    body = json.dumps({"url": url, "request": "http", "return_format": "markdown"}).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=60) as resp:
        page = json.load(resp)
    if isinstance(page, list):
        page = page[0]
    return page.get("status") or 0


def main() -> int:
    if len(sys.argv) < 3:
        print("usage: python3 pace.py DELAY URL [URL ...]")
        return 1
    delay, urls = float(sys.argv[1]), sys.argv[2:]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    start = time.monotonic()
    worst = 200
    for i, url in enumerate(urls):
        if i > 0:
            time.sleep(delay)
        at = time.monotonic() - start
        status = fetch(url, key)
        print(f"{at:5.1f}s  {status}  {url}")
        if status != 200:
            worst = status
    print(f"total: {time.monotonic() - start:.1f}s for {len(urls)} pages, delay {delay:g}s")
    return 0 if worst == 200 else 1


if __name__ == "__main__":
    sys.exit(main())
```

Because `time.sleep` sits at the top of the loop, the pause runs after the previous answer has arrived, never while a request is open. For the clock, Python's documentation says of `time.monotonic()` that its starting point has no fixed meaning, so only the "difference between the results of two calls is valid." So the script takes one reading at the start and prints every other one as a difference from it. The pause is a float, so `0.5` works as well as `2`.

The file above is the one the runs below used, and its body has no `user_agent`. Before you run it yourself, give it the name from lesson 2. Replace the `body = ...` line in `fetch()` with this one, using your own bot name, page and address in place of the example ones:

```python
    body = json.dumps({
        "url": url,
        "request": "http",
        "return_format": "markdown",
        "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)",
    }).encode()
```

Nothing else changes, so your output still compares with the runs below.

## Run it twice

Both runs were made on 2026-11-20 with Python 3.14.7, over the first three listing pages of the quotes practice site, and both exited 0. The first passes a pause of 0, which is only for comparison on a site built for practice. On any other site, follow its stated request rules, and use the pause from the request rate page when it has none.

```bash
python3 pace.py 0 https://quotes.toscrape.com/page/1/ https://quotes.toscrape.com/page/2/ https://quotes.toscrape.com/page/3/
```

```text
  0.0s  200  https://quotes.toscrape.com/page/1/
  2.0s  200  https://quotes.toscrape.com/page/2/
  3.9s  200  https://quotes.toscrape.com/page/3/
total: 6.3s for 3 pages, delay 0s
```

The second changes one value, the pause, to 2 seconds.

```bash
python3 pace.py 2 https://quotes.toscrape.com/page/1/ https://quotes.toscrape.com/page/2/ https://quotes.toscrape.com/page/3/
```

```text
  0.0s  200  https://quotes.toscrape.com/page/1/
  4.3s  200  https://quotes.toscrape.com/page/2/
  7.8s  200  https://quotes.toscrape.com/page/3/
total: 9.3s for 3 pages, delay 2s
```

Here are the start times from both runs next to each other.

| Request | Pause 0 | Pause 2 |
| ------- | ------- | ------- |
| page 1  | 0.0s    | 0.0s    |
| page 2  | 2.0s    | 4.3s    |
| page 3  | 3.9s    | 7.8s    |
| total   | 6.3s    | 9.3s    |

## Read the gaps

First, what the clock measures. Each stamp is taken just before `fetch()`, so the time between two stamps covers the API call, the answer, `json.load`, the print and the pause. This lesson calls all of that but the pause the fetch time. It is what your script saw, not how long the practice site took to answer.

Start with the run that had no pause. Its requests were still about two seconds apart, because the script waits for each answer before it sends the next request. With a pause of 0 the gap is only the fetch time, and a faster fetch brings the requests that much closer together.

Now the second run. The gap from page 1 to page 2 was 4.3 seconds: 2 seconds of pause, so roughly 2.3 seconds of fetch time. The gap from page 2 to page 3 was 3.5 seconds, roughly 1.5 of fetch time and 2 of pause. These are estimates, because you subtract the pause you asked for. Of the two parts of a gap, only the pause is yours to set.

The totals hold one surprise. The second run asked for two pauses of 2 seconds, 4 seconds in all, but finished only 3 seconds later than the first: 9.3 against 6.3. The script does not time its sleeps on their own, so the split is an estimate. If each sleep ran for exactly the 2 seconds asked, the three fetches took about 5.3 seconds in all, against 6.3 in the first run. Fetch time moves from one run to the next. The pause does not, which is why it is the number to choose with care. Python's documentation adds that a sleep can run a little long, since "The suspension time may be longer than requested by an arbitrary amount", so treat your pause as the shortest gap the site will see, not an exact one.

The same sum tells you how long a bigger job takes before you start it. A list of N pages makes N fetches and one pause fewer, since nothing waits before the first request. So the estimate is N times the fetch time, plus N minus 1 times the pause. With the second run's estimated fetch times of 1.5 to 2.3 seconds and a 2 second pause, a list of 100 pages would take roughly six to seven minutes. If that is too slow, use fewer pages, not a shorter pause.

How long a pause to choose for a site that publishes no number is the subject of [the request rate page](/learn/request-rate/). The short version for this course: one request open at a time, and a pause of at least a second, on any site you have not been told otherwise about. That rule holds for every [web scraping](/web-scraping/) job in the course, whatever tool sends the requests.

## When the site says slow down

A site that thinks you are too fast can answer 429. RFC 6585 defines it this way: "The 429 status code indicates that the user has sent too many … requests in a given amount of time". It adds that the response "MAY include a Retry-After header indicating how long" to wait.

With `pace.py` that can show up in two ways, and they look different.

The first is a page status. The site answered 429, and the script prints it in that page's line, notes it for exit 1 and carries on with your list. Ctrl-C is too late to count on, since with a short pause the next request may already be on its way. Make your copy stop by itself. Put these lines in the loop, right after the `print` of the status line:

```python
        if status == 429:
            print("the site answered 429, stopping")
            return 1
```

The second is a 429 from the API itself, on the call the script makes. Then `urlopen()` raises before `fetch()` returns, so no status line prints, and Python stops the script with a traceback naming HTTP Error 429. To see how long to wait, replace the `status = fetch(url, key)` line in your copy with these, and add `import urllib.error` at the top:

```python
        try:
            status = fetch(url, key)
        except urllib.error.HTTPError as err:
            if err.code != 429:
                raise
            print("the API answered 429, Retry-After:", err.headers.get("Retry-After"))
            return 1
```

When a Retry-After value comes back, wait at least that long before you run the script again, and then run it with a longer pause or a shorter list. [The Retry-After page](/learn/retry-after/) covers the two forms the value can take. Neither change was in the runs above.

In both cases, do not rerun straight away to see whether it was a one-off.

## Try it yourself

Make the `user_agent` change above, then run the second command again with `1` in place of `2`, and `/page/4/` to `/page/6/` in place of pages 1 to 3. Subtract each start time from the next to get the gaps, and take 1 second off each gap to estimate the fetch time your script saw. The script prints times to a tenth of a second, so a gap can show as exactly 1.0. You are done when every gap is 1.0 seconds or more and you have a fetch-time estimate written next to each one.

## Do this, avoid this

### Do this

- Put the pause before every request after the first, so no two requests to one host are open at once.
- Name the pages on the command line, so the number of requests is fixed before the run starts.
- Keep the total line from each run beside the pause it used, and compare them when you change the pause.
- Check the site's terms of use for a stated rate, and use a longer pause when they ask for one.

### Avoid this

- Running with a pause of 0 on any site other than a practice site, even one whose answer time you have measured. A fast answer does not make a fast rate welcome.
- Reading the pause as the whole gap. The fetch time comes first.
- Letting the loop carry on through the list after a 429.
- Starting several copies of the script against one host, which undoes the pause.

## Next: the second fetch

To compare two pauses, this lesson asked the practice site for the same three pages twice, ten seconds apart. The next lesson asks what that second pass cost the site: once you have fetched a page, do you need to request it again, or can you work from a copy you saved?

## Sources

1. [Python documentation, time module, time.sleep and time.monotonic](https://docs.python.org/3/library/time.html) Read November 20, 2026
2. [RFC 6585, Additional HTTP Status Codes, IETF, April 2012](https://www.rfc-editor.org/rfc/rfc6585.html) Read November 20, 2026
