Table of contents
- API Optimization Means
- Ways to Optimize Node.js APIs.
- 1. Always use Async/Await functions call
- 2. Avoid Sessions, Cookies, HTML page rendering in at Server side & Send Only Data in the API Response.
- 3. PM2 Clustering for Optimizing APIs
- 4. Reducing TIme to First Byte (TTFB)
- 5. Use Logging for Monitor
- 6. Run Task in Parallel
- 7. Database Queries Optimization
- 9. Use InMemory database like Redis to cache in App
- End...
In this article, we will discuss the best methods to optimize APIs so that our user get fast response from our APIs.
Specifically, we are talking about Node.js API optimization.
API Optimization Means
- Improving responsive time of API. The shorter the API, faster the API will be
- Improving performance. Which help us to use less resources (CPU & Memory)
- Quick response or low latency of API on large number of requests hitting at the same time
- best error management during wrong request.
Ways to Optimize Node.js APIs.
1. Always use Async/Await functions call
Use asynchronous function to perform nonblocking I/O operations, which help us to Optimize CPU usages.
I/O operations include CURD (create, update, read, write)operations on database, Cloud Storage, or local Storage disk.
Using Asynchronous calls in highly intensive I/O Operations applications will improve performance. This is because CPU can handle multiple request simultaneously due to non-blocking I/O while I/O request is processing I/O operations.
import { readFileSync, readFile } from 'fs'
// 1. blocking I/O Oprations
let file = readFileSync("file_name.txt") // synchronous and blocks execution until finished.
console.log(file)
// 2. non-blocking I/O Oprations
readFile('file_name.txt',(err,file) => {
if(err) return err;
console.log(file)
}) // is asynchronous and returns immediately while things function in the background
2. Avoid Sessions, Cookies, HTML page rendering in at Server side & Send Only Data in the API Response.
Using cookies and sessions to store temporary states in the server cost a lot to server.
API should be stateless, which we can achieve using JWT, OAuth authentication mechanisms. These mechanisms generate tokens which can be store at client side and reduce job of server for managing state.
- JWT is a JSON-based security token for API Authentication. JWT can be read but not modifiable once they are sent.
- OAuth stand for open standard for authorization. OAuth is the standard set of step for generating token.
Don't send the full HTML page in the response of the API. Node server work better when only data is sent by API in JSON or any another.
3. PM2 Clustering for Optimizing APIs
PM2 is a Process Manager designed for Node.js API. The built-in load balancer allows the application to run as multiple processes without changing code.
PM2 improve performance and concurrency of your API.
CMD for pm2 cluster for scaling across all available CPUs:
pm2 start app.js -i 0
4. Reducing TIme to First Byte (TTFB)
Time to First Byte is matrix used to mesure of responsiveness of web server or other network resurces. TTFB measures the duration from client making HTTP request to first byte of page being received by the client's browser.
If the web browser loads within 100ms. THis is because of the physical distance between the server and client.
Here we can reduce TTFB by using CDN (content delevarery network) which cach content in local datacenter across the globe. This helps users access the content with less latency. Cloudflare is one of the CDN solutions you can have look.
5. Use Logging for Monitor
The best way to monitor the proper functioning of your API is to keep tarack of all activity. This is were logging the data comes into picture
Use console.log() for printing out logs on console
Use custom package for more efficient way to moniter logs like Morgan Winston in log files
6. Run Task in Parallel
Use async.js to help you run tasks. Running tasks in parallel create greate inpact on performence of your API. And also help in reducing latency and minimimize blocking oprations.
You don't need to control the execution sequence of the program
7. Database Queries Optimization
Database Query optimization is an essential part of any optimized APIs in Node. Especially in large applications, You'll need to query database many time. Hence bad query can reduce the performence of the API.
Indexing is an approch to optimize the performence of database by minimizing number of disk acesses required when featching data from database. It use data structure technique that is used to quickly locate and acess data in database. Indexes are created using database colms.
Note :- You can query database fast after indexing but Insertation will take time.
There is a huge difference in the number of documents scanned ~ 1038:
Without indexing => 1039 or any number document scanned
With indexing => 1 document scanned
9. Use InMemory database like Redis to cache in App
Using InMemory database like Redis or Memcached. It optimizes the APIs response time by storing and retrieving the data from main maemory of server. It increases the performence of the database queries which also requce time for quarying.
There is a huge difference in the response time ~ 899.37ms.Following is the response time for Node.js API with and without Redis.
Without Redis:- 900ms
With Redis:- 0.621ms
End...
Hope you like this artical do share with your friends and please share your feedback in comments.