In the first part of this series, we toured performance APIs in Node.js. We discussed the capabilities of APIs and how they can diagnose slowdowns or network issues in your Node application.
Now, in this concluding segment, we will embark on a practical journey, applying these performance hooks in a real-world scenario. You will understand how to effectively use these tools to monitor and enhance your application's performance.
Let's dive in and see these concepts in action!
Prerequisites
Before proceeding with this tutorial, ensure you have a foundational understanding of the Node.js Performance Measurement APIs as outlined in part one of this series.
Continuous Monitoring with Performance Observer for Node
Continuing our exploration of Node.js Performance APIs, we come to the
Performance Observer.
This API allows you to track new PerformanceEntry
instances in real time as
they are added to the Performance Timeline. Let's examine how to implement it:
With this configuration, every time a PerformanceEntry
with the
'resource' entryType
is added to the Performance Timeline, it gets logged automatically to
the console. To explore all the entry types available for monitoring, you can
execute:
This will display a variety of entry types:
To broaden the scope of monitoring to encompass all these entry types, adjust your observer like so:
A use case for observing the performance timeline is to upload performance measurements to an Application Performance Monitoring (APM) service like AppSignal. This way, you can keep track of how the key metrics you care about are performing and get alerted to any performance degradation.
In the following sections, I'll present a practical example showcasing the use of the Performance Observer in real-world application contexts.
A Practical Example: Monitoring Third-Party API Integrations for Node
To maintain a seamless user experience within your app, you need to track the performance of the external APIs you rely on. Delays in API responses can lead to slower interactions, adversely affecting your application's responsiveness.
To mitigate this, it's advisable to choose API providers that offer response time guarantees. Additionally, you can implement a strategy to switch to a fallback API or use cached resources when experiencing latency spikes.
Let's explore a practical scenario where your Node.js application interacts with multiple third-party APIs. You need to track each request's latency to establish a performance baseline and monitor adherence to Service-Level Agreements (SLAs).
In such cases, you can use the performance measurement APIs to collect the timing data, format it appropriately, and dispatch it periodically to a performance monitoring tool or a logging system.
This ongoing process allows you to understand the typical performance parameters for each API, so you can quickly identify and resolve any anomalies or unexpected delays in API responses.
In the following example, you'll set up monitoring for a Node.js application's API requests using AppSignal. This setup ensures that you can always track an API's response times and get alerted to performance issues automatically.
Let's begin!
Setting up the Demo Repository
To follow through with the example below, clone this repository to your computer with the command below:
After cloning, switch to the repository's directory and install the necessary dependencies:
Then, open the project in your text editor and navigate to the server.js
file.
This file includes a basic Fastify server setup with one route:
This route performs three GET requests and returns a 200 OK response. While this is a simplistic example, it's perfectly suited to demonstrate how performance hooks can be employed in real-world applications.
To start the server for development on port 3000, run:
Verify that the server is functioning correctly by sending a request to the root using curl. The command should execute successfully:
In the following section, you'll use the PerformanceObserver
API to monitor
each API request continuously.
Tracking the API Requests
Since the Fetch API automatically adds resource timing data to the Performance
Timeline for each request, you can automatically track the measurements using
the PerformanceObserver
API as shown below:
In this setup, each time a PerformanceResourceTiming
object is added to the
timeline, the script checks if the initiator is a fetch
request and logs the
details to the console. Clearing the resource timings after logging ensures room
for new entries.
Once you update the file, the server should restart, and you can repeat the
curl
command from earlier:
The server's console should now display three PerformanceResourceTiming
entries sequentially:
For a more focused output, you can modify the logging to include only the relevant details:
Resulting in:
With the ability to track, format, and log each request's timing, the next phase involves integrating these metrics with a monitoring solution like AppSignal.
Before moving to the next section, sign up for a 30-day free trial of AppSignal.
Tracking Node.js Performance Measurements with AppSignal
Once you've signed into your AppSignal account, create a new application and follow the setup instructions. Copy the Push API Key when prompted or head over to the settings and find the key in the Push & Deploy section.
Back in your project, create a .env
file at the root directory and add your
AppSignal Push API Key:
Once saved, return to your server.js
file and
initialize your AppSignal configuration
as follows:
Next, modify the PerformanceObserver
to start tracking the timing data in
AppSignal:
The addDistributionValue()
method is ideal for tracking metrics over time,
allowing you to create graphs based on average values or call counts.
Its first argument is the metric name, and the second is the value to be tracked. It also accepts one or more tags in an optional object, which, in this case, is each third-party integration being tracked in the program.
Save the file and wait for the server to restart. Test the setup by sending
requests to the /
route every five seconds using this script:
With the script running, head back to your AppSignal application and click Add dashboard on the left followed by Create a dashboard on the resulting page. Title your dashboard and click Create dashboard.
Once the dashboard is created, click the Add graph button. Give your graph a title (such as "Request durations") and click the add metric button:
Find the external_api_request
metric option and configure the graph as shown
below:
Click the Back to overview button, and change the value of the Label of value in Legend field to:
Once you're done, click the Create graph button on the bottom right. You will now see a line graph plotting the duration of each API request made by your program.
You can hover on the line graph to view the mean, 90th, and 95th percentile for each request.
Any spikes or unusual patterns in the chart can be investigated to pinpoint the cause of performance issues.
See the AppSignal documentation for more information on metrics and dashboards.
Getting Alerted to Performance Issues
When you've established the normal behavior of an API, you can set up alerts to detect when anomalies occur. AppSignal simplifies this process, allowing you to quickly configure alerts for unusual performance patterns.
Return to your dashboard and find the Anomaly Detection > Triggers section in the lower left. Click the Add a trigger button on the resulting page:
In the New trigger form, click Custom metrics at the bottom of the
sidebar. Here, configure the trigger based on your specific requirements. Ensure
you select external_api_request
as the Metric name and choose an
appropriate Comparison operator that suits the alert condition you want to
monitor.
To receive email alerts, ensure that the Email notifications option is checked. This will notify you via email whenever the set conditions are met, helping you stay informed about any performance issues in real time. You can also add other alerting integrations like Slack, PagerDuty, Discord, etc., in the application settings.
Once you've set up the trigger conditions and notification settings, click Save trigger. This action will activate the trigger, and AppSignal will start monitoring the specified metric according to the conditions you've set.
And that's it!
Wrapping Up
With this setup in place, you can now track your third-party integrations reliably and get alerted if any performance issues arise.
I hope this has given you an idea of how to use the Node.js performance APIs in tandem with AppSignal to track, monitor, and ultimately improve your Node application's performance.
Cheers, and happy coding!
P.S. If you liked this post, subscribe to our JavaScript Sorcery list for a monthly deep dive into more magical JavaScript tips and tricks.
P.P.S. If you need an APM for your Node.js app, go and check out the AppSignal APM for Node.js.