Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# Changelog

## 2.5.0

### Added
- **`concurrency="auto"`** finds how many requests at once the servers handle well, like TCP congestion control: it starts at 8 attempts on the wire, doubles while responses stay healthy, backs off to three quarters as soon as the servers push back (429/502/503/504, timeouts, dropped connections on more than 5 % of recent attempts) and to nine tenths when responses take twice as long as the host's normal, then stops just below the level that caused pushback and probes it again only after a few healthy windows. It grows only when the whole limit is in use, and a request waiting to retry does not hold a place. `max_concurrency` (default 500) caps it. Against a local server that rejects anything over 12 at a time, it settled at 12 with 1 % extra attempts, where `concurrency=100` needed 46 % more; against one that slows down under load, it kept 9 requests in flight instead of 100.
- The progress line shows `active 12/16` (in flight / allowed) with `concurrency="auto"`; every change is logged at `DEBUG` and a summary at `INFO`. `ProgressInfo.concurrency` holds the current limit.
- **Open file limit:** before sending, the concurrency is checked against the process's open file limit (`ulimit -n`; one file per connection, plus one pool per SOCKS proxy). A limit that is too low is raised as far as the system allows; if that is not enough, the concurrency is lowered to fit, with a warning naming the `ulimit -n` value to use. This replaces "Too many open files" failures, for example with `concurrency=1000` in a shell limited to 256. Not applicable on Windows.
- Command line: `-c auto`, `--max-concurrency`.

### Fixed
- On Python 3.9 and 3.10, the built-in `TimeoutError` (raised for example by SOCKS proxies) was not treated as retryable, because it differs from `asyncio.TimeoutError` before Python 3.11.

## 2.4.3

