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.

fix(core): avoid re-submitting already-enqueued requests in addRequestsBatched (#3843)

nikitachapovskii-dev704c26980650
diff --git a/packages/core/src/storages/request_dedup_cache.ts b/packages/core/src/storages/request_dedup_cache.ts
new file mode 100644
index 000000000..632e56a0c
--- /dev/null
+++ b/packages/core/src/storages/request_dedup_cache.ts
@@ -0,0 +1,51 @@
+/**
+ * A fixed-size, direct-mapped cache for `uniqueKey`-based request deduplication.
+ *
+ * `RequestProvider.requestCache` only remembers the first batch of requests, so repeated
+ * `addRequestsBatched()` calls with overlapping URLs re-submit already-enqueued requests
+ * (https://github.com/apify/crawlee/issues/3120). This is a separate, cheaper cache we can populate on
+ * every batch: a fixed number of slots indexed by a hash of the request's cache key, storing the
+ * server-assigned `requestId`. Memory is capped by the slot count regardless of the working set size;
+ * a hash collision just overwrites a slot, causing an occasional cache miss (a harmless re-submission)
+ * but never a false hit — so a genuinely new request is never dropped.
+ *
+ * @internal
+ */
+export class RequestDeduplicationCache {
+ private keys: (string | undefined)[];
+ private ids: (string | undefined)[];
+
+ // The slot count is the same for every queue, so it's a fixed default rather than a per-consumer option.
+ constructor(private readonly size = 1_000_000) {
+ this.keys = new Array<string | undefined>(size);
+ this.ids = new Array<string | undefined>(size);
+ }
+
+ get(cacheKey: string): string | null {
+ const index = this.indexOf(cacheKey);
+ return this.keys[index] === cacheKey ? this.ids[index]! : null;
+ }
+
+ add(cacheKey: string, requestId: string): void {
+ const index = this.indexOf(cacheKey);
+ this.keys[index] = cacheKey;
+ this.ids[index] = requestId;
+ }
+
+ clear(): void {
+ this.keys = new Array<string | undefined>(this.size);
+ this.ids = new Array<string | undefined>(this.size);
+ }
+
+ // A cheap FNV-1a hash of the cache key — avoids pulling in a dedicated hashing dependency.
+ private indexOf(cacheKey: string): number {
+ /* eslint-disable no-bitwise */
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < cacheKey.length; i++) {
+ hash ^= cacheKey.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return (hash >>> 0) % this.size;
+ /* eslint-enable no-bitwise */
+ }
+}
diff --git a/packages/core/src/storages/request_provider.ts b/packages/core/src/storages/request_provider.ts
index be9a3f441..47554a3d4 100644
--- a/packages/core/src/storages/request_provider.ts
+++ b/packages/core/src/storages/request_provider.ts
@@ -32,6 +32,7 @@ import type { InternalSource, RequestOptions, Source } from '../request';
import { Request } from '../request';
import type { Constructor } from '../typedefs';
import { checkStorageAccess } from './access_checking';
+import { RequestDeduplicationCache } from './request_dedup_cache';
import type { IStorage, StorageManagerOptions } from './storage_manager';
import { StorageManager } from './storage_manager';
import { getRequestId, purgeDefaultStorages, QUERY_HEAD_MIN_LENGTH } from './utils';
@@ -128,6 +129,13 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
protected queueHeadIds = new ListDictionary<string>();
protected requestCache: LruCache<RequestLruItem>;
+ /**
+ * Remembers the `requestId` of every request already submitted to the client — including background
+ * batches that `requestCache` skips — so overlapping URL sets aren't re-submitted.
+ * See {@link RequestDeduplicationCache} for why this is a separate, cheaper cache.
+ */
+ protected requestSeenCache: RequestDeduplicationCache;
+
protected recentlyHandledRequestsCache: LruCache<boolean>;
protected queuePausedForMigration = false;
@@ -152,6 +160,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
this.proxyConfiguration = options.proxyConfiguration;
this.requestCache = new LruCache({ maxLength: options.requestCacheMaxSize });
+ this.requestSeenCache = new RequestDeduplicationCache();
this.recentlyHandledRequestsCache = new LruCache({ maxLength: options.recentlyHandledRequestsMaxSize });
this.log = log.child({ prefix: `${options.logPrefix}(${this.id}, ${this.name ?? 'no-name'})` });
@@ -253,6 +262,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
const { requestId, wasAlreadyPresent } = queueOperationInfo;
this._cacheRequest(cacheKey, queueOperationInfo);
+ this.requestSeenCache.add(cacheKey, requestId);
if (!wasAlreadyPresent && !this.recentlyHandledRequestsCache.get(requestId)) {
this.assumedTotalCount++;
@@ -338,17 +348,18 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
for (const request of requests) {
const cacheKey = getCachedRequestId(request.uniqueKey);
+ // Prefer the full `requestCache` record; fall back to the dedup cache for background batches it skips.
const cachedInfo = this.requestCache.get(cacheKey);
+ const knownRequestId = cachedInfo?.id ?? this.requestSeenCache.get(cacheKey);
- if (cachedInfo) {
- request.id = cachedInfo.id;
+ if (knownRequestId) {
+ request.id = knownRequestId;
results.processedRequests.push({
wasAlreadyPresent: true,
- // We may assume that if request is in local cache then also the information if the
- // request was already handled is there because just one client should be using one queue.
- wasAlreadyHandled: cachedInfo.isHandled,
- requestId: cachedInfo.id,
- uniqueKey: cachedInfo.uniqueKey,
+ // The dedup cache doesn't track the handled state; only the full record does.
+ wasAlreadyHandled: cachedInfo?.isHandled ?? false,
+ requestId: knownRequestId,
+ uniqueKey: request.uniqueKey,
});
} else if (!requestsToAdd.has(request.uniqueKey)) {
requestsToAdd.set(request.uniqueKey, request);
@@ -378,6 +389,9 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
this._cacheRequest(cacheKey, { ...newRequest, forefront });
}
+ // Unlike `requestCache`, populate this on every batch (including background ones).
+ this.requestSeenCache.add(cacheKey, requestId);
+
if (!wasAlreadyPresent && !this.recentlyHandledRequestsCache.get(requestId)) {
this.assumedTotalCount++;
@@ -747,6 +761,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
this.assumedTotalCount = 0;
this.assumedHandledCount = 0;
this.requestCache.clear();
+ this.requestSeenCache.clear();
}
/**
diff --git a/test/core/storages/request_queue.test.ts b/test/core/storages/request_queue.test.ts
index 6a67ae785..f8f0cf16f 100644
--- a/test/core/storages/request_queue.test.ts
+++ b/test/core/storages/request_queue.test.ts
@@ -302,6 +302,47 @@ describe('RequestQueue remote', () => {
expect(mockAddRequests.mock.calls.length).toBeLessThan(20);
});
+ test('addRequestsBatched does not re-submit already enqueued requests beyond the initial batch (#3120)', async () => {
+ const queue = new RequestQueue({ id: 'dedup-across-batches', client: storageClient });
+ const mockAddRequests = vitest.spyOn(queue.client, 'batchAddRequests');
+
+ // Fake platform: deduplicates server-side by `uniqueKey` and counts every submitted request as a write.
+ const serverSeen = new Set<string>();
+ let submittedCount = 0;
+ mockAddRequests.mockImplementation(async (requests) => {
+ submittedCount += requests.length;
+ return {
+ processedRequests: requests.map((r) => {
+ const wasAlreadyPresent = serverSeen.has(r.uniqueKey);
+ serverSeen.add(r.uniqueKey);
+ return {
+ requestId: `id-${r.uniqueKey}`,
+ uniqueKey: r.uniqueKey,
+ wasAlreadyPresent,
+ wasAlreadyHandled: false,
+ };
+ }),
+ unprocessedRequests: [],
+ };
+ });
+
+ // More requests than a single batch, so the tail is added in background batches (the buggy path).
+ const urls = Array.from({ length: 5 }, (_, i) => ({ url: `http://example.com/page-${i}` }));
+ const options = { batchSize: 2, waitBetweenBatchesMillis: 0, waitForAllRequestsToBeAdded: true };
+
+ // First pass: every request is new, so all are submitted once.
+ await queue.addRequestsBatched(urls, options);
+ expect(submittedCount).toBe(5);
+ // The heavy `requestCache` still only remembers the first batch; the background batches are
+ // deduplicated by the lightweight cache instead.
+ expect(queue['requestCache'].length()).toBe(2);
+
+ // Second pass with the same URLs: everything is already enqueued, so nothing is re-submitted.
+ // Before the fix, the 3 requests outside the first batch would be sent again (submittedCount === 8).
+ await queue.addRequestsBatched(urls, options);
+ expect(submittedCount).toBe(5);
+ });
+
test('should cache new requests locally', async () => {
const queue = new RequestQueue({ id: 'some-id', client: storageClient });