polkadot-js / api

Promise and RxJS APIs around Polkadot and Substrate based chains via RPC calls. It is dynamically generated based on what the Substrate runtime provides in terms of metadata.
Apache License 2.0
1.07k stars 350 forks source link

Memory Leak in `query.entriesPaged` #5798

Open justraman opened 7 months ago

justraman commented 7 months ago

I've encountered an issue related to memory consumption while using the entriesPaged method. As I attempt to retrieve entries from the API in batches within a loop, I've noticed a steady increase in memory usage over time. This gradual buildup eventually leads to high memory consumption, crashes with FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Here is the code which lead to memory leak

    const BATCH_SIZE = 500;
    let lastKey = '';

    while (true) {
        const query = await api.query.multiTokens.tokens.entriesPaged({
            args: [],
            pageSize: BATCH_SIZE,
            startKey: lastKey,
        });

        if (query.length === 0) {
            break;
        }
        for (const [key, value] of query) {
            lastKey = key.toHex();
        }
    }

please run it against rpc: wss://enjin-matrix-rpc-1.dwellir.com or you can also quickly reproduce this by running this on polkadot.js web.

TarikGul commented 1 month ago

Could be related: https://github.com/polkadot-js/api/issues/5981