Caching & Politeness
A good crawler is fast for you and invisible to the sites it visits. PAM Crawl gives you both: a persistent HTTP cache that turns repeat runs into near-instant ones, and per-host politeness (connection limits, delays, robots.txt, adaptive back-off) that keeps your crawls from overwhelming anyone. This page covers both, plus user agents, sessions and proxies.
The HTTP Cache
Section titled “The HTTP Cache”Call cache() to store responses in SQLite and reuse them on the next run:
use Pam\Crawl\Crawl;use Pam\Crawl\Page;
Crawl::site('https://docs.example.com') ->depth(2)->limit(100) ->cache() // ./.cache/pam-crawl.sqlite ->each(function (Page $page): void { printf("%s %s\n", $page->fromCache ? 'cache' : 'net ', $page->url); });Fresh entries are served without touching the network. Once an entry is older than the TTL
(24 hours by default), PAM Crawl revalidates it with If-None-Match / If-Modified-Since; a
304 Not Modified answer refreshes the entry instead of downloading the page again. Only
successful GET responses (status 200 to 399) are stored.
Cache Location And TTL
Section titled “Cache Location And TTL”Crawl::url($url)->cache(); // ./.cache/pam-crawl.sqliteCrawl::url($url)->cache('/var/cache/crawl/docs.sqlite'); // your own fileCrawl::url($url)->cache(ttl: 3600); // fresh for one hourCrawl::url($url)->cache(false); // no cacheThe store keeps at most 200,000 entries. A persistent PAM worker opens each cache file once and reuses the handle for its lifetime.
Cache Modes
Section titled “Cache Modes”CacheMode mirrors Crawl4AI’s cache modes. Pass it as the third argument of cache() or with
cacheMode():
use Pam\Crawl\Cache\CacheMode;
Crawl::urls($urls)->cache()->cacheMode(CacheMode::Bypass)->all();| Mode | Reads | Writes | Use it to |
|---|---|---|---|
CacheMode::Enabled (default) |
yes | yes | Serve fresh entries, revalidate stale ones |
CacheMode::ReadOnly |
yes | no | Never touch the network; missing pages fail |
CacheMode::WriteOnly |
no | yes | Always fetch and refresh the store |
CacheMode::Bypass |
no | no | Fetch fresh this once, leave the store unchanged |
CacheMode::Disabled |
no | no | No cache at all |
On the command line use --cache [path] and --bypass-cache (-bc), or set a default with
pam crawl config set CACHE_MODE use|bypass|refresh. The HTTP API
uses one shared cache when you start it with --cache or CRAWL_CACHE.
A Custom Cache
Section titled “A Custom Cache”To store responses elsewhere (Redis, a database, object storage), implement
Pam\Crawl\Cache\Cache and pass it with withCache():
use Pam\Crawl\Cache\Cache;use Pam\Crawl\Cache\CachedEntry;use Pam\Crawl\Fetch\Response;
final class MyCache implements Cache{ public function get(string $url): ?CachedEntry { /* ... */ }
public function put(Response $response): void { /* ... */ }
/** Mark an entry fresh again after a 304 Not Modified. */ public function touch(string $url): void { /* ... */ }}
Crawl::urls($urls)->withCache(new MyCache())->all();Politeness
Section titled “Politeness”Concurrency And Delays
Section titled “Concurrency And Delays”PAM Crawl keeps up to 32 requests in flight in total and at most 6 per host by default. Lower them for small sites, and add a minimum delay between requests to the same host:
Crawl::site('https://small-blog.example.com') ->concurrency(8, perHost: 2) // 8 in flight in total, 2 per host ->delay(1.0) // at least 1 s between requests to one host ->jitter(0.5) // plus a random 0 to 0.5 s ->each(fn (Page $p) => /* ... */ null);| Method | Default | Description |
|---|---|---|
concurrency(int $total, ?int $perHost = null) |
32 |
Requests in flight in total |
perHost(int $connections) |
6 |
Requests in flight per host |
delay(float $seconds) |
0.0 |
Minimum spacing between requests to one host |
jitter(float $seconds) |
0.0 |
Random extra delay per request to one host |
timeout(float $seconds, ?float $connect = null) |
20.0 / 10.0 |
Request and connect timeouts |
retries(int $retries) |
2 |
Retries for network errors and retryable statuses |
maxBytes(int $bytes) |
10 MiB | Largest response body accepted |
robots.txt
Section titled “robots.txt”Deep crawls started with Crawl::site() respect robots.txt by default. For Crawl::url() and
Crawl::urls(), call respectRobots() (CLI: --robots):
Crawl::urls($urls) ->respectRobots() ->userAgent('AcmeBot/1.0 (+https://example.com/bot)') ->each(fn (Page $p) => /* ... */ null);respectRobots(false) turns it off, for example for your own sites.
The parser follows RFC 9309: user-agent groups, longest-match Allow / Disallow, the * and
$ wildcards, Crawl-delay and Sitemap lines. Some details worth knowing:
- Disallowed URLs are not fetched; they come back as failed pages with the error
blocked by robots.txt. - The group is chosen by the first product token of your user agent (
AcmeBotabove), falling back to the*group. Crawl-delayraises the per-host delay, capped at 30 seconds.- A robots.txt that answers with an error is treated as “allow all”, like Crawl4AI.
- Rules are cached for 24 hours inside a persistent PAM worker, so repeat crawls do not refetch them.
sitemap() (CLI: --sitemap) also seeds deep crawls from the sitemaps that robots.txt lists.
Retries And Back-Off
Section titled “Retries And Back-Off”Network errors and the statuses 408, 425, 429, 500, 502, 503 and 504 are retried up to
retries() times with exponential back-off (capped at 30 seconds). A Retry-After header wins,
up to 60 seconds.
When a host answers 429 Too Many Requests or 503 Service Unavailable, PAM Crawl also slows
that host down for the rest of the crawl: it drops to one request at a time and doubles the
per-host delay (to at least one second). Other hosts keep their normal pace.
Identity
Section titled “Identity”User Agents
Section titled “User Agents”By default, requests carry a current desktop Chrome user agent. You may set your own, or use realistic browser user agents with matching client hints:
Crawl::url($url)->userAgent('AcmeBot/1.0 (+https://example.com/bot)');Crawl::url($url)->randomUserAgent(); // one random desktop or mobile UACrawl::url($url)->randomUserAgent('mobile');Crawl::urls($urls)->randomUserAgent(rotate: 5); // rotate 5 UAs per requestHeaders And Cookies
Section titled “Headers And Cookies”Crawl::url($url) ->header('Accept-Language', 'en') ->headers(['X-Requested-With' => 'pam-crawl']) ->cookies(['lang' => 'en']);Sessions
Section titled “Sessions”session() keeps cookies across every request of a crawl. With a file, the cookie jar also
survives between runs and processes, so you can log in once and crawl as that user:
$jar = __DIR__.'/storage/cookies.txt';
Crawl::url('https://example.com/login') ->post('user=alice&password=secret') ->session($jar) ->get();
Crawl::site('https://example.com/account')->session($jar)->depth(1)->all();Proxies And Bot Walls
Section titled “Proxies And Bot Walls”Crawl::urls($urls) ->proxy('http://user:pass@proxy-1:8080', 'socks5://proxy-2:1080') // round-robin ->retryBlocked(2) // retry walls via the next proxy ->fallback(fn (string $url): ?string => $myRenderingService->html($url)) ->all();Pages blocked by a bot challenge or WAF have $page->blocked === true, with the vendor in
$page->error. retryBlocked() retries them through the next proxy (it needs several proxies),
and fallback() hands blocked or failed pages to your own fetcher as a last resort.
Monitoring A Crawl
Section titled “Monitoring A Crawl”Stats collects live statistics with constant memory. Pass it to onPage() and print it:
use Pam\Crawl\Stats;
$stats = new Stats();Crawl::urls($urls)->cache()->onPage($stats)->all();
echo $stats, "\n";// 1 pages (1 ok, 0 failed, 1 cached) in 0.0s — 2123.7 pages/s, p50 0ms, p95 0ms, 0.0 MBIt also exposes pages, ok, failed, fromCache, bytes, statuses, errors, hosts,
rate() and percentile(), and serializes to JSON.
This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai).