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

coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Fantastical 3.8.2 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
iShowU Instant 1.4.14 - Full-featured sc...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more

Latest Forum Discussions

See All

The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »
‘Junkworld’ Is Out Now As This Week’s Ne...
Epic post-apocalyptic tower-defense experience Junkworld () from Ironhide Games is out now on Apple Arcade worldwide. We’ve been covering it for a while now, and even through its soft launches before, but it has returned as an Apple Arcade... | Read more »
Motorsport legends NASCAR announce an up...
NASCAR often gets a bad reputation outside of America, but there is a certain charm to it with its close side-by-side action and its focus on pure speed, but it never managed to really massively break out internationally. Now, there's a chance... | Read more »
Skullgirls Mobile Version 6.0 Update Rel...
I’ve been covering Marie’s upcoming release from Hidden Variable in Skullgirls Mobile (Free) for a while now across the announcement, gameplay | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Share on Facebook Apply Read more
Machine Operator 4 - *Apple* 2nd Shift - Bon...
Machine Operator 4 - Apple 2nd ShiftApply now " Apply now + Start apply with LinkedIn + Apply Now Start + Please wait Date:Sep 22, 2023 Location: Swedesboro, NJ, US, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.