Reducing Memory Usage
From SilverRack - Affordable VPS Hosting - Wiki
Apache can have a huge impact on memory usage, so it's a good way to reduce memory usage on your VPS. The basic idea to reducing Apache memory usage is limit the "Server Pool Size." By default the Apache config will handle many concurrent users, so it has a large server pool size, but if you need to support very many concurrent users, you can turn the settings down. Here's how:
<IfModule mpm_prefork_module> StartServers 2 MinSpareServers 2 MaxSpareServers 5 MaxClients 75 MaxRequestsPerChild 300 </IfModule> <IfModule mpm_worker_module> StartServers 2 MaxClients 75 MinSpareThreads 2 MaxSpareThreads 5 ThreadsPerChild 10 MaxRequestsPerChild 300 </IfModule>
Basically, what I've done above is to tell Apache:
- Don't start so many servers to begin with (
- Don't run too many servers at once (
- Don't keep running servers indefinitely, shut them down after some period of time (
Unfortunately, there's not a lot you can do with MySQL. If you're not using InnoDB tables, you can turn off support for that (just add
skip-innodb to your my.cnf) and it will dramatically reduce memory usage -- that will make the biggest difference.
You can tweak, the Query Cache, but by default MySQL has these set pretty conservatively (usually you would crank them up on a dedicated database server). If you mess with these you run the risk of ruining your database performance.
The other thing that will help, not just with memory usage, but all around performance, is to turn on the slow query log. In your
my.cnf add the following:
log_slow_queries = /path/to/mysql-slow.log long_query_time = 2 log-queries-not-using-indexes
Now you can go back and peruse the slow query log and see which queries are performing poorly. Then go back to your code and optimize them.
Ruby on Rails
A great way to reduce memory usage for Ruby on Rails applications is to run them on Phusion Passenger (mod_rails) and Ruby Enterprise Edition. You can see a 30% reduction in memory usage over an equivalent Mongrel cluster. See the Ruby on Rails page for more on installing and setting up Ruby Enterprise Edition and Passenger (mod_rails).
Here's how you can tune your Passenger installation. Add the following directives to your Apache config:
PassengerMaxPoolSize 2 RailsSpawnMethod smart RackAutoDetect off
PassengerMaxPoolSize limits the number of Passenger instances that run simultaneously (and they can use a lot of memory!). Now for the
RailsSpawnMethod you need to be aware your application may not be compatible -- you'll have to test it and see. Finally, it may not help with memory much, but if you're only running a Rails app, you can tell Passenger to not bother checking for Rack applications. You can read more on optimizing Passenger here