There are cases when you may notice that the memory usage is too high inside your VPS without a specific reason.
This may happen because of how OpenVZ calculates the memory used by your applications, most visible with Java applications or other servers using threads (Apache with mpm_worker or mpm_event).
You can read more here: http://wiki.openvz.org/Stack_size
A solution as explained in the article above is to decrease the stack size since the default value is too high in almost all cases.
Getting the current stack size limit
You can see the current stack size limit (RLIMIT_STACK) by running ulimit -s
command. Result is in kilobytes.
For example, we installed Apache with mpm_worker in a VPS with MaxClients set to 25 and the threads per child set to 25 also. While 25 concurrent requests is not much the memory usage for that Apache spiked to 300MB. That's a little too high.
We then edited /etc/init.d/httpd (on CentOS, for other distributions it may be called apache2) and added: ulimit -s 256 on a separate line in the file, at the beginning like this:
# Source function library.
. /etc/rc.d/init.d/functions
ulimit -s 1024 # Stack size limit is 1M
if [ -f /etc/sysconfig/httpd ]; then
. /etc/sysconfig/httpd
fi
After restarting Apache, the total memory used went down to around 30MB, which is acceptable.
This also works for other applications like MySQL for example.