When working with heavy frameworks like Next.js 14 and above, you might notice significant memory usage, especially during development. If your system has limited resources, running yarn dev
or pnpm dev
can sometimes cause your machine to hang or become unresponsive. In this article, we will create a simple Bash script to monitor RAM usage and automatically stop the development server if the usage exceeds a defined limit.
Why Monitor Memory Usage?
High RAM usage can slow down your system, leading to decreased productivity and potential data loss if the machine crashes. By automating the process of stopping heavy processes when memory usage crosses a certain threshold, you can prevent such issues and ensure smoother development.
The Script
Here is the Bash script that monitors RAM usage and terminates processes when necessary:
#!/bin/bash
# RAM usage limit (percentage)
LIMIT=95 # Change to 90 if you want a lower limit
# Function to get current RAM usage
get_ram_usage() {
free | awk '/Mem:/ {printf "%.0f", $3/$2 * 100}'
}
# Loop to monitor RAM periodically
while true; do
RAM_USAGE=$(get_ram_usage)
echo "RAM usage: $RAM_USAGE%"
if (( RAM_USAGE >= LIMIT )); then
echo "RAM has reached the limit of $LIMIT%. Stopping node processes."
killall -SIGINT node
fi
sleep 5 # Check every 5 seconds
done
Copy the script and save it as monitor_ram.sh
.
Explanation of the Script
-
LIMIT
: Sets the threshold for RAM usage. You can adjust this value as needed. -
get_ram_usage
: Calculates current memory usage using thefree
command. -
Main Loop
: Continuously monitors memory usage and stops all Node.js processes if the limit is exceeded.
How to Use the Script
Make the script executable:
chmod +x monitor_ram.sh
Run the script:
./monitor_ram.sh
The script will monitor your RAM usage and stop the development server if the usage exceeds the defined limit.
Conclusion
This script provides a simple and effective way to prevent system crashes due to high memory usage during Next.js development. Although the example provided here is specifically for Linux-based systems like Debian or Ubuntu, you can adapt the script for macOS or Windows as well. If the Bash script doesn't work out of the box, you can always ask ChatGPT for help to tailor it to your operating system.
Moreover, the concept isn't limited to monitoring RAM for Next.js. You can modify the script to work with other technologies by following the same principle: monitor resource usage and terminate services or processes that are consuming too much memory. Feel free to experiment and expand on this idea!
If you have any questions or suggestions, let me know in the comments. Happy coding!
Top comments (0)