Node.js › Email & Notifications

How would you implement rate limiting or throttling for outgoing notifications to avoid overwhelming users or violating a provider's sending limits?

Advanced

Answer

Rate limiting for outgoing notifications operates at two levels: respecting the third-party provider's own sending limits (using a concurrency-limited job queue, discussed earlier in Background Jobs & Queues), and respecting a reasonable limit on how many notifications a single user receives within a time window (to avoid notification fatigue or accidentally spamming a user due to a bug), typically tracked via a counter in Redis with a TTL matching the rate-limit window.
async function canSendNotification(userId, maxPerHour = 5) {
  const key = `notif-rate:${userId}`;
  const count = await redis.incr(key);
  if (count === 1) await redis.expire(key, 3600);
  return count <= maxPerHour;
}
Real-world example A social media platform caps push notifications to any single user at five per hour, using a Redis-backed counter, preventing a bug in a batch-processing job from accidentally flooding a user's phone with dozens of duplicate notifications in a short period.

Common follow-ups: How do you decide an appropriate per-user rate limit without being so restrictive that important notifications get suppressed?;How would you prioritize which notifications to send first if a user has hit their rate limit and several are queued?