Throttling calls to a server function in NextJS

I have a server function that can poll if a long-running event (Ethereum transaction being mined) has completed yet. The actual request checking the blockchain is obviously also async and can take a second or two. If someone hits the page when the transaction result hasn't already been stored in the db, their client will start calling a function on the server to check the status and update the db on success. If multiple people are on this page, I don't really want to poll the blockchain excessively, so I want to early exit from calls to the server function that happen too often. Will this approach work?
const lastInvocationTimes = new Map<string, number>();

export async function pollProposalTransactionAndUpdateIfResolved({
proposalId,
chainId,
transactionHash,
}: {
proposalId: Proposal["id"];
transactionHash: Hash;
chainId: number;
}) {
// unique key for the tx.
const key = `${chainId}-${transactionHash}`;
const lastInvocationTime = lastInvocationTimes.get(key);

// Check if on cooldown.
if (lastInvocationTime && lastInvocationTime + 1000 * 15 > Date.now()) {
console.debug(`polling ${transactionHash} on ${chainId} throttled`);
return;
}

// Not invoked recently.
lastInvocationTimes.set(key, Date.now());
await _pollProposalTransactionAndUpdateIfResolved({
proposalId,
chainId,
transactionHash,
});
}
const lastInvocationTimes = new Map<string, number>();

export async function pollProposalTransactionAndUpdateIfResolved({
proposalId,
chainId,
transactionHash,
}: {
proposalId: Proposal["id"];
transactionHash: Hash;
chainId: number;
}) {
// unique key for the tx.
const key = `${chainId}-${transactionHash}`;
const lastInvocationTime = lastInvocationTimes.get(key);

// Check if on cooldown.
if (lastInvocationTime && lastInvocationTime + 1000 * 15 > Date.now()) {
console.debug(`polling ${transactionHash} on ${chainId} throttled`);
return;
}

// Not invoked recently.
lastInvocationTimes.set(key, Date.now());
await _pollProposalTransactionAndUpdateIfResolved({
proposalId,
chainId,
transactionHash,
});
}
Asking because I'm not sure if all clients share the same server instance, so I don't know if lastInvocationTimes will always be correct? I'm using NextJS on vercel
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server