TweetFollow Us on Twitter

Web Performance Tuning

Volume Number: 22 (2006)
Issue Number: 10
Column Tag: Web Performance Tuning

Web Performance Tuning

Supercharge your Web Sites in Minutes!

by Jin Lin, Emmanuel Stein, and Jamie Ferri

Introduction

There are many ways to improve the performance of websites built upon Apache, PHP and MySQL, from simple modification of configuration files to recompilation of the source code with customized settings for your situations. In this article, we will focus on each component of an AMP-based system in turn, and address common bottlenecks with simple solutions that can be readily applied to your particular implementation.

The performance of websites is measured by the speed with which it is able to service HTTP requests. As discussed in the April "Web Benchmarking 101" article, load testing tools like ApacheBench and JMeter can be used to gauge the performance of your web applications. In essence, these tools simulate heavy web traffic by instantiating multiple simultaneous requests, while measuring resultant load and response times. These reports are invaluable when benchmarking a server's response time and throughput across configurations.

Apache Server

RAM is the most important variable that influences the performance of Apache server. As RAM usage goes up, frequent drive swapping increases the latency of HTTP requests. Each httpd process uses around 2-3 MB of RAM when serving static html pages, and as much as 15 MB when serving dynamic pages. Because the memory footprint of Apache processes grow to accommodate the quantity of content being served, they can rapidly take up an amount of RAM equal to the largest and most complicated script on your system. In other words, even if only 1% of your web pages are dynamic, each httpd process will grow to take up in excess of 15 MB of RAM, and will not release resources until the corresponding process dies. Therefore, by properly adjusting the number of httpd processes, the server spawns, as well as their lifespan, you can greatly boost the performance of Apache server.

The following options, within httpd.conf, can be tweaked to improve Apache's use of memory.

  • KeepAlive - Creates persistent connections by keeping child processes busy while waiting for subsequent requests to be sent over the same connections. Persistent connections reduce the overhead for setting up and shutting down multiple HTTP connections. By enabling this option we can dramatically improve the render time for HTML pages with multiple images. Related options include MaxKeepAliveRequests (maximum number of requests that can be sent on a given connection before it is closed), and KeepAliveTimeout (number of seconds Apache waits for the next request before closing connections). Both of these impose a limit on KeepAlive to prevent a client from holding resources too long. Therefore, it is best to set KeepAliveTimeout to a very low value such as 2 seconds. However, if you have more concurrent users than available child processes, or if the server is only serving dynamic pages, using KeepAlive will hurt overall performance and should be disabled.

  • MaxClients - Limits the number of child processes the server can spawn or the number of simultaneous HTTP requests that can be supported. Once this limit is reached, additional attempted connections will be queued up to the number specified in the ListenBacklog directive. The default value for MaxClients is 500. Generally, it should be set to a number big enough to handle as many simultaneous requests as possible, but still small enough to ensure that there is ample physical memory for all processes. This will avoid excessive drive swapping. An easy way to test how many HTTP processes your system can handle is to launch Activity Monitor, enter httpd in the search field and make sure All Processes is selected. This will list the status of every httpd process running on your system (Figure 1). To get the value of MaxClients, divide the amount of available memory by the mean RAM consumption of the Apache processes.



Figure 1. Activity Monitor - find out the RAM usage of httpd processes

  • MaxRequestsPerChild - Sets the maximum number of requests a child process will service before the child process kills itself. This setting can reduce the total memory usage, and prevent memory leaks by forcing child processes to die and restart with a much smaller memory footprint. The default value in Mac OS X is 100,000. You might want to set it to a lower value if you find that some of your httpd processes are using too much memory.

  • MinSpareServers, MaxSpareServers - Regulates how a parent process spawns child processes in order to service requests. Creating child processes is expensive. As long as the server is busy creating more child processes, it won't be able to serve user requests. If your site is event-driven, such that the number of connections fluctuates radically in short periods of time, you should increase the value of MinSpareServers. On the other hand, you should avoid setting MaxSpareServers too high since excess child processes will take up resources unnecessarily.

  • ExtendedStatus - Useful for collecting server statistics such as the status and CPU usage of each child process, the number of requests per second, and more. This setting is enabled by default and is at the expense of extra system calls. With ExtendedStatus enabled, web server statistics can be accessed via http://localhost/server-status. You can also get the status page to refresh itself every N seconds via http://localhost/server-status?refresh=N. This can be very useful for setup, optimization, and debugging. However, when you're not in active testing, you should disable this option to reclaim extra CPU cycles.

Other ways to improve Apache's performance include disabling logs when unnecessary, disable use of .htaccess via AllowOverride none, and eliminating unused modules. Apache Performance Notes (http://httpd.apache.org/docs/1.3/misc/perf-tuning.html) offers additional tips on Apache tuning. If you don't need the extensive feature set offered by Apache, you may want to consider a lightweight alternative. An example is LightTPD <http://www.lighttpd.net/>, whose strength is efficient handling of high traffic volumes on older systems, and which includes many features such as PHP, CGI, SSI, and URL-rewriting.

