REST API Performance Tips
The need to improve the performance of a specific endpoint of a REST API happens very often, here I present to you some tips that can help you to improve the performance of your REST API:
Verify the time consumed on the endpoint
Execute the request and verify how much time it is taking. Personally, I think that if the requests take more than 300ms then I should take a look at it and try to improve it if it’s worthy.
Identify the task(s) that are taking more time to finish. If you have more than one time-consuming task on your endpoint try to execute them in parallel to save time. Try to avoid executing big time-consuming tasks synchronously.
Send only the data that will be used by the client
Verify that I’m only sending just the data that the client will consume. Two things to apply are:
- Consider paginating the results if they are too much.
- Return just the necessary fields, i.e.: if we should return a list of employees from DB maybe we just need to return the name and department and not the age, birthday and other things. You can provide a “fields” param on the endpoint when the client can specify what fields he wants to retrieve.
Compress your Response
You can compress your response using for example Gzip. That will allow you to save bandwidth and of course response time.
Use Cache whenever possible
If it is reasonable cache the whole endpoint response. If your backend is executing a time consuming task to gather some data back consider to use a cache there so you don’t have to execute that expensive task all the time, that way you just have to execute it when you consider that an acceptable amount of time has passed and the expensive task should be consumed again to maintain the data updated on the cache.
Put your server behind a reverse proxy (i.e. Nginx) so you can easily apply horizontal scalability, that means that you can add more server instances. i.e.: if you are receiving 1000 requests on a single server if you add one more the reverse proxy server will balance the load between servers and now each one will receive 500 requests.
Add more RAM or CPU to your server instance.