Diagnosing High Memory Usage and Persistent Laravel Processes on Linux
When managing a Linux server running Docker, PHP-FPM, and Laravel applications, you may occasionally notice that memory usage keeps increasing or that multiple PHP processes remain running for an unexpectedly long time.
Some common examples include:
- Multiple
dockerdentries appearing inhtop. - Several PHP-FPM workers consuming significant memory.
- Multiple
php artisan schedule:runprocesses accumulating. - Laravel queue workers remaining alive even when there are no pending jobs.
- Processes continuing to run after their expected tasks have finished.
Understanding how Linux processes work and how Laravel manages background tasks is essential for diagnosing these problems.
This article summarizes a practical troubleshooting process and explains how to identify and manage these processes.
1. Understanding Multiple Docker Processes in htop
You may encounter output similar to this:
19249 root 20 0 2019M 63340 5364 S 0.0 0.8 dockerd
19250 root 20 0 2019M 63340 5364 S 0.0 0.8 dockerd
19251 root 20 0 2019M 63340 5364 S 0.0 0.8 dockerd
19252 root 20 0 2019M 63340 5364 S 0.0 0.8 dockerd
At first glance, it looks like multiple Docker daemon processes are consuming memory.
However, these entries may actually represent threads belonging to the same dockerd process.
Docker is written in Go, and its runtime creates multiple operating system threads to handle concurrent operations.
Understanding the memory values
Two important columns in htop are:
- VIRT: Total virtual memory allocated or mapped by the process.
- RES: Resident memory currently occupying physical RAM.
For example:
VIRT: 2019M
RES: 63340 KB
This means the process has approximately 2 GB of virtual address space, but only around 62 MB of resident physical memory.
The virtual memory value does not mean that the process is consuming 2 GB of physical RAM.
Also, multiple thread entries share the same process address space. Their RES values must not be added together as if they were independent processes.
How to hide thread entries
In htop, press:
H
This toggles the display of user threads.
In top, you can also press uppercase H to toggle thread visibility.
This makes it easier to distinguish actual processes from their threads.
2. Identifying PHP-FPM Memory Consumption
Another common situation is seeing multiple PHP-FPM workers:
827 nobody 20 0 3879M 61316 1088 S 0.0 0.8 php-fpm: pool www
826 nobody 20 0 3879M 59820 1096 S 0.0 0.8 php-fpm: pool www
834 nobody 20 0 3878M 59312 1132 S 0.0 0.8 php-fpm: pool www
836 nobody 20 0 3878M 59208 1068 S 0.0 0.8 php-fpm: pool www
Unlike Docker threads, PHP-FPM workers are independent processes.
Each worker has its own process memory, although some memory regions, such as shared libraries and OPcache, may be shared.
Why does PHP-FPM use so much memory?
There are several possible reasons:
- PHP scripts process large arrays or datasets.
- ORM queries load large amounts of database records.
- Export or report-generation tasks require significant memory.
- PHP extensions allocate additional memory.
- Long-running workers retain memory after processing requests.
PHP’s memory manager may retain allocated memory for reuse instead of immediately returning it to the operating system.
Consequently, a worker’s resident memory may remain relatively high even after a request has completed.
How to prevent excessive memory accumulation
PHP-FPM provides several configuration options.
Open the relevant pool configuration file, usually www.conf, and check the following settings:
pm.max_requests = 500
This setting instructs each worker to handle a maximum of 500 requests before exiting. PHP-FPM then creates a replacement worker.
It is useful for limiting long-term memory accumulation.
If you are using dynamic process management, you can also adjust:
pm.max_spare_servers = 4
This limits the number of idle workers retained by PHP-FPM.
The appropriate values depend on your server’s available memory and application traffic.
One important detail: when evaluating total PHP-FPM memory usage, remember that RSS includes shared memory. Adding every worker’s RSS together can overestimate actual physical memory consumption. PSS is more useful for estimating each process’s proportional share.
3. Determining Whether a Process Runs Inside Docker
When you find an unexpected PHP process, the next step is determining whether it belongs to the host system or a Docker container.
For example, suppose you want to investigate PID 827.
Run:
cat /proc/827/cgroup
Host process example
You might see:
11:devices:/system.slice/php-fpm.service
10:blkio:/system.slice/php-fpm.service
8:memory:/system.slice/php-fpm.service
The /system.slice/php-fpm.service path indicates that the process belongs to a systemd-managed service on the host.
Docker container process example
A Docker-managed process may show:
11:devices:/docker/01aa6624de46bdf2a927da508c8c9e29...
10:blkio:/docker/01aa6624de46bdf2a927da508c8c9e29...
8:memory:/docker/01aa6624de46bdf2a927da508c8c9e29...
The /docker/ path and container ID indicate that the process belongs to a Docker container.
The exact cgroup layout can vary depending on the cgroup version and container runtime.
Find the corresponding Docker container
Once you have identified the container ID, use:
docker ps --filter "id=01aa6624de46"
To include stopped containers:
docker ps -a --filter "id=01aa6624de46"
You can also inspect the process hierarchy:
pstree -sp 827
A process hierarchy containing containerd-shim can provide additional evidence that the process belongs to a container.
4. Investigating Accumulated Laravel schedule:run Processes
One particularly interesting problem occurs when multiple Laravel scheduler processes accumulate.
For example:
18740 root 20 0 138M 46976 15264 S 0.0 0.6 php artisan schedule:run
19186 root 20 0 138M 46976 15264 S 0.0 0.6 php artisan schedule:run
22054 root 20 0 138M 46976 15264 S 0.0 0.6 php artisan schedule:run
22806 root 20 0 138M 46976 15264 S 0.0 0.6 php artisan schedule:run
Why are there so many instances of the same command?
How Laravel’s scheduler works
A typical Laravel scheduler is triggered through Cron:
* * * * * cd /path/to/project && php artisan schedule:run >> /dev/null 2>&1
Cron starts a new schedule:run process every minute.
Under normal circumstances, each process checks the scheduled tasks, executes the tasks that are due, and exits.
However, if a scheduled task takes longer than expected or becomes blocked, the previous scheduler process may still be running when Cron starts the next one.
This can result in multiple processes accumulating.
Identify how long the processes have been running
Use:
ps -eo pid,lstart,etime,cmd | grep "schedule:run"
Example:
18740 Wed Dec 2 01:10:01 2026 46:12 php artisan schedule:run
The etime column shows the elapsed time since the process started.
This is much more useful than the TIME+ column in htop, which displays accumulated CPU time rather than total process lifetime.
Why does withoutOverlapping() not always solve the problem?
Laravel provides:
$schedule->command('your:command')
->everyMinute()
->withoutOverlapping();
This prevents the same scheduled task from running concurrently by using a cache-based mutex.
However, it does not prevent Cron from launching another schedule:run process every minute.
If a scheduler process is blocked during application initialization, cache access, database access, or another operation, new scheduler processes may still accumulate.
It is important to distinguish between preventing scheduled task overlap and preventing scheduler process accumulation.
Investigate the actual blocking point
Run the scheduler manually with verbose output:
php artisan schedule:run -vvv
Check the following:
- Whether the scheduler can initialize successfully.
- Whether it gets stuck while connecting to Redis or the database.
- Whether a particular scheduled command takes too long.
- Whether another application service provider is blocking initialization.
Also inspect running Artisan processes:
ps aux | grep artisan
Use flock to prevent overlapping scheduler processes
One additional protection is using Linux flock directly in Cron:
* * * * * /usr/bin/flock -xn /tmp/laravel-schedule.lock -c "cd /path/to/project && php artisan schedule:run >> /dev/null 2>&1"
This ensures that only one scheduler invocation can hold the lock at a time.
If the previous invocation is still running, the next Cron execution exits without starting another scheduler process.
This is particularly useful when scheduled tasks occasionally take longer than one minute.
Note that runInBackground() can also be useful for independent, long-running scheduled commands, but it should not be used as a substitute for proper process supervision.
5. Understanding Laravel Queue Workers
Another process that often appears in server monitoring tools is:
php artisan queue:work \
--queue=update-vip-service \
--sleep=3 \
--tries=3 \
--daemon
Unlike schedule:run, this process is designed to remain alive.
Why does queue:work keep running?
Laravel queue workers are long-running processes.
Their basic workflow is:
- Bootstrap the Laravel application.
- Connect to the configured queue backend.
- Retrieve available jobs.
- Execute a job.
- If the queue is empty, wait for the configured sleep interval.
- Continue polling for new jobs.
For example:
--sleep=3
means the worker waits approximately three seconds when no jobs are available before checking again.
Therefore, seeing a queue worker in the S (Sleeping) state with almost zero CPU usage is generally normal.
It does not necessarily indicate a stuck process.
The --daemon option was historically used to explicitly enable long-running worker behavior. In modern Laravel versions, queue:work already operates as a long-running worker, so explicitly specifying --daemon is generally unnecessary.
How to stop a queue worker safely
If you need to stop a specific worker, you have several options.
Option 1: Send SIGTERM
kill 6573
This requests a graceful shutdown. Laravel can finish the current job before exiting.
Option 2: Restart Laravel queue workers
From the application directory:
php artisan queue:restart
This signals workers to exit after completing their current jobs.
This is particularly useful after deploying new application code.
Option 3: Forcefully terminate a process
If a worker is genuinely unresponsive:
kill -9 6573
For multiple workers belonging to a specific queue, first inspect the matching processes:
pgrep -af "queue=update-vip-service"
Only after confirming the matches should you consider terminating them.
Be careful with SIGKILL: it does not allow Laravel to perform graceful shutdown operations. An interrupted job may need to be retried or recovered according to the queue driver’s reservation and retry configuration.
Why does a queue worker sometimes remain stuck?
A long-running worker can encounter problems such as:
- Database connection failures.
- Redis connection problems.
- Slow external API requests.
- Database lock contention.
- Jobs that take longer than expected.
- Missing timeout configuration.
For example, if a worker is waiting indefinitely for a database or external service, it may remain alive without processing new jobs.
Consider configuring an appropriate timeout:
php artisan queue:work \
--queue=update-vip-service \
--sleep=3 \
--tries=3 \
--timeout=60
The timeout should be coordinated with the queue connection’s retry_after setting so that a job is not released for retry while the original worker is still executing it.
6. Managing Laravel Queue Workers with Supervisor
If you are already using Supervisor, you generally do not need to manually manage queue worker processes.
Supervisor is responsible for:
- Starting workers automatically.
- Restarting workers after unexpected exits.
- Keeping the configured number of workers running.
- Managing worker logs.
- Controlling worker processes.
Laravel queue workers and Supervisor serve complementary purposes.
Laravel workers continuously consume jobs, while Supervisor ensures that the workers remain available.
Why use Supervisor instead of Cron?
A queue worker is intended to be a long-running process.
Putting the following command directly into Cron is not a good approach:
php artisan queue:work
Cron is designed to execute scheduled commands, not continuously supervise background workers.
Supervisor is a better choice because it monitors process health and automatically restarts workers when necessary.
Example Supervisor configuration
Create a configuration file:
/etc/supervisor/conf.d/laravel-vip-worker.conf
Example:
[program:laravel-vip-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work --queue=update-vip-service --sleep=3 --tries=3 --timeout=60 --max-jobs=1000 --memory=128
autostart=true
autorestart=true
user=nobody
numprocs=2
redirect_stderr=true
stdout_logfile=/var/log/supervisor/vip-worker.log
Important settings:
| Setting | Description |
|---|---|
autostart | Automatically start workers when Supervisor starts. |
autorestart | Restart workers when they exit unexpectedly or normally. |
user | User account used to execute the worker. |
numprocs | Number of worker processes to start. |
--timeout=60 | Maximum execution time for an individual job. |
--max-jobs=1000 | Restart the worker after processing 1,000 jobs. |
--memory=128 | Restart the worker when its memory usage exceeds the configured threshold. |
After updating the configuration:
supervisorctl reread
supervisorctl update
Check the worker status:
supervisorctl status
You can also restart a specific program:
supervisorctl restart laravel-vip-worker:*
Supervisor will start replacement workers when the previous ones exit.
Do you need multiple queue workers?
Not necessarily.
The numprocs setting controls how many worker processes run simultaneously.
A reasonable starting point depends on workload:
| Workload | Suggested workers | Considerations |
|---|---|---|
| Low-frequency tasks | 1–2 | Usually sufficient for occasional jobs. |
| Moderate workloads | 2–4 | Provides additional concurrency. |
| High-frequency or slow I/O tasks | 4–8 | Allows more jobs to run concurrently. |
These are starting points, not universal recommendations.
Each worker consumes memory independently, although some memory regions may be shared.
For a small server, running too many workers can waste RAM without providing meaningful performance improvements.
Start with a small number of workers and increase it only when queue throughput or job latency justifies the additional resource consumption.
7. A Real-World Root Cause: Database Connection Failures
During the troubleshooting process described in this article, the underlying issue was eventually identified as a database connection failure.
This explains why multiple Laravel processes could remain alive unexpectedly.
How database failures affect schedule:run
Laravel scheduler initialization and scheduled tasks may need to access the database or cache.
If the database is unavailable, these operations can block while waiting for connection attempts or network timeouts.
Because Cron continues launching schedule:run every minute, multiple scheduler processes may accumulate.
How database failures affect queue:work
Queue workers may also depend on database connectivity.
For example:
- A database-backed queue needs database access to retrieve jobs.
- A job may execute SQL queries.
- A job may call an external service and subsequently update database records.
When database connectivity fails, a long-running worker may become blocked or encounter repeated exceptions.
The important distinction is that a queue worker normally remains alive by design. Its continued existence is not itself evidence of a problem.
The actual problem is whether it can continue processing jobs successfully.
Recommended checks
When database connectivity is restored, inspect the relevant workers and scheduler processes.
You can request a graceful restart of Laravel queue workers:
php artisan queue:restart
If you use Supervisor, it will automatically start replacement workers when the old ones exit.
Also inspect the database connection configuration and ensure that appropriate connection and query timeouts are configured for your environment.
Do not assume that a single PDO timeout setting controls every possible database operation or network failure.
8. Useful Commands for Daily Process Troubleshooting
The following commands are particularly useful when investigating Linux processes.
| Purpose | Command |
|---|---|
| Show processes and threads | htop |
| Toggle thread visibility | Press H in htop |
| Show process start time and elapsed time | ps -eo pid,lstart,etime,cmd |
| Inspect a process’s cgroup | cat /proc/PID/cgroup |
| Show a process hierarchy | pstree -sp PID |
| Display complete process commands | ps aux |
| Find Laravel Artisan processes | pgrep -af artisan |
| Find specific queue workers | pgrep -af queue:work |
| List Docker containers | docker ps |
| Find a container by ID | docker ps --filter "id=CONTAINER_ID" |
| Check Supervisor processes | supervisorctl status |
| Restart Laravel queue workers | php artisan queue:restart |
Replace PID and CONTAINER_ID with the actual process ID and container ID.
Conclusion
Investigating high memory usage on a Linux server requires understanding the difference between processes, threads, and long-running background workers.
Several important lessons from this troubleshooting experience are worth remembering:
- Multiple
dockerdentries may represent threads sharing one process memory space rather than independent Docker daemons. - PHP-FPM workers are independent processes, but shared memory means their RSS values should not simply be added together.
/proc/PID/cgroupis a useful way to determine whether a process belongs to Docker or a host-level systemd service.- Laravel’s
schedule:runshould normally finish quickly. Accumulating instances often indicate blocked initialization or scheduled tasks that take too long. withoutOverlapping()prevents overlapping scheduled tasks, but does not prevent Cron from launching another scheduler process.- Laravel queue workers are designed to run continuously. Their presence in
htopis normal when they are managed by Supervisor. - Supervisor should manage the lifecycle and number of queue workers instead of relying on Cron to launch permanent background processes.
- Database connectivity problems can affect multiple background services simultaneously, making them appear to have unrelated process-management problems.
When troubleshooting server performance, do not immediately kill processes just because they consume memory or remain alive for a long time.
First identify what they do, how they were started, whether they are managed by another service, and what they are waiting for.
Understanding these details makes it much easier to identify the actual root cause and avoid introducing additional problems while fixing the original one.
