Basic Rate-limiting in WooCommerce with native class

WC_Rate_Limiter is a great little utility class in WooCommerce codebase which is not very popular but could be very helpful at times. I accidentally stumbled upon it while reading the source code of WooCommerce and thought of sharing it on my blog.

You would want to use rate-limiting to prevent user from performing an action again and again too frequently. For example, one would want to rate-limit file download so that a file can be downloaded only once a day.

It’s very easy and straight-forward to accomplish this with a few lines of code.


$user_id = get_current_user_id();
$action  = "download_my_file_{$user_id}";
$delay   = 60 * 60 * 24; // 24 hours.

if ( WC_Rate_Limiter::retried_too_soon( $action ) ) {
    echo 'Sorry, you can only download the file once in a day. ';
} else {
	WC_Rate_Limiter::set_rate_limit( $action, $delay );
    // Add code to download the file.

$action is a custom action name for the event. You can name it anything.

$delay is the time interval for which you want to rate-limit the action.

  1. Hey man,

    This is very good to know, thank you!

    Nevertheless, there’s one thing to keep in mind: it seems that the WC_Rate_Limiter class stores everything as an option and things don’t get deleted when the limit is expired.

    For that reason, you would want to limit the number of actions. If it’s a couple of actions per user_id, that’s fine, but if you end generating plenty of actions (ex. allowing non-connected users to do something, creating actions based on their ip), it’s going to clutter the DB.

    For these cases, transients may be a better choice.

    1. Hi, Thanks for your comment. As far as I can check in the source code of WC_Rate_Limiter, it seems they store it in a custom class.

      Also, looks like there is a cleanup procedure that runs every 3 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

WooCommerce is_catalog() function

WooCommerce is_catalog() function