### Fixed
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ reqstorm does all of that for you, with one call.
|---|---|
| One result per request | Failures are recorded, never raised; every attempt is kept |
| Rate limits | Per host, in any unit (`"100/min"`), or `"auto"` from the server's 429s and headers |
| Concurrency | Overall and per host |
| Concurrency | Overall and per host, or `"auto"` to find it from the responses |
| Retries | Exponential backoff with a cap and jitter, `Retry-After`; plus end-of-run rounds |
| Reports | Failures by reason, p50/p95/p99 response times, per-host figures |
| Pagination | Next links, `Link` headers, cursors and page numbers |
Expand Down Expand Up @@ -264,6 +264,10 @@ results = reqstorm.fetch_all_sync(

The limit applies to each host (`host:port`) separately and counts retries too, so requests to different APIs never slow each other down. Requests to one host are spaced evenly.

**Don't know how much the server can take?** `concurrency="auto"` finds out, like TCP congestion control: it starts at 8 requests at once, doubles while responses stay healthy, and backs off on 429/5xx, timeouts or slowdowns. Against a server that rejects anything over 12 at a time it settles at 12 with 1 % extra attempts, where a fixed 100 needs 46 % more.

Concurrency does not depend on CPU cores: requests mostly wait for the network, and one core keeps hundreds in flight. If the concurrency needs more open connections than `ulimit -n` allows, the limit is raised automatically, or the concurrency is lowered with a warning.

**Don't know the limit?** `rate_limit="auto"` learns it from the server. A `429 Too Many Requests` pauses the host for `Retry-After` and slows it down; `X-RateLimit-Remaining` and `X-RateLimit-Reset` spread the remaining requests over the window; the rate recovers when the server stops pushing back. 429 responses are retried without using up `retries`.

**Plan before you send.** `estimate` predicts the duration and names the bottleneck, without sending anything:
Expand Down
3 changes: 2 additions & 1 deletion docs/guide/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ $ reqstorm urls.txt -o results.jsonl --report
| `--bearer TOKEN` | Send `Authorization: Bearer TOKEN`; the `REQSTORM_TOKEN` environment variable works too, and keeps the token out of your shell history |
| `--proxy URL` | Send through a proxy (`http://`, `socks5://`, `socks5h://`, `socks4://`, `socks4a://`); repeat the option to rotate through several |
| `--rate` | Per-host rate limit: `5`, `10/s`, `100/min`, `1000/h`, or `auto` |
| `-c`, `--per-host` | Concurrency in total and per host |
| `-c N`, `--per-host N` | Concurrency in total and per host |
| `-c auto`, `--max-concurrency N` | Find the concurrency from the responses, up to N (default 500); see [Rate limits and concurrency](limits.md#finding-the-concurrency-automatically-concurrencyauto) |
| `--timeout`, `--retries`, `--backoff` | Per attempt timeout, retries and the first wait between them |
| `--max-backoff`, `--no-jitter` | Longest wait between retries (default 30 s); wait exactly instead of a random part of it |
| `--retry-rounds`, `--retry-round-delay` | Send failed requests again at the end (needs `-o`) |
Expand Down
40 changes: 40 additions & 0 deletions docs/guide/limits.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,46 @@ Pauses are capped at 5 minutes. `concurrency` and `concurrency_per_host` still a

`concurrency` caps how many requests are in flight at once (default 100). `concurrency_per_host` caps it per host (default: no per-host cap). Requests are spread over a fixed number of workers that read your URLs lazily, so a generator of millions of URLs is fine.

Concurrency is not tied to the number of CPU cores. reqstorm runs every request on one thread with asyncio, and a request spends almost all its time waiting for the network, so one core easily keeps hundreds of requests in flight. What limits a batch is the server, and on your side the number of open connections, both covered below.

### Finding the concurrency automatically: `concurrency="auto"`

When you don't know how much a server can take, let reqstorm find out:

```python
results = reqstorm.fetch_all_sync(urls, concurrency="auto", retries=3)
```

It works like TCP congestion control:

- It starts with 8 attempts on the wire and **doubles** that after each healthy window of time (about three times the response time, at least a quarter of a second).
- It **backs off** to three quarters as soon as the servers push back: 429, 502, 503 or 504 responses, timeouts or dropped connections on more than 5 % of recent attempts. It **eases off** to nine tenths when responses take more than twice as long as that host's normal.
- After the first backoff it grows by about 10 % per window, stops just below the level where the servers pushed back, and tries that level again only after a few healthy windows.
- It grows only when the whole limit is in use, and a request waiting to retry does not hold a place, so the limit is what the servers actually see.

`max_concurrency` (default 500) is the highest it may go. With `progress=True` the line shows the current limit as `active 12/16` (in flight / allowed), and the log reports every change at `DEBUG` and a summary at `INFO`.

How it compares with the default `concurrency=100`, measured against a local server that rejects with a 503 anything over its capacity (600 requests, `retries=3`):

| Server capacity | `concurrency=100` | `concurrency="auto"` |
|---|---|---|
| 3 at a time | 494 of 600 succeed, 105 % extra attempts | 600 succeed, 2 % extra; settles at 3 |
| 12 at a time | 600 succeed, 46 % extra | 600 succeed, 1 % extra, faster; settles at 12 |
| 40 at a time | 600 succeed, 20 % extra | 600 succeed, 6 % extra; settles at 39 |
| 100 at a time | 600 succeed, 0.2 s | 600 succeed, 1.0 s (it starts at 8 and needs time to grow) |
| never rejects, slows down under load | 100 requests at once | at most 9 at once |

So `"auto"` is gentle with servers that are already busy and close to ideal for unknown capacity. For a short batch against a server that easily handles your fixed number, a fixed number is faster, because `"auto"` spends the first second or so finding out. It treats the batch as a whole; to limit one busy host among several, combine it with `concurrency_per_host`.

### Open file limit

Every connection is an open file, and the operating system limits how many a process may have (`ulimit -n`; some macOS shells start at 256). Asking for more connections than that used to fail with "Too many open files". Now, before sending anything, reqstorm compares the concurrency with the limit:

- If the limit is too low, it is raised as far as the system allows, and an `INFO` message says so.
- If it cannot be raised far enough, the concurrency is lowered to fit, with a `WARNING` that names the `ulimit -n` value to use for the full concurrency.

64 file descriptors are kept free for log and output files, and each SOCKS proxy (which has its own connection pool) counts separately. Windows has no such limit, so nothing changes there.

## Estimating a batch

`reqstorm.estimate` tells you how long a batch should take and which setting is the bottleneck, without sending anything:
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ reqstorm: 3500/7000 (50%) ok 3493 failed 7 active 12 retries 41 1.7 req/s
|---|---|
| `3500/7000 (50%)` | Requests with a final result, of all requests |
| `ok`, `failed` | How those ended |
| `active` | Requests being sent, waiting for a response, or waiting to retry right now |
| `active` | Requests being sent, waiting for a response, or waiting to retry right now. With `concurrency="auto"`, shown as `active 12/16`: in flight / currently allowed |
| `retries` | Retries so far, of all requests |
| `1.7 req/s` | Finished requests per second over the last minute |
| `round 1/2` | With `retry_rounds`: the round being sent |
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ print(results.summary())

---

`"10/s"`, `"100/min"`, `"1000/h"` per host, or `"auto"` to follow the server's 429s and rate-limit headers. Know how long a batch takes before you start it.
`"10/s"`, `"100/min"`, `"1000/h"` per host, or `"auto"` to follow the server's 429s and rate-limit headers. `concurrency="auto"` finds how many requests at once a server handles well. Know how long a batch takes before you start it.

[:octicons-arrow-right-24: Rate limits](guide/limits.md)

Expand Down
2 changes: 1 addition & 1 deletion reqstorm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def main():
from ._sync import fetch_all_sync, fetch_to_db_sync, fetch_to_file_sync, stream_sync
from ._template import from_template, read_csv, read_sql

__version__ = "2.4.3"
__version__ = "2.5.0"

# A library must not print log messages the application did not ask for: without this,
# Python's last-resort handler would print reqstorm's warnings and errors to stderr in
Expand Down
20 changes: 17 additions & 3 deletions reqstorm/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@ def _parser() -> argparse.ArgumentParser:
add = pace.add_argument
add("--rate", metavar="LIMIT",
help="per-host rate limit: 5, 10/s, 100/min, 1000/h, or auto (default: none)")
add("-c", "--concurrency", type=int, default=100, metavar="N",
help="requests in flight at once (default: 100)")
add("-c", "--concurrency", type=_concurrency, default=100, metavar="N",
help="requests in flight at once, or auto to find the number from the responses (default: 100)")
add("--max-concurrency", type=int, default=500, metavar="N",
help="with -c auto: the highest number it may reach (default: 500)")
add("--per-host", type=int, default=0, metavar="N",
help="requests in flight per host (default: no limit)")
add("--timeout", type=float, default=30.0, metavar="SECONDS",
Expand Down Expand Up @@ -157,6 +159,15 @@ def _parser() -> argparse.ArgumentParser:
# fmt: on


def _concurrency(text: str) -> Union[int, str]:
if text == "auto":
return text
try:
return int(text)
except ValueError:
raise argparse.ArgumentTypeError(f"invalid concurrency {text!r}; use a number or auto") from None


def _paginator(text: Optional[str], max_pages: int) -> Optional[Paginator]:
if not text:
return None
Expand Down Expand Up @@ -291,7 +302,9 @@ def _batch(args: argparse.Namespace, cache: Optional[Cache]) -> int:
if total is None:
raise ValueError("--estimate needs an input file, not standard input")
print(estimate(total, rate_limit=None if rate == "auto" else rate, hosts=_hosts(args),
concurrency=args.concurrency, concurrency_per_host=args.per_host,
# with -c auto, the best case: the highest concurrency it may reach
concurrency=args.max_concurrency if args.concurrency == "auto" else args.concurrency,
concurrency_per_host=args.per_host,
latency=args.latency)) # fmt: skip
return 0

Expand All @@ -308,6 +321,7 @@ def _batch(args: argparse.Namespace, cache: Optional[Cache]) -> int:
json=json.loads(args.json) if args.json else None,
data=args.data,
concurrency=args.concurrency,
max_concurrency=args.max_concurrency,
concurrency_per_host=args.per_host,
timeout=args.timeout,
retries=args.retries,
Expand Down
Loading
Loading