All for Joomla All for Webmasters
Ruby On Rails

Boosting your Rails API Performance Through Caching

In your application development, you can realize that some endpoints in your API will often keep their response unchanged. That unnecessary rework may be a gap in your API performance. For those cases, when your response doesn’t need to be updated in real time, a good approach would be to cache your API response. In this post, I will show that solution on Ruby on Rails framework with a WordPress API call.

Picture this situation: in your endpoint, you need to fetch the posts from a blog category that rarely receives new posts. Without caching, each user request would be a call to an external API (that would often provide the same response). To boost that process, we can set in our code a key that identifies and caches that response. Once the first call is done, the next ones that contains the same keys will be just retrieved and so, optimized. In ruby code:

This is a classic example of fetching posts from a WordPress API. Notice that the posts variable assignment is now a block code that contains the API call. That fetch function block code from cache framework (which is available by default on Rails) receives two params: an array with the keys that identifies our call, and the expiry time for that value stored (this should be set according to how often that response changes and you need it to be updated). As the first param is an array, we can use a set of N keys to label that call. In another case where you want to cache that value by user, for example, you can add the user ID to that set.

This short and simple code block is enough to a good improvement in your API performance. Remember that, by default, Rails caching is disabled in development environment. To enable/disable it, you can run rake dev:cache . If you have any doubts or suggestions, please use the comment area or contact me.

You Might Also Like

2 Comments

  • Reply
    Online Training
    June 1st, 2021 at 06:18

    Thank you for sharing details.

  • Reply
    Mulesoft Training
    July 7th, 2021 at 08:42

    Nice article. Thank you for sharing.

  • Leave a Reply to Mulesoft Training Cancel Reply