Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

docs: Document LoadSignal customization for ConcurrencySystem (#3976)

Jan Buchar80effc195204
diff --git a/docs/guides/scaling_crawlers.mdx b/docs/guides/scaling_crawlers.mdx
index 178073cf0..98ab04ad7 100644
--- a/docs/guides/scaling_crawlers.mdx
+++ b/docs/guides/scaling_crawlers.mdx
@@ -11,6 +11,9 @@ import CodeBlock from '@theme/CodeBlock';
import MinMaxConcurrencySource from '!!raw-loader!./scaling_crawlers_minMaxConcurrency.ts';
import MaxRequestsPerMinuteSource from '!!raw-loader!./scaling_crawlers_maxRequestsPerMinute.ts';
import ConcurrencySystemSource from '!!raw-loader!./scaling_crawlers_concurrencySystem.ts';
+import LoadSignalsOffSource from '!!raw-loader!./scaling_crawlers_loadSignalsOff.ts';
+import CustomLoadSignalSource from '!!raw-loader!./scaling_crawlers_customLoadSignal.ts';
+import WrapLoadSignalSource from '!!raw-loader!./scaling_crawlers_wrapLoadSignal.ts';
As we build our crawler, we might want to control how many requests we do to the website at a time. Crawlee provides several options to fine tune how many parallel requests should be made at any time, how many requests should be done per minute, and how should scaling work based on the available system resources.
@@ -123,39 +126,22 @@ Whether the machine counts as overloaded is decided by *load signals*. Four are
A signal we don't want watched at all can be switched **off** with `false`, which stops it being collected as well as evaluated (its entry in the reported status then simply reads as not overloaded):
-```ts
-const concurrencySystem = new ConcurrencySystem({
- loadSignals: {
- // Our storage backend reports no rate-limit statistics, so stop polling it every second.
- client: false,
- eventLoop: { maxBlockedMillis: 100 },
- },
-});
-```
+<CodeBlock language="js">
+ {LoadSignalsOffSource}
+</CodeBlock>
We can also watch resources of our own by implementing <ApiLink to="core/interface/LoadSignal">`LoadSignal`</ApiLink> — navigation timeouts or proxy health, say — and passing them in `loadSignals.custom`. The <ApiLink to="core/class/SnapshotStore">`SnapshotStore`</ApiLink> helper does the time-windowed bookkeeping for us:
-```ts
-const store = new SnapshotStore();
-
-const proxyHealth: LoadSignal = {
- name: 'proxyHealth',
- overloadedRatio: 0.3,
- async start({ maxSampleWindowMillis }) {
- // Retain exactly the window we will be sampled over, and drop anything measured before a restart.
- store.useSampleWindow(maxSampleWindowMillis);
- store.clear();
- // ...start measuring, calling store.push() per measurement
- },
- async stop() { /* ...stop measuring */ },
- getSample: (sampleDurationMillis) => store.getSample(sampleDurationMillis),
-};
-
-const concurrencySystem = new ConcurrencySystem({ loadSignals: { custom: [proxyHealth] } });
-```
+<CodeBlock language="js">
+ {CustomLoadSignalSource}
+</CodeBlock>
Each built-in is a public class too — `MemoryLoadSignal`, `EventLoopLoadSignal`, `CpuLoadSignal`, `ClientLoadSignal` — taking exactly the bag its `loadSignals` key accepts. Constructing one directly is how we *wrap* a built-in rather than reimplement it (to hold its overload verdict for a while after the resource recovers, say): switch the original off with `cpu: false`, and pass a signal that delegates to the instance we built in `custom`.
+<CodeBlock language="js">
+ {WrapLoadSignalSource}
+</CodeBlock>
+
:::info Signal names are the keys of the reported status
A signal's `name` is the key its verdict appears under in the reported status, so two signals cannot share one — a duplicate throws at construction time. That is why taking over a built-in name (`memInfo`, `eventLoopInfo`, `cpuInfo`, `clientInfo`) requires switching that built-in off.
diff --git a/docs/guides/scaling_crawlers_customLoadSignal.ts b/docs/guides/scaling_crawlers_customLoadSignal.ts
new file mode 100644
index 000000000..ee5d093f0
--- /dev/null
+++ b/docs/guides/scaling_crawlers_customLoadSignal.ts
@@ -0,0 +1,33 @@
+import type { LoadSignal } from 'crawlee';
+import { ConcurrencySystem, SnapshotStore } from 'crawlee';
+
+// The only part that is ours: anything we can poll and reduce to "is this resource in trouble?"
+async function areProxiesStruggling(): Promise<boolean> {
+ const response = await fetch('https://proxy-monitor.example.com/health');
+
+ return !response.ok;
+}
+
+const store = new SnapshotStore();
+let interval: NodeJS.Timeout;
+
+const proxyHealth: LoadSignal = {
+ name: 'proxyHealth',
+ overloadedRatio: 0.3,
+ async start({ maxSampleWindowMillis }) {
+ // Retain exactly the window we will be sampled over, and drop anything measured before a restart.
+ store.useSampleWindow(maxSampleWindowMillis);
+ store.clear();
+
+ interval = setInterval(async () => {
+ const createdAt = new Date();
+ store.push({ createdAt, isOverloaded: await areProxiesStruggling() }, createdAt);
+ }, 1_000);
+ },
+ async stop() {
+ clearInterval(interval);
+ },
+ getSample: (sampleDurationMillis) => store.getSample(sampleDurationMillis),
+};
+
+const concurrencySystem = new ConcurrencySystem({ loadSignals: { custom: [proxyHealth] } });
diff --git a/docs/guides/scaling_crawlers_loadSignalsOff.ts b/docs/guides/scaling_crawlers_loadSignalsOff.ts
new file mode 100644
index 000000000..06f43eea7
--- /dev/null
+++ b/docs/guides/scaling_crawlers_loadSignalsOff.ts
@@ -0,0 +1,9 @@
+import { ConcurrencySystem } from 'crawlee';
+
+const concurrencySystem = new ConcurrencySystem({
+ loadSignals: {
+ // Our storage backend reports no rate-limit statistics, so stop polling it every second.
+ client: false,
+ eventLoop: { maxBlockedMillis: 100 },
+ },
+});
diff --git a/docs/guides/scaling_crawlers_wrapLoadSignal.ts b/docs/guides/scaling_crawlers_wrapLoadSignal.ts
new file mode 100644
index 000000000..9d5b307c1
--- /dev/null
+++ b/docs/guides/scaling_crawlers_wrapLoadSignal.ts
@@ -0,0 +1,35 @@
+import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from 'crawlee';
+import { ConcurrencySystem, CpuLoadSignal } from 'crawlee';
+
+const cooldownMillis = 10_000;
+
+// The built-in still does all the measuring; we only reinterpret what it measured.
+const cpu = new CpuLoadSignal();
+
+const stickyCpu: LoadSignal = {
+ // Taking the built-in's name over is allowed only because we switch the built-in off below.
+ name: cpu.name,
+ overloadedRatio: cpu.overloadedRatio,
+ start: (context: LoadSignalStartContext) => cpu.start(context),
+ stop: () => cpu.stop(),
+ getSample(sampleDurationMillis?: number): LoadSnapshot[] {
+ // Keep reporting overload for a while after the CPU recovers, so that scaling up does not immediately
+ // overload it again.
+ let overloadedUntil = 0;
+
+ return cpu.getSample(sampleDurationMillis).map((snapshot) => {
+ if (snapshot.isOverloaded) {
+ overloadedUntil = +snapshot.createdAt + cooldownMillis;
+ }
+
+ return { ...snapshot, isOverloaded: +snapshot.createdAt < overloadedUntil };
+ });
+ },
+};
+
+const concurrencySystem = new ConcurrencySystem({
+ loadSignals: {
+ cpu: false,
+ custom: [stickyCpu],
+ },
+});