MySQL

MySQL, as a database server, does a lot of data transfer between disk and CPU. Disk I/O will therefore be the first bottleneck that you are likely to encounter. To decrease disk I/O, the various internal buffers of MySQL use main memory as a cache for data that is on disk. MySQL has global buffers in addition to per-thread buffers. The general rule of thumb is that the main memory available to MySQL should be big enough to handle MySQL's global buffers plus per-thread buffers multiplied by the maximum number of concurrent connections being created. By properly adjusting the amount of memory that MySQL allocates to each of these buffers, you will gain significant performance improvements.

Here are some key parameters in my.cnf that can be used to decrease disk I/O:

Global parameters

  • key_buffer_size - Key buffer is a global buffer that stores MyISAM (the default storage engine) indexes. Every time a block of index values is referenced, it will be loaded into the key buffer. In order to scan a table's index faster, a query reads the relevant indexes from the buffer rather than the disk. Unfortunately, when the buffer is full, some values stored in the buffer must be discarded to make room for new values. It is recommended to set this value between 20% and 50% of the total memory on a dedicated server, or the total size of .MYI files (index files) on a shared server. If you don't have that much memory dedicated to key buffer, you can tune this setting by comparing the Key_reads (number of requests read from disk), and the Key_read_requests (number of requests for a index block) status variables. The ratio of Key_reads to Key_read_requests should be less than 1%. or 1 Key_reads for every 100 or more Key_read_requests. Use the show status like '%key_read%' command to reveal these two values, and use the show variables like '%key_buffer%' command to find out the key buffer size. Note that the key buffer is only for MyISAM tables. Other table types have different parameters for tuning (e.g. innodb_buffer_pool_size for InnoDB tables).

  • table_cache - Limits the maximum number of tables that can be opened at once. With MyISAM tables, each table and index represents a separate file. Because opening and closing files is relatively slow, MySQL puts tables in cache until they are explicitly closed, or the total number of open tables exceeds the table_cache parameter. Increasing the value of table_cache will be helpful if you have a large number of tables on your server. To determine whether the table_cache value needs to be increased, type the following at a mysql prompt:

          show variables like 'table_cache';
          show status like 'open_tables';

    If the value of open_tables is significantly bigger than the value of table_cache, then you should increase the value of table_cache.

  • max_connections - Controls the maximum number of simultaneous client connections. The default value is 100. If your server is very busy, or if the value of the Threads_connected status variable approximates to the value of max_connections, you should increase the value of the latter to allow for more connections.

Per-Client Buffers

Exercise caution when increasing the value of per-client variables as these buffers are allocated on a per connection basis. The value of these buffers should not be too high; otherwise, the performance of MySQL or other processes may suffer due to exorbitant memory consumption.

  • read_buffer_size - Specifies the size of the buffer that is used when a full table scan is performed to store the table data.

  • read_rnd_buffer_size - Determines the size of the buffer that is used in reading records after an intermediate sort.

  • sort_buffer_size - Determines the size of the buffer that is used during read and sort operations.

  • join_buffer_size - Determines the size of the buffer that is used to process joins.

  • max_allowed_packet - The maximum size of the buffer that is used for client communication.

  • tmp_table_size - Specifies the maximum size of temporary tables that can be stored in the memory. If the value is too small, MySQL will place the temporary table on disk. To determine the proper value for tmp_table_size, compare the values of Created_tmp_tables (number of temporary tables that are created), and Created_tmp_disk_tables (number of temporary tables that are placed on disk) status variables. You should increase tmp_table_size if the ratio of Created_tmp_disk_tables and Created_tmp_tables exceeds 2%.

Query Cache

  • query_cache_type, query_cache_size - Determines the operating mode (0 for off, 1 for on, 2 for on demand), and size parameters for query cache. The query cache keeps the results of frequently executed SELECTs in memory so that MySQL doesn't need to access the slow disk-based subsystems. This works as follows: The first time a given SELECT statement is executed, the server remembers the query and the associated results. The next time the server sees that statement, it pulls the results directly from the query cache and returns it to the user. MySQL's query cache is case-sensitive such that, each query must be identical (e.g. no extra spaces). The default value of query_cache_size is set to 0 and effectively disables the cache even if the value of query_cache_type is non-zero. To check out the performance of the query cache and its use of memory, run the following command:

       show status like '%qcache%';
  • Qcache_lowmem_prunes - Counts the number of queries that have been removed from the cache in order to free up memory for caching new queries. This can be used to help determine query cache size. Under certain circumstances, such as when queries retrieve data from a constant table, the query cache isn't very useful and should be disabled.

