Rate limiting with delay node

I couldn't find a sufficient option for a recent Karaoke project. What I needed was the ability to send the first X messages in Y time period and then drop the rest until the time is up.

I ended up using a function node that I believe should work with the following:

// Define constants for rate limiting
const RATE_LIMIT = 100; // Change this to your desired rate limit
const RESET_TIME_MS = 24 * 60 * 60 * 1000; // 24 hours

// Initialize the message count and the daily reset timestamp in flow context
flow.set('messageCount', flow.get('messageCount', "memoryOnly") || 0, "memoryOnly");
flow.set('dailyResetTimestamp', flow.get('dailyResetTimestamp', "memoryOnly") || Date.now(), "memoryOnly");

// Get the current timestamp
const currentTime = Date.now();

// Get the message count and daily reset timestamp from flow context
const messageCount = flow.get('messageCount', "memoryOnly");
const dailyResetTimestamp = flow.get('dailyResetTimestamp', "memoryOnly");

// Check if it's time to reset the message count
if (currentTime - dailyResetTimestamp >= RESET_TIME_MS) {
    flow.set('messageCount', 0, "memoryOnly"); // Reset the count
    flow.set('dailyResetTimestamp', currentTime, "memoryOnly"); // Update the reset timestamp
};

// Increment the message count
flow.set('messageCount', messageCount + 1, "memoryOnly");

// Determine if the message should be allowed or blocked
if (messageCount >= RATE_LIMIT) {
    // Block the message
    return null;
};

// Allow the message to pass
return msg;

Would this make a good suggestion for the core delay node when set to rate limit?

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.