This content originally appeared on Bits and Pieces - Medium and was authored by Eren Yatkin
Proper Way to Add Graceful Shutdown — Node.js
Hi, internet! I know you are trying to do your best to improve your skills in software development and I am here to give you a niche subject. If you are a backend developer this post is just for you!
When we are developing our projects, micro startups or the next big FAANG, we need to do this the right way. It does not matter which design system you chose microservice, SOA or monolithic you should always add a graceful shutdown procedure in your application because data loss is not a thing we can afford. Besides that, the service you provide will be interrupted.
In today's circumstances, projects are at least updated once a day and this can cause service interruption which can in turn cause data inconsistency. To prevent this we have a simple solution that will be worth developing.
What is Graceful Shutdown?
Graceful shutdown is essential for server applications because it ensures that a service can be shut down in a controlled manner without disrupting other services that depend on it. Microservice architectures typically involve breaking down a large application into smaller, independent services that communicate with each other over the network or are complete applications themselves, working on their own. Each service is responsible for a specific task and can be developed, deployed, and scaled independently.
When an application needs to be shut down, it is important to do so in a way that does not cause any disruption to the overall system. A graceful shutdown allows the service to complete any in-progress tasks, clean up any resources it is using, and notify other services that it is going offline. This can help prevent data loss, reduce downtime, and avoid cascading failures that could affect other services.
Here are some key reasons why graceful shutdown is important for microservices:
- Prevent data loss: If a service is shut down abruptly, any in-progress transactions or requests may be lost, leading to data corruption or data loss. A graceful shutdown ensures that all data is saved and any pending requests are processed before shutting down.
- Avoid cascading failures: When a service goes offline, it can trigger a cascade of failures in other services that depend on it. A graceful shutdown allows dependent services to prepare for the outage and gracefully handle the failure.
- Reduce downtime: By shutting down in a controlled manner, you can minimize the amount of downtime required for maintenance or updates. This helps keep the system up and running and reduces the impact on users.
- Clean up resources: A service may be using resources such as file handles, database connections, or network sockets. A graceful shutdown allows the service to release these resources in a controlled manner, reducing the risk of resource leaks or conflicts with other services.
Overall, graceful shutdown is an important part of microservices development and deployment. It helps ensure that each service can be managed independently and that the overall system remains stable and reliable. As a developer, it is important to design services with graceful shutdown in mind and to test this functionality thoroughly to ensure that it works as expected.
In Node.js, shutdown signals are signals sent to a Node.js process that notify it to gracefully shut down. These signals allow a Node.js process to perform any necessary cleanup tasks before exiting, such as closing open connections or releasing resources.
Here are the most common shutdown signals in Node.js:
- SIGINT: The SIGINT signal is generated when the user presses CTRL+C on the terminal. This signal is often used to gracefully terminate a Node.js process.
- SIGTERM: The SIGTERM signal is used to request a graceful termination of a Node.js process. This signal can be sent by a process manager or other external tool to gracefully shut down the Node.js process.
- SIGHUP: The SIGHUP signal is generated when a process is disconnected from the terminal or when the terminal session ends. This signal is often used to request a reload or restart of a Node.js process.
When a Node.js process receives a shutdown signal, it can use the process.on() method to register a handler function to perform any necessary cleanup tasks. For example, the handler function can close open connections, release resources, and gracefully terminate the process.
The Example
In this example, we will use plain Express to demonstrate. I assume that you are capable of creating a Node.js project and adding some packages.
const express = require('express');
const app = express();
let appStatus = 1;
app.use((req, res, next) => {
if (appStatus) {
return next();
}
throw new Error('App is closing');
})
app.get('/', (req, res, next) => {
res.send('*** Server is working ***')
});
app.listen(3000, () => {
console.log('App is now running on: http://localhost:3000')
});
process.on('SIGINT', (signal) => {
appStatus = 0;
console.log('*** Signal received ****');
console.log('*** App will be closed in 10 sec ****');
setTimeout(shutdownProcedure, 10000);
})
function shutdownProcedure() {
console.log('*** App is now closing ***');
process.exit(0);
}
Let’s break it down:
- We defined Express to create a server.
- Created a variable called app and this will be our server application.
- Defined a variable called appStatus to allow requests to be processed.
- Added middleware to check app status to allow requests to be processed or not.
- Added a route to handle incoming requests.
- Started to listen port on 3000 and output a message.
- Also, we started to list incoming signals with process.on('SIGINT') this will be fired when you kill the app with ctrl + c.
- We set appStatus = 0 to block incoming requests then started a timer.
- When the timer goes off shutdown procedure will be complete and we can close our application.
Conclusion
As a developer, it’s important to design services with graceful shutdown in mind and to test this functionality thoroughly to ensure that it works as expected. By doing so, you can ensure that your microservices architecture is flexible, scalable, and resilient and that your Node.js applications are able to handle any situation that arises.
💡 By using an open-source toolchain like Bit, you can further ensure felixibility, scalability, and resilience in a microservice architecture by making sure your components are made independent, then versioned, tested, and shared across different microservices, with automatic semver and a dependency graph for each. This reduces the risk of failures caused by inconsistent dependencies or code duplication.
Learn more here:
Component-Driven Microservices with NodeJS and Bit
Thank you all for reading through here, I much appreciate your time. See you all on another blog post!
From monolithic to composable software with Bit
Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more
- Creating a Developer Website with Bit components
- How We Build Micro Frontends
- How we Build a Component Design System
- How to reuse React components across your projects
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
Proper Way To Add Graceful Shutdown — NodeJs was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Eren Yatkin
Eren Yatkin | Sciencx (2023-03-29T10:43:46+00:00) Proper Way To Add Graceful Shutdown — NodeJs. Retrieved from https://www.scien.cx/2023/03/29/proper-way-to-add-graceful-shutdown-nodejs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.