DEV Community

Victor de Lima
Victor de Lima

Posted on

Use cache-control for API never crash! (ReactJS)

Hello guys, today I’m going to talk a little about a nice tip for when you’re using an external API it never crashes, taking down the site where this return is coming from because of several requests made by users who request it in your application.

When using max-age to set your cache times, you must consider the file type and how it is used. We will discuss this in more detail later in this article.

In this specific project you will understand why we use this method and reasons to still use it when we are using the return of an external API.

We used the cache-control for an API from the TSE — Tribunal Superior Eleitoral to create a webapp of the results of the 2022 elections in Brazil.

As this data will be accessed from several places and the last webapp created in PHP had more than 2 million requests per hour, there was a lot of downtime on the TSE website, thus not returning any data for a period of 1 hour until the website returned to get on the air again (That was a problem for us)

But how did I solve this problem? Very simple after all, as I went from PHP to ReactJS (best thing I did)… Because the code has more techniques of clean, readable code and with a good user experience… Nothing against PHP, but in this project the ReactJS gave 100x0 in PHP.

Returning to the subject, to solve this problem, a normal fetch call was made with the link where the API is returned in JSON and we added a header

`headers: {
“Content-Type”: “application/json”,

“cache-control”: “s-maxage=10, stale-while-revalidate”
}`

you can see in the code or in the photo of how this code was:

headers-cache-control

But why use cache-control in this case?

Remember that we talked about more than 2 million requests in the TSE API?

Well, with the cache control I can set a “maxAge” a maximum age time for the API to return new data saving the ones requested by the user in the cache and request new data only after 10 seconds giving a very foul way A GOOD TIME TO The BREATHE API.

With the stress test, we had a 98% improvement based on the amount of request x data the API returned every 10 seconds compared to the previous project without the cache-control. As a result, the project became more scalable and safer with data handling.

Top comments (0)