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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## [0.84.0] - 2026-11-29

ScrapeBadger replaced rate-limit tiers and per-minute limits with one number per account: **max concurrency**, how many requests the account may run at the same time across all of its API keys. There is no per-minute limit any more. (SCR-736)

### Breaking
- **`RateLimitError` describes the concurrency limit.** The class name and import are unchanged, and every 429 still raises it. New attributes: `max_concurrency` and `concurrent_requests` (ints from the 429 body, `None` when the body has none; `max_concurrency` is 1 for an agent trial key's `trial_concurrency` 429). `retry_after` is now always a number of seconds from the `Retry-After` header and defaults to 1 (was 60) when the header is missing or malformed. Removed: `limit`, `remaining`, `reset_at` and `tier`; code that reads them gets `AttributeError`. The keyword arguments of the constructor changed the same way.
- **Pagination no longer throttles.** The `*_all` iterators read `X-RateLimit-*` headers and slowed down near the limit; the API no longer sends those headers, so the throttling and its "Rate limit: ... throttling pagination" warning are gone. Pages are still fetched one at a time, with the same cursor, `max_pages` and `max_items` handling.
- **`account.get_account_info()`** (raw dict) no longer has `tier` or `rate_limit_per_minute`. It has `max_concurrency` (the account's limit) and `concurrent_requests` (its requests running right now, not counting this one).

### Changed
- The API's 429 for the limit is `{"error": "concurrency_limit_exceeded", "detail": ..., "max_concurrency": N, "concurrent_requests": N}` with `Retry-After: 1`. Successful responses carry `X-Concurrency-Limit` and `X-Concurrency-Remaining` instead of `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `X-Api-Tier`.
- **A concurrency 429 is retried automatically.** `concurrency_limit_exceeded` and `trial_concurrency` are refused before the call runs or bills, so the SDK waits for a slot (`Retry-After`, then 2, 4, 8, at most 10 s) and retries, up to `max_retries`. Other 429s (e.g. the zero-credit throttle) still raise straight away; `retry_on_status` is unchanged.
- README: "Rate Limit Aware Pagination" is replaced by a "Concurrency" section (checking the limit, staying under it with a semaphore, handling the 429).

## [0.83.1] - 2026-11-26

### Changed
Expand Down
70 changes: 58 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ The official Python SDK for [ScrapeBadger](https://scrapebadger.com) - async web

- **Async-first** - Built with `asyncio` for high-performance concurrent scraping
- **Type-safe** - Full type hints and Pydantic models for all responses
- **Automatic pagination** - Iterator methods with smart rate limit handling
- **Automatic pagination** - Iterator methods that follow cursors for you
- **Resilient retries** - Exponential backoff on transient errors
- **Async requests and webhooks** - Submit any slow call, poll or `wait` for it, or take a signed webhook; idempotency keys make re-submits safe
- **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams
Expand Down Expand Up @@ -243,8 +243,8 @@ async with ScrapeBadger(api_key="your-key") as client:
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
print(f"Limit: {e.limit}, Remaining: {e.remaining}")
print(f"Too many concurrent requests. Retry after {e.retry_after} seconds")
print(f"Running: {e.concurrent_requests} of {e.max_concurrency}")
except InsufficientCreditsError:
print("Out of credits! Purchase more at scrapebadger.com")
except NotFoundError:
Expand Down Expand Up @@ -311,20 +311,66 @@ import logging
logging.basicConfig(level=logging.WARNING)
```

### Rate Limit Aware Pagination
### Concurrency

When using `*_all` pagination methods, the SDK reads `X-RateLimit-Remaining` and
`X-RateLimit-Reset` headers from each response. When remaining requests drop below
20% of your tier's limit, pagination automatically slows down to spread requests
across the remaining window — preventing 429 errors. A warning is logged when
throttling activates:
Every ScrapeBadger account has a **max concurrency**: how many requests it can
have running at the same time, across all of its API keys. There is no
per-minute limit; send as many requests as you like, as long as no more than
`max_concurrency` are in flight at once. Your plan sets the number, see
[pricing](https://scrapebadger.com/pricing).

Check it with the account endpoint (free):

```python
info = await client.account.get_account_info()
print(info["max_concurrency"]) # requests the account may run at once
print(info["concurrent_requests"]) # running right now, not counting this call
```
⚠ Rate limit: 25/300 remaining (resets in 42s), throttling pagination to ~0.6 req/s

To stay under it, cap your own in-flight calls, for example with a semaphore:

```python
import asyncio

from scrapebadger import ScrapeBadger

async with ScrapeBadger(api_key="your-key") as client:
info = await client.account.get_account_info()
slots = asyncio.Semaphore(info["max_concurrency"])

async def fetch(username: str):
async with slots:
return await client.twitter.users.get_by_username(username)

users = await asyncio.gather(*(fetch(u) for u in ["elonmusk", "nasa", "github"]))
```

This works transparently with all tier levels (Free: 60/min, Basic: 300/min,
Pro: 1000/min, Enterprise: 5000/min).
The limit counts every request of the account, whichever key, process or
machine sends it, so split the number between workers that share an account.
The `*_all` iterators fetch one page at a time and hold one slot. An async
request (`client.requests.submit`) holds its slot until the call finishes;
polling it does not take one.

A request over the limit is refused before it runs, so it is not charged. The
API answers `429` with `Retry-After: 1`:

```json
{
"error": "concurrency_limit_exceeded",
"detail": "Too many concurrent requests: ...",
"max_concurrency": 5,
"concurrent_requests": 5
}
```

The SDK retries this 429 by itself: it waits `Retry-After`, then 2, 4, 8 and at
most 10 seconds between attempts, up to `max_retries` (10 by default). Only when
the retries run out does it raise `RateLimitError`, with `max_concurrency`,
`concurrent_requests` and `retry_after` (seconds). Capping your own in-flight
calls as above avoids the wait altogether.

Successful responses carry `X-Concurrency-Limit` (your max concurrency) and
`X-Concurrency-Remaining` (free slots once this request started).

## Development

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "scrapebadger"
version = "0.83.1"
version = "0.84.0"
description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more"
readme = "README.md"
license = { text = "MIT" }
Expand Down
2 changes: 1 addition & 1 deletion src/scrapebadger/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,7 @@ async def main():
ZestimateHistoryPoint as ZillowZestimateHistoryPoint,
)

__version__ = "0.83.1"
__version__ = "0.84.0"

__all__ = [
# TikTok core models
Expand Down
45 changes: 35 additions & 10 deletions src/scrapebadger/_internal/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,11 @@

T = TypeVar("T")

# 429 bodies that mean "every concurrency slot is in use": retried by default.
_CONCURRENCY_ERRORS = frozenset({"concurrency_limit_exceeded", "trial_concurrency"})

# User agent for SDK requests
SDK_VERSION = "0.83.1"
SDK_VERSION = "0.84.0"
USER_AGENT = f"scrapebadger-python/{SDK_VERSION}"


Expand All @@ -79,6 +82,13 @@ def _retry_after_seconds(response: httpx.Response, default: int) -> int:
return default


def _int_or_none(value: Any) -> int | None:
"""An integer field of an error body, or None when it is missing or not an integer."""
if isinstance(value, bool) or not isinstance(value, int):
return None
return value


class BaseClient:
"""Base HTTP client with retry logic and error handling.

Expand Down Expand Up @@ -209,15 +219,16 @@ def _handle_error_response(
raise ValidationError(message, status_code, data)

if status_code == 429:
max_concurrency = _int_or_none(data.get("max_concurrency"))
if max_concurrency is None and data.get("error") == "trial_concurrency":
max_concurrency = 1 # agent trial keys run one call at a time
raise RateLimitError(
message,
status_code,
data,
limit=data.get("limit"),
remaining=data.get("remaining"),
reset_at=data.get("reset_at"),
retry_after=_retry_after_seconds(response, default=60),
tier=data.get("tier"),
max_concurrency=max_concurrency,
concurrent_requests=_int_or_none(data.get("concurrent_requests")),
retry_after=_retry_after_seconds(response, default=1),
)

if status_code >= 500:
Expand Down Expand Up @@ -316,17 +327,31 @@ async def _send(
replayed = (
response.headers.get("Idempotent-Replayed", "").strip().lower() == "true"
)
# A concurrency 429 is refused before anything runs or bills,
# so it is always safe to retry once a slot frees up.
concurrency_full = (
response.status_code == 429 and data.get("error") in _CONCURRENCY_ERRORS
)
# Don't retry client errors (except specific status codes)
if (
not retry_status
or replayed
or response.status_code not in self._config.retry_on_status
or (
response.status_code not in self._config.retry_on_status
and not concurrency_full
)
):
self._handle_error_response(response, data)

# Retry on configured status codes
if attempt < self._config.max_retries:
delay = max(2**attempt, _retry_after_seconds(response, default=0))
if concurrency_full:
# Slots free as requests finish: poll briskly, not 2**n.
delay = max(
_retry_after_seconds(response, default=1), min(2**attempt, 10)
)
else:
delay = max(2**attempt, _retry_after_seconds(response, default=0))
logger.warning(
"⚠ %s %s — retrying in %ss (attempt %d/%d)",
response.status_code,
Expand Down Expand Up @@ -495,8 +520,8 @@ async def get_with_headers(

Returns:
A (data, headers) tuple. ``data`` is the parsed JSON response;
``headers`` is a plain dict of response header name → value strings
(e.g. ``{"X-RateLimit-Remaining": "250", ...}``).
``headers`` is a plain dict of response header name → value strings,
with lowercase names (e.g. ``{"x-concurrency-remaining": "4", ...}``).
"""
return await self._request_with_retry("GET", path, params=params)

Expand Down
46 changes: 28 additions & 18 deletions src/scrapebadger/_internal/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
try:
tweets = await client.twitter.tweets.get_by_id("123456")
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after}s")
print(f"Too many concurrent requests. Retry after: {e.retry_after}s")
except AuthenticationError:
print("Invalid API key")
except ScrapeBadgerError as e:
Expand Down Expand Up @@ -128,43 +128,53 @@ def __init__(


class RateLimitError(ScrapeBadgerError):
"""Raised when rate limit is exceeded.
"""Raised for a 429: usually the account is already at its max concurrency.

Every account has a max concurrency: how many requests it may have in
flight at the same time, across all of its API keys. A request over that
number is refused with ``429`` (``error: "concurrency_limit_exceeded"``)
before it runs, so it is not charged; retry it as soon as one of your
running requests finishes. Agent trial keys run one call at a time and
answer ``429`` (``error: "trial_concurrency"``) the same way. Other 429s
(e.g. ``error: "rate_limited"`` from an endpoint's own cap) raise this
too; ``response_data["error"]`` tells them apart.

The SDK does not retry a 429 by itself. Keep the number of requests you
send at once under ``max_concurrency`` (see the README's "Concurrency"
section), or wait ``retry_after`` seconds and try again.

Attributes:
limit: Maximum requests allowed per minute.
remaining: Requests remaining in current window.
reset_at: Unix timestamp when the rate limit resets.
retry_after: Seconds until the rate limit resets.
tier: The user's current rate limit tier.
max_concurrency: How many requests the account may run at once, or
None when the response did not say (1 for an agent trial key).
concurrent_requests: How many of its requests were running when this
one was refused, or None when the response did not say.
retry_after: Seconds to wait before retrying, from the ``Retry-After``
header (1 when the header is missing or malformed).

Example:
```python
try:
tweets = await client.twitter.tweets.search("python")
except RateLimitError as e:
print(f"Rate limited. Wait {e.retry_after} seconds.")
print(f"{e.concurrent_requests}/{e.max_concurrency} requests running")
await asyncio.sleep(e.retry_after)
```
"""

def __init__(
self,
message: str = "Rate limit exceeded",
message: str = "Too many concurrent requests",
status_code: int = 429,
response_data: dict[str, Any] | None = None,
*,
limit: int | None = None,
remaining: int | None = None,
reset_at: int | None = None,
retry_after: int | None = None,
tier: str | None = None,
max_concurrency: int | None = None,
concurrent_requests: int | None = None,
retry_after: float = 1,
) -> None:
super().__init__(message, status_code, response_data)
self.limit = limit
self.remaining = remaining
self.reset_at = reset_at
self.max_concurrency = max_concurrency
self.concurrent_requests = concurrent_requests
self.retry_after = retry_after
self.tier = tier


class InsufficientCreditsError(ScrapeBadgerError):
Expand Down
Loading
Loading