1. Background #
Modern CPUs are multi-core, and microservices typically use multithreading to maximize performance. However, when troubleshooting production issues, it’s often necessary to know how many threads a particular process is running. Without advanced APM tools, many developers aren’t sure how to monitor thread usage at the OS level.
In this guide, we’ll walk through different ways to check and monitor thread counts for microservices running on a Linux server.
2. Check Thread Count in Linux #
There are several built-in methods to check the number of threads a process is using.
2.1 Using the ps Command
#
The ps command displays information about active processes. With the -eLf options, you can also see thread-related details:
ps -eLf
Example output:
UID PID PPID LWP C NLWP STIME TTY TIME CMD
root 1 0 1 0 1 14:45 ? 00:00:00 /usr/sbin/init
root 28 1 28 0 1 14:45 ? 00:00:00 /usr/lib/systemd/systemd-journald
root 153 123 153 0 1 14:50 pts/2 00:00:00 ps -eLf
Key fields:
- PID: Process ID
- PPID: Parent process ID
- LWP: Lightweight process (thread ID)
- NLWP: Number of threads in the process
If you only want the thread count for a specific PID, use:
ps -o nlwp <PID>
or equivalently:
ps -o thcount <PID>
To get the total thread count across the server:
ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'
2.2 Checking the /proc Directory
#
Linux exposes process details in /proc. You can check threads for a given PID:
ls /proc/<PID>/task/
Each entry corresponds to a thread ID.
Another way is to check the status file:
cat /proc/<PID>/status | grep Threads
This outputs the current thread count for that process.
3. Real-Time Thread Monitoring #
3.1 Using watch with ps
#
To continuously monitor the number of threads for a process, combine watch with ps:
watch -n 1 ps -o thcount <PID>
This refreshes every second and shows live thread count updates.
3.2 Using the top Command
#
top provides real-time system monitoring but doesn’t display thread counts by default.
To enable thread count:
- Run
top - Press f to enter field management
- Select the
nTHfield (number of threads) - Press q to return
Now, top will display a nTH column showing the number of threads per process.
Example view:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND nTH
1 root 20 0 21456 9212 7048 S 0.0 0.1 0:00.28 systemd 1
28 root 20 0 26528 7976 7104 S 0.0 0.1 0:00.04 journald 1
119 root 20 0 12068 3664 3100 S 0.0 0.0 0:06.19 top 1
4. Summary #
To monitor microservice thread usage in Linux:
- Use
psfor one-time snapshots - Use
/procfor detailed process information - Use
watchortopfor real-time monitoring
This helps identify thread overuse issues in microservices and ensures better resource management on your servers.
👉 Next step: You can also integrate these commands into monitoring scripts or tools like Prometheus + Grafana for automated thread usage alerts.