For a more detailed treatment of MySQL server performance tuning consult <http://dev.mysql.com/books/hpmysql-excerpts/ch06.html>.

PHP

PHP uses a two-part process for generating HTML: each time a PHP script is accessed, it is first compiled into opcode, which is then executed to generate the html. (This workflow can be seen in figure 2). This repeating process of compilation and execution, not only places significant demands on the CPU, but also increases the latency of HTTP requests, especially as scripts grow in complexity. Because it takes much longer to serve a PHP script than a static html page, we can employ various caching schemes to minimize the process of compilation and execution, and thus boost web performance.



Figure 2. PHP script workflow

If your pages change infrequently, you will want to choose a caching mechanism such as Smarty or Cache_Lite to store the entire HTML output of your PHP script. Smarty (http://smarty.php.net/) is a robust template framework, which separates business logic (PHP code), from presentation (HTML templates). Smarty offers the ability to cache all or part of rendered HTML. For information on installation, setup and use, consult the excellent documentation on Smarty's website <http://smarty.php.net/manual/en/>. Because Smarty requires you to restructure your PHP codes, a simpler alternative is Cache_Lite. Cache_Lite provides a solid, easy-to-implement library for solving cache-related issues. It is easy to install via the PEAR (PHP Extension and Application Repository) Package Manager that comes pre-installed with Mac OS X.

To install Cache_Lite, type the following into the terminal: sudo pear install Cache_Lite. Once installed, wrap the following code around your PHP scripts to enable HTML caching:

Listing 1: Cache_Lite code wrapper to enable HTML caching

// Include the Cache_Lite package.
require_once ( "Cache/Lite/Output.php" );
// Define options to control the behavior of 
//    Cache_Lite_Output object.
$options = array(
   'cacheDir' => 'cache/',
   'lifeTime' => 3600,   // expire after 1 hour 
   'pearErrorMode' => CACHE_LITE_ERROR_DIE
   );
// Instantiate Cache_Lite_Output object
$cache = new Cache_Lite_Output($options);
// Test if the cached file is exists.
// If so, use the cached file.
// Otherwise, compile and execute the PHP codes and rendered a 
//   cache file with the ID specified below.
if ( !( $cache -> start ( "index".$q_string ) ) ) {
/*  ***  YOUR PHP CODE HERE  ***  */
// the end of Cache_Lite_Output object
$cache -> end();
   }

You can now run ApacheBench with and without Cache_Lite in order to measure the performance improvement. In this example, I chose to set the number of requests to 1000 (-n 1000), and the number of simultaneous connections to 10 (-c 10). The performance with and without Cache_Lite enabled is seen in figures 3 and 4, respectively.



Figure 3. ab results for the script with Cache_Lite enabled



Figure 4. ab results for the same script without Cache_Lite

As you can see from the two terminal outputs, it took about 12 seconds to serve 1000 requests using 10 simultaneous connections for the script with Cache_Lite enabled, versus 77 seconds for the same script without Cache_Lite. Therefore, the script with the caching system can be served 6 times as fast as the one without. As the size and complexity of your scripts increase, this speed difference will be even greater.

If your page changes more frequently, such as with a stock quote, cached HTML will obviously not be suitable. In this case, you will want to choose an opcode cache. Opcode caches keep compiled PHP scripts in memory to eliminate the need to recompile the script for each subsequent request. Well-known opcode caches include eAccelerator <http://eaccelerator.net/>, PHP Accelerator <http://www.php-accelerator.co.uk/>, Turck MMCache <http://turck-mmcache.sourceforge.net/>, and Alternative PHP Cache <http://pecl.php.net/package/APC>. If you do not wish to go through the trouble to set up opcode cache, you can simply download MAMP (Macintosh, Apache, MySQL, PHP) from <http://www.mamp.info/en/home/>. This packaged solution comes with additional libraries such as eAccelerator, Zend Optimizer, and phpMyAdmin, among others.

You can further improve PHP performance via other methods, such as using output buffering. It is always good practice to ensure clean, optimized code with the aide of profiling tools such as APD and DBG.

Conclusion

In this article we've explored several performance tuning techniques that can be applied individually or in combination to enhance the performance of AMP-based sites. By making changes to the Apache httpd.conf file, adjusting MySQL's memory use, and properly caching PHP generated HTML output, we demonstrated how to achieve significant performance improvement without purchasing additional hardware. Whether you are running a complex content management solution or hosting a personal blog, these practical guidelines will allow you to take your web applications to the next level within minutes.


Jin Lin and Emmanuel Stein are partners in the consulting firm MacVerse, Corp, which offers implementation, system administration, and development services geared towards the enterprise market. You may reach them at <info@macverse.com>.

Jamie Ferri is a research psychologist who spends much of her time developing websites and databases for scientific applications. You can drop her a line at jamie@catcollective.com

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.