简体   繁体   中英

Implementing a Notificaion Queue in Node.js

Background: Imagine an app like Instagram where you can submit posts and other people can like them. Whenever someone likes your post, you get a notification.

Requirement: We should not send a notification everytime a person likes a particular post of yours. We should be smart about how and which notifications we send.

Here's an example:

Let's say you posted a post at 8:27 pm . I liked your post. Within 5 seconds, another friend of yours liked the same post. The user can get the following notifications:

  1. Emma Watson liked your post.
  2. Natalia Dyer liked your post.

However, imageine 20 people liking the post within 5 seconds. Since we do not want to bombard the user with notifications, we should smartly club them and say:

  1. Natalia Dyer and 1 other person liked your post.

How do we do that?

How do we send notifications when the "LIKE A POST" api is hit, and how do club the notifications into a single one?

A maybe wrong solution: When that API is hit, we store in redis that a notification is supposed to be sent for this post to a user.

Then, there is a consumer of that reddit queue that pops things out every five seconds.

If we receive a notification before it has been picked up by the consumer, we remove the previous entry in the redis cache and replace it with our new notification.

Then, after five seconds, if no other actress likes our post, we will get a notification saying: Natalia Dyer and 1 other person liked your post

Let me know if that is a legit and efficient solution. If it is, is it scalable?

Any new ideas/iterations are welcome and I look forward to them.

You could use better-queue to create a queue with a batchDelay and merge duplicated tasks.

In your example, the batchDelay would be 5 seconds and you could build the taskId = postId + actionId

Where the postId uniquely identifies the post and the actionId would be something like "likeAction".

This way, in that 5-second time window, all the like notifications for that same post will have the same taskId and will be merged into a single task.

Let me know if it works for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM