How did I implement rate/limit feature for comments?

How did I implement rate/limit feature for comments?

Daily short news for you
  • A library brings a lot of motion effects to your website: animejs.com

    Go check it out, scroll a bit and your eyes will be dazzled 😵‍💫

    » Read more
  • A repository that compiles a list of system prompts that have been "leaked" on the Internet. Very useful for anyone researching how to write system prompts. I must say they are quite meticulous 😅

    jujumilk3/leaked-system-prompts

    » Read more
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more

Problem

Captcha is a method designed to prevent spam behavior on applications, especially on web applications. Without captcha, attackers can easily generate automated queries with continuous frequency to a specific function to sabotage the system.

However, captcha is not without flaws. Its biggest drawback is that it can be confusing for users. Many codes are generated to verify that you are a human, but sometimes you have to wonder if you are indeed human when you can't decipher those distorted or blurry characters.

The comment function on 2coffee does not use captcha to create difficulties for users. Instead, I have implemented a technique called "rate/limit" to restrict spam behavior. Basically, it prevents continuous actions and limits the number of times a certain action can be performed within a specific time period. For example, only allowing users to comment a maximum of 3 times in 1 minute, or requiring a minimum of 10 seconds before submitting the next comment.

In today's article, I would like to share the process of implementing my rate/limit feature. I believe it will be helpful for readers, or I hope to receive feedback from readers to improve the implementation.

Algorithm

The initial idea is very simple. Since I didn't want to be too strict, I decided to allow users to submit a comment every 10 seconds after a successful submission. After successfully submitting a comment on one post, they need to wait at least 10 seconds before submitting a comment on any other post.

At this point, I need to implement an algorithm that takes the user ID as input and returns true/false. True if the limit has not been exceeded, false if they have commented too many times. Based on this, I can determine whether to allow them to submit a comment or not.

There are many ways to solve this problem, the simplest one is to retrieve their last comment and check the time to see if it's valid. This method is fast and straightforward to implement, but if there are many comments in the future, the query can become slower. Furthermore, future expansions may become more complicated. For example, changing the algorithm to allow them to submit a maximum of 3 comments within one minute. This would make the query more complex and likely slower.

Since Redis is being used, I have another approach to leverage the expire feature (ttl) of a key in Redis. I will create a key in the format comment_limit:user_id which contains a boolean value with an expiration time equal to the time between consecutive comments. Each time a comment is made, I just need to check if the key comment_limit:user_id exists. If it exists, it means they are not allowed to comment, and vice versa.

The advantage of this method is that the condition check is relatively fast, requiring only one query to retrieve the comment_limit:user_id key. However, more code needs to be written to handle the logic.

Implementation

The implementation is very simple. You need to have a Redis server to create keys with ttl. Each time you call the comment creation function, check if the comment_limit:user_id key exists.

For example, in the case where my user_id is 1:

GET comment_limit:1

If comment_limit:1 returns true, throw an error indicating that commenting is not allowed. Otherwise, if it returns null, allow the comment to be added, and then create a key comment_limit:1 with an expiration time set to the time you have configured. Let's assume it's 10 seconds:

SET comment_limit:1 true EX 10

With this, after 10 seconds, comment_limit:1 will be automatically deleted and the logic will allow the user to comment again.

Conclusion

There are many ways to implement the rate/limit algorithm for comment sections. I am currently using the approach of using the automatic expiration feature of keys combined with naming conventions to create a logic for checking the availability of comment activities. If you have any other approaches, please leave a comment for everyone to know!

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...