1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
4 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5 This file is generated from xml source: DO NOT EDIT
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8 <title>Apache Performance Tuning - Apache HTTP Server</title>
9 <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
10 <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
11 <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../style/css/prettify.css" />
12 <script src="../style/scripts/prettify.js" type="text/javascript">
15 <link href="../images/favicon.ico" rel="shortcut icon" /></head>
16 <body id="manual-page"><div id="page-header">
17 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
18 <p class="apache">Apache HTTP Server Version 2.5</p>
19 <img alt="" src="../images/feather.gif" /></div>
20 <div class="up"><a href="./"><img title="<-" alt="<-" src="../images/left.gif" /></a></div>
22 <a href="http://www.apache.org/">Apache</a> > <a href="http://httpd.apache.org/">HTTP Server</a> > <a href="http://httpd.apache.org/docs/">Documentation</a> > <a href="../">Version 2.5</a> > <a href="./">Miscellaneous Documentation</a></div><div id="page-content"><div id="preamble"><h1>Apache Performance Tuning</h1>
24 <p><span>Available Languages: </span><a href="../en/misc/perf-tuning.html" title="English"> en </a> |
25 <a href="../fr/misc/perf-tuning.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
26 <a href="../ko/misc/perf-tuning.html" hreflang="ko" rel="alternate" title="Korean"> ko </a> |
27 <a href="../tr/misc/perf-tuning.html" hreflang="tr" rel="alternate" title="Türkçe"> tr </a></p>
31 <p>Apache 2.x is a general-purpose webserver, designed to
32 provide a balance of flexibility, portability, and performance.
33 Although it has not been designed specifically to set benchmark
34 records, Apache 2.x is capable of high performance in many
35 real-world situations.</p>
37 <p>Compared to Apache 1.3, release 2.x contains many additional
38 optimizations to increase throughput and scalability. Most of
39 these improvements are enabled by default. However, there are
40 compile-time and run-time configuration choices that can
41 significantly affect performance. This document describes the
42 options that a server administrator can configure to tune the
43 performance of an Apache 2.x installation. Some of these
44 configuration options enable the httpd to better take advantage
45 of the capabilities of the hardware and OS, while others allow
46 the administrator to trade functionality for speed.</p>
49 <div id="quickview"><ul id="toc"><li><img alt="" src="../images/down.gif" /> <a href="#hardware">Hardware and Operating System Issues</a></li>
50 <li><img alt="" src="../images/down.gif" /> <a href="#runtime">Run-Time Configuration Issues</a></li>
51 <li><img alt="" src="../images/down.gif" /> <a href="#compiletime">Compile-Time Configuration Issues</a></li>
52 <li><img alt="" src="../images/down.gif" /> <a href="#trace">Appendix: Detailed Analysis of a Trace</a></li>
53 </ul><ul class="seealso"><li><a href="#comments_section">Comments</a></li></ul></div>
54 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
56 <h2><a name="hardware" id="hardware">Hardware and Operating System Issues</a></h2>
60 <p>The single biggest hardware issue affecting webserver
61 performance is RAM. A webserver should never ever have to swap,
62 as swapping increases the latency of each request beyond a point
63 that users consider "fast enough". This causes users to hit
64 stop and reload, further increasing the load. You can, and
65 should, control the <code class="directive"><a href="../mod/mpm_common.html#maxrequestworkers">MaxRequestWorkers</a></code> setting so that your server
66 does not spawn so many children it starts swapping. This procedure
67 for doing this is simple: determine the size of your average Apache
68 process, by looking at your process list via a tool such as
69 <code>top</code>, and divide this into your total available memory,
70 leaving some room for other processes.</p>
72 <p>Beyond that the rest is mundane: get a fast enough CPU, a
73 fast enough network card, and fast enough disks, where "fast
74 enough" is something that needs to be determined by
77 <p>Operating system choice is largely a matter of local
78 concerns. But some guidelines that have proven generally
83 <p>Run the latest stable release and patchlevel of the
84 operating system that you choose. Many OS suppliers have
85 introduced significant performance improvements to their
86 TCP stacks and thread libraries in recent years.</p>
90 <p>If your OS supports a <code>sendfile(2)</code> system
91 call, make sure you install the release and/or patches
92 needed to enable it. (With Linux, for example, this means
93 using Linux 2.4 or later. For early releases of Solaris 8,
94 you may need to apply a patch.) On systems where it is
95 available, <code>sendfile</code> enables Apache 2 to deliver
96 static content faster and with lower CPU utilization.</p>
100 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
101 <div class="section">
102 <h2><a name="runtime" id="runtime">Run-Time Configuration Issues</a></h2>
106 <table class="related"><tr><th>Related Modules</th><th>Related Directives</th></tr><tr><td><ul><li><code class="module"><a href="../mod/mod_dir.html">mod_dir</a></code></li><li><code class="module"><a href="../mod/mpm_common.html">mpm_common</a></code></li><li><code class="module"><a href="../mod/mod_status.html">mod_status</a></code></li></ul></td><td><ul><li><code class="directive"><a href="../mod/core.html#allowoverride">AllowOverride</a></code></li><li><code class="directive"><a href="../mod/mod_dir.html#directoryindex">DirectoryIndex</a></code></li><li><code class="directive"><a href="../mod/core.html#hostnamelookups">HostnameLookups</a></code></li><li><code class="directive"><a href="../mod/core.html#enablemmap">EnableMMAP</a></code></li><li><code class="directive"><a href="../mod/core.html#enablesendfile">EnableSendfile</a></code></li><li><code class="directive"><a href="../mod/core.html#keepalivetimeout">KeepAliveTimeout</a></code></li><li><code class="directive"><a href="../mod/prefork.html#maxspareservers">MaxSpareServers</a></code></li><li><code class="directive"><a href="../mod/prefork.html#minspareservers">MinSpareServers</a></code></li><li><code class="directive"><a href="../mod/core.html#options">Options</a></code></li><li><code class="directive"><a href="../mod/mpm_common.html#startservers">StartServers</a></code></li></ul></td></tr></table>
108 <h3><a name="dns" id="dns">HostnameLookups and other DNS considerations</a></h3>
112 <p>Prior to Apache 1.3, <code class="directive"><a href="../mod/core.html#hostnamelookups">HostnameLookups</a></code> defaulted to <code>On</code>.
113 This adds latency to every request because it requires a
114 DNS lookup to complete before the request is finished. In
115 Apache 1.3 this setting defaults to <code>Off</code>. If you need
116 to have addresses in your log files resolved to hostnames, use the
117 <code class="program"><a href="../programs/logresolve.html">logresolve</a></code>
118 program that comes with Apache, or one of the numerous log
119 reporting packages which are available.</p>
121 <p>It is recommended that you do this sort of postprocessing of
122 your log files on some machine other than the production web
123 server machine, in order that this activity not adversely affect
124 server performance.</p>
126 <p>If you use any <code><code class="directive"><a href="../mod/mod_access_compat.html#allow">Allow</a></code> from domain</code> or <code><code class="directive"><a href="../mod/mod_access_compat.html#deny">Deny</a></code> from domain</code>
127 directives (i.e., using a hostname, or a domain name, rather than
128 an IP address) then you will pay for
129 two DNS lookups (a reverse, followed by a forward lookup
130 to make sure that the reverse is not being spoofed). For best
131 performance, therefore, use IP addresses, rather than names, when
132 using these directives, if possible.</p>
134 <p>Note that it's possible to scope the directives, such as
135 within a <code><Location /server-status></code> section.
136 In this case the DNS lookups are only performed on requests
137 matching the criteria. Here's an example which disables lookups
138 except for <code>.html</code> and <code>.cgi</code> files:</p>
140 <pre class="prettyprint lang-config">
142 <Files ~ "\.(html|cgi)$">
148 <p>But even still, if you just need DNS names in some CGIs you
149 could consider doing the <code>gethostbyname</code> call in the
150 specific CGIs that need it.</p>
154 <h3><a name="symlinks" id="symlinks">FollowSymLinks and SymLinksIfOwnerMatch</a></h3>
158 <p>Wherever in your URL-space you do not have an <code>Options
159 FollowSymLinks</code>, or you do have an <code>Options
160 SymLinksIfOwnerMatch</code> Apache will have to issue extra
161 system calls to check up on symlinks. One extra call per
162 filename component. For example, if you had:</p>
164 <pre class="prettyprint lang-config">
165 DocumentRoot /www/htdocs
167 Options SymLinksIfOwnerMatch
172 <p>and a request is made for the URI <code>/index.html</code>.
173 Then Apache will perform <code>lstat(2)</code> on
174 <code>/www</code>, <code>/www/htdocs</code>, and
175 <code>/www/htdocs/index.html</code>. The results of these
176 <code>lstats</code> are never cached, so they will occur on
177 every single request. If you really desire the symlinks
178 security checking you can do something like this:</p>
180 <pre class="prettyprint lang-config">
181 DocumentRoot /www/htdocs
183 Options FollowSymLinks
186 <Directory /www/htdocs>
187 Options -FollowSymLinks +SymLinksIfOwnerMatch
192 <p>This at least avoids the extra checks for the
193 <code class="directive"><a href="../mod/core.html#documentroot">DocumentRoot</a></code> path.
194 Note that you'll need to add similar sections if you
195 have any <code class="directive"><a href="../mod/mod_alias.html#alias">Alias</a></code> or
196 <code class="directive"><a href="../mod/mod_rewrite.html#rewriterule">RewriteRule</a></code> paths
197 outside of your document root. For highest performance,
198 and no symlink protection, set <code>FollowSymLinks</code>
199 everywhere, and never set <code>SymLinksIfOwnerMatch</code>.</p>
203 <h3><a name="htacess" id="htacess">AllowOverride</a></h3>
207 <p>Wherever in your URL-space you allow overrides (typically
208 <code>.htaccess</code> files) Apache will attempt to open
209 <code>.htaccess</code> for each filename component. For
212 <pre class="prettyprint lang-config">
213 DocumentRoot /www/htdocs
220 <p>and a request is made for the URI <code>/index.html</code>.
221 Then Apache will attempt to open <code>/.htaccess</code>,
222 <code>/www/.htaccess</code>, and
223 <code>/www/htdocs/.htaccess</code>. The solutions are similar
224 to the previous case of <code>Options FollowSymLinks</code>.
225 For highest performance use <code>AllowOverride None</code>
226 everywhere in your filesystem.</p>
230 <h3><a name="negotiation" id="negotiation">Negotiation</a></h3>
234 <p>If at all possible, avoid content-negotiation if you're
235 really interested in every last ounce of performance. In
236 practice the benefits of negotiation outweigh the performance
237 penalties. There's one case where you can speed up the server.
238 Instead of using a wildcard such as:</p>
240 <pre class="prettyprint lang-config">DirectoryIndex index</pre>
243 <p>Use a complete list of options:</p>
245 <pre class="prettyprint lang-config">DirectoryIndex index.cgi index.pl index.shtml index.html</pre>
248 <p>where you list the most common choice first.</p>
250 <p>Also note that explicitly creating a <code>type-map</code>
251 file provides better performance than using
252 <code>MultiViews</code>, as the necessary information can be
253 determined by reading this single file, rather than having to
254 scan the directory for files.</p>
256 <p>If your site needs content negotiation consider using
257 <code>type-map</code> files, rather than the <code>Options
258 MultiViews</code> directive to accomplish the negotiation. See the
259 <a href="../content-negotiation.html">Content Negotiation</a>
260 documentation for a full discussion of the methods of negotiation,
261 and instructions for creating <code>type-map</code> files.</p>
265 <h3>Memory-mapping</h3>
269 <p>In situations where Apache 2.x needs to look at the contents
270 of a file being delivered--for example, when doing server-side-include
271 processing--it normally memory-maps the file if the OS supports
272 some form of <code>mmap(2)</code>.</p>
274 <p>On some platforms, this memory-mapping improves performance.
275 However, there are cases where memory-mapping can hurt the performance
276 or even the stability of the httpd:</p>
280 <p>On some operating systems, <code>mmap</code> does not scale
281 as well as <code>read(2)</code> when the number of CPUs increases.
282 On multiprocessor Solaris servers, for example, Apache 2.x sometimes
283 delivers server-parsed files faster when <code>mmap</code> is disabled.</p>
287 <p>If you memory-map a file located on an NFS-mounted filesystem
288 and a process on another NFS client machine deletes or truncates
289 the file, your process may get a bus error the next time it tries
290 to access the mapped file content.</p>
294 <p>For installations where either of these factors applies, you
295 should use <code>EnableMMAP off</code> to disable the memory-mapping
296 of delivered files. (Note: This directive can be overridden on
297 a per-directory basis.)</p>
305 <p>In situations where Apache 2.x can ignore the contents of the file
306 to be delivered -- for example, when serving static file content --
307 it normally uses the kernel sendfile support the file if the OS
308 supports the <code>sendfile(2)</code> operation.</p>
310 <p>On most platforms, using sendfile improves performance by eliminating
311 separate read and send mechanics. However, there are cases where using
312 sendfile can harm the stability of the httpd:</p>
316 <p>Some platforms may have broken sendfile support that the build
317 system did not detect, especially if the binaries were built on
318 another box and moved to such a machine with broken sendfile support.</p>
321 <p>With an NFS-mounted filesystem, the kernel may be unable
322 to reliably serve the network file through its own cache.</p>
326 <p>For installations where either of these factors applies, you
327 should use <code>EnableSendfile off</code> to disable sendfile
328 delivery of file contents. (Note: This directive can be overridden
329 on a per-directory basis.)</p>
333 <h3><a name="process" id="process">Process Creation</a></h3>
337 <p>Prior to Apache 1.3 the <code class="directive"><a href="../mod/prefork.html#minspareservers">MinSpareServers</a></code>, <code class="directive"><a href="../mod/prefork.html#maxspareservers">MaxSpareServers</a></code>, and <code class="directive"><a href="../mod/mpm_common.html#startservers">StartServers</a></code> settings all had drastic effects on
338 benchmark results. In particular, Apache required a "ramp-up"
339 period in order to reach a number of children sufficient to serve
340 the load being applied. After the initial spawning of
341 <code class="directive"><a href="../mod/mpm_common.html#startservers">StartServers</a></code> children,
342 only one child per second would be created to satisfy the
343 <code class="directive"><a href="../mod/prefork.html#minspareservers">MinSpareServers</a></code>
344 setting. So a server being accessed by 100 simultaneous
345 clients, using the default <code class="directive"><a href="../mod/mpm_common.html#startservers">StartServers</a></code> of <code>5</code> would take on
346 the order 95 seconds to spawn enough children to handle
347 the load. This works fine in practice on real-life servers,
348 because they aren't restarted frequently. But does really
349 poorly on benchmarks which might only run for ten minutes.</p>
351 <p>The one-per-second rule was implemented in an effort to
352 avoid swamping the machine with the startup of new children. If
353 the machine is busy spawning children it can't service
354 requests. But it has such a drastic effect on the perceived
355 performance of Apache that it had to be replaced. As of Apache
356 1.3, the code will relax the one-per-second rule. It will spawn
357 one, wait a second, then spawn two, wait a second, then spawn
358 four, and it will continue exponentially until it is spawning
359 32 children per second. It will stop whenever it satisfies the
360 <code class="directive"><a href="../mod/prefork.html#minspareservers">MinSpareServers</a></code>
363 <p>This appears to be responsive enough that it's almost
364 unnecessary to twiddle the <code class="directive"><a href="../mod/prefork.html#minspareservers">MinSpareServers</a></code>, <code class="directive"><a href="../mod/prefork.html#maxspareservers">MaxSpareServers</a></code> and <code class="directive"><a href="../mod/mpm_common.html#startservers">StartServers</a></code> knobs. When more than 4 children are
365 spawned per second, a message will be emitted to the
366 <code class="directive"><a href="../mod/core.html#errorlog">ErrorLog</a></code>. If you
367 see a lot of these errors then consider tuning these settings.
368 Use the <code class="module"><a href="../mod/mod_status.html">mod_status</a></code> output as a guide.</p>
370 <p>Related to process creation is process death induced by the
371 <code class="directive"><a href="../mod/mpm_common.html#maxconnectionsperchild">MaxConnectionsPerChild</a></code>
372 setting. By default this is <code>0</code>,
373 which means that there is no limit to the number of connections
374 handled per child. If your configuration currently has this set
375 to some very low number, such as <code>30</code>, you may want to bump this
376 up significantly. If you are running SunOS or an old version of
377 Solaris, limit this to <code>10000</code> or so because of memory leaks.</p>
379 <p>When keep-alives are in use, children will be kept busy
380 doing nothing waiting for more requests on the already open
381 connection. The default <code class="directive"><a href="../mod/core.html#keepalivetimeout">KeepAliveTimeout</a></code> of <code>5</code>
382 seconds attempts to minimize this effect. The tradeoff here is
383 between network bandwidth and server resources. In no event
384 should you raise this above about <code>60</code> seconds, as <a href="http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-95-4.html">
385 most of the benefits are lost</a>.</p>
389 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
390 <div class="section">
391 <h2><a name="compiletime" id="compiletime">Compile-Time Configuration Issues</a></h2>
395 <h3>Choosing an MPM</h3>
399 <p>Apache 2.x supports pluggable concurrency models, called
400 <a href="../mpm.html">Multi-Processing Modules</a> (MPMs).
401 When building Apache, you must choose an MPM to use. There
402 are platform-specific MPMs for some platforms:
403 <code class="module"><a href="../mod/mpm_netware.html">mpm_netware</a></code>,
404 <code class="module"><a href="../mod/mpmt_os2.html">mpmt_os2</a></code>, and <code class="module"><a href="../mod/mpm_winnt.html">mpm_winnt</a></code>. For
405 general Unix-type systems, there are several MPMs from which
406 to choose. The choice of MPM can affect the speed and scalability
411 <li>The <code class="module"><a href="../mod/worker.html">worker</a></code> MPM uses multiple child
412 processes with many threads each. Each thread handles
413 one connection at a time. Worker generally is a good
414 choice for high-traffic servers because it has a smaller
415 memory footprint than the prefork MPM.</li>
417 <li>The <code class="module"><a href="../mod/event.html">event</a></code> MPM is threaded like the
418 Worker MPM, but is designed to allow more requests to be
419 served simultaneously by passing off some processing work
420 to supporting threads, freeing up the main threads to work
421 on new requests.</li>
423 <li>The <code class="module"><a href="../mod/prefork.html">prefork</a></code> MPM uses multiple child
424 processes with one thread each. Each process handles
425 one connection at a time. On many systems, prefork is
426 comparable in speed to worker, but it uses more memory.
427 Prefork's threadless design has advantages over worker
428 in some situations: it can be used with non-thread-safe
429 third-party modules, and it is easier to debug on platforms
430 with poor thread debugging support.</li>
434 <p>For more information on these and other MPMs, please
435 see the MPM <a href="../mpm.html">documentation</a>.</p>
439 <h3><a name="modules" id="modules">Modules</a></h3>
443 <p>Since memory usage is such an important consideration in
444 performance, you should attempt to eliminate modules that you are
445 not actually using. If you have built the modules as <a href="../dso.html">DSOs</a>, eliminating modules is a simple
446 matter of commenting out the associated <code class="directive"><a href="../mod/mod_so.html#loadmodule">LoadModule</a></code> directive for that module.
447 This allows you to experiment with removing modules, and seeing
448 if your site still functions in their absence.</p>
450 <p>If, on the other hand, you have modules statically linked
451 into your Apache binary, you will need to recompile Apache in
452 order to remove unwanted modules.</p>
454 <p>An associated question that arises here is, of course, what
455 modules you need, and which ones you don't. The answer here
456 will, of course, vary from one web site to another. However, the
457 <em>minimal</em> list of modules which you can get by with tends
458 to include <code class="module"><a href="../mod/mod_mime.html">mod_mime</a></code>, <code class="module"><a href="../mod/mod_dir.html">mod_dir</a></code>,
459 and <code class="module"><a href="../mod/mod_log_config.html">mod_log_config</a></code>. <code>mod_log_config</code> is,
460 of course, optional, as you can run a web site without log
461 files. This is, however, not recommended.</p>
465 <h3>Atomic Operations</h3>
469 <p>Some modules, such as <code class="module"><a href="../mod/mod_cache.html">mod_cache</a></code> and
470 recent development builds of the worker MPM, use APR's
471 atomic API. This API provides atomic operations that can
472 be used for lightweight thread synchronization.</p>
474 <p>By default, APR implements these operations using the
475 most efficient mechanism available on each target
476 OS/CPU platform. Many modern CPUs, for example, have
477 an instruction that does an atomic compare-and-swap (CAS)
478 operation in hardware. On some platforms, however, APR
479 defaults to a slower, mutex-based implementation of the
480 atomic API in order to ensure compatibility with older
481 CPU models that lack such instructions. If you are
482 building Apache for one of these platforms, and you plan
483 to run only on newer CPUs, you can select a faster atomic
484 implementation at build time by configuring Apache with
485 the <code>--enable-nonportable-atomics</code> option:</p>
487 <div class="example"><p><code>
489 ./configure --with-mpm=worker --enable-nonportable-atomics=yes
492 <p>The <code>--enable-nonportable-atomics</code> option is
493 relevant for the following platforms:</p>
497 <li>Solaris on SPARC<br />
498 By default, APR uses mutex-based atomics on Solaris/SPARC.
499 If you configure with <code>--enable-nonportable-atomics</code>,
500 however, APR generates code that uses a SPARC v8plus opcode for
501 fast hardware compare-and-swap. If you configure Apache with
502 this option, the atomic operations will be more efficient
503 (allowing for lower CPU utilization and higher concurrency),
504 but the resulting executable will run only on UltraSPARC
508 <li>Linux on x86<br />
509 By default, APR uses mutex-based atomics on Linux. If you
510 configure with <code>--enable-nonportable-atomics</code>,
511 however, APR generates code that uses a 486 opcode for fast
512 hardware compare-and-swap. This will result in more efficient
513 atomic operations, but the resulting executable will run only
514 on 486 and later chips (and not on 386).
521 <h3>mod_status and ExtendedStatus On</h3>
525 <p>If you include <code class="module"><a href="../mod/mod_status.html">mod_status</a></code> and you also set
526 <code>ExtendedStatus On</code> when building and running
527 Apache, then on every request Apache will perform two calls to
528 <code>gettimeofday(2)</code> (or <code>times(2)</code>
529 depending on your operating system), and (pre-1.3) several
530 extra calls to <code>time(2)</code>. This is all done so that
531 the status report contains timing indications. For highest
532 performance, set <code>ExtendedStatus off</code> (which is the
537 <h3>accept Serialization - multiple sockets</h3>
541 <div class="warning"><h3>Warning:</h3>
542 <p>This section has not been fully updated
543 to take into account changes made in the 2.x version of the
544 Apache HTTP Server. Some of the information may still be
545 relevant, but please use it with care.</p>
548 <p>This discusses a shortcoming in the Unix socket API. Suppose
549 your web server uses multiple <code class="directive"><a href="../mod/mpm_common.html#listen">Listen</a></code> statements to listen on either multiple
550 ports or multiple addresses. In order to test each socket
551 to see if a connection is ready Apache uses
552 <code>select(2)</code>. <code>select(2)</code> indicates that a
553 socket has <em>zero</em> or <em>at least one</em> connection
554 waiting on it. Apache's model includes multiple children, and
555 all the idle ones test for new connections at the same time. A
556 naive implementation looks something like this (these examples
557 do not match the code, they're contrived for pedagogical
560 <pre class="prettyprint lang-c">
565 FD_ZERO (&accept_fds);
566 for (i = first_socket; i <= last_socket; ++i) {
567 FD_SET (i, &accept_fds);
569 rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
570 if (rc < 1) continue;
572 for (i = first_socket; i <= last_socket; ++i) {
573 if (FD_ISSET (i, &accept_fds)) {
574 new_connection = accept (i, NULL, NULL);
575 if (new_connection != -1) break;
578 if (new_connection != -1) break;
580 process_the(new_connection);
585 <p>But this naive implementation has a serious starvation problem.
586 Recall that multiple children execute this loop at the same
587 time, and so multiple children will block at
588 <code>select</code> when they are in between requests. All
589 those blocked children will awaken and return from
590 <code>select</code> when a single request appears on any socket
591 (the number of children which awaken varies depending on the
592 operating system and timing issues). They will all then fall
593 down into the loop and try to <code>accept</code> the
594 connection. But only one will succeed (assuming there's still
595 only one connection ready), the rest will be <em>blocked</em>
596 in <code>accept</code>. This effectively locks those children
597 into serving requests from that one socket and no other
598 sockets, and they'll be stuck there until enough new requests
599 appear on that socket to wake them all up. This starvation
600 problem was first documented in <a href="http://bugs.apache.org/index/full/467">PR#467</a>. There
601 are at least two solutions.</p>
603 <p>One solution is to make the sockets non-blocking. In this
604 case the <code>accept</code> won't block the children, and they
605 will be allowed to continue immediately. But this wastes CPU
606 time. Suppose you have ten idle children in
607 <code>select</code>, and one connection arrives. Then nine of
608 those children will wake up, try to <code>accept</code> the
609 connection, fail, and loop back into <code>select</code>,
610 accomplishing nothing. Meanwhile none of those children are
611 servicing requests that occurred on other sockets until they
612 get back up to the <code>select</code> again. Overall this
613 solution does not seem very fruitful unless you have as many
614 idle CPUs (in a multiprocessor box) as you have idle children,
615 not a very likely situation.</p>
617 <p>Another solution, the one used by Apache, is to serialize
618 entry into the inner loop. The loop looks like this
619 (differences highlighted):</p>
621 <pre class="prettyprint lang-c">
623 <strong>accept_mutex_on ();</strong>
627 FD_ZERO (&accept_fds);
628 for (i = first_socket; i <= last_socket; ++i) {
629 FD_SET (i, &accept_fds);
631 rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL);
632 if (rc < 1) continue;
634 for (i = first_socket; i <= last_socket; ++i) {
635 if (FD_ISSET (i, &accept_fds)) {
636 new_connection = accept (i, NULL, NULL);
637 if (new_connection != -1) break;
640 if (new_connection != -1) break;
642 <strong>accept_mutex_off ();</strong>
643 process the new_connection;
648 <p><a id="serialize" name="serialize">The functions</a>
649 <code>accept_mutex_on</code> and <code>accept_mutex_off</code>
650 implement a mutual exclusion semaphore. Only one child can have
651 the mutex at any time. There are several choices for
652 implementing these mutexes. The choice is defined in
653 <code>src/conf.h</code> (pre-1.3) or
654 <code>src/include/ap_config.h</code> (1.3 or later). Some
655 architectures do not have any locking choice made, on these
656 architectures it is unsafe to use multiple
657 <code class="directive"><a href="../mod/mpm_common.html#listen">Listen</a></code>
660 <p>The <code class="directive"><a href="../mod/core.html#mutex">Mutex</a></code> directive can
661 be used to change the mutex implementation of the
662 <code>mpm-accept</code> mutex at run-time. Special considerations
663 for different mutex implementations are documented with that
666 <p>Another solution that has been considered but never
667 implemented is to partially serialize the loop -- that is, let
668 in a certain number of processes. This would only be of
669 interest on multiprocessor boxes where it's possible multiple
670 children could run simultaneously, and the serialization
671 actually doesn't take advantage of the full bandwidth. This is
672 a possible area of future investigation, but priority remains
673 low because highly parallel web servers are not the norm.</p>
675 <p>Ideally you should run servers without multiple
676 <code class="directive"><a href="../mod/mpm_common.html#listen">Listen</a></code>
677 statements if you want the highest performance.
682 <h3>accept Serialization - single socket</h3>
686 <p>The above is fine and dandy for multiple socket servers, but
687 what about single socket servers? In theory they shouldn't
688 experience any of these same problems because all children can
689 just block in <code>accept(2)</code> until a connection
690 arrives, and no starvation results. In practice this hides
691 almost the same "spinning" behaviour discussed above in the
692 non-blocking solution. The way that most TCP stacks are
693 implemented, the kernel actually wakes up all processes blocked
694 in <code>accept</code> when a single connection arrives. One of
695 those processes gets the connection and returns to user-space,
696 the rest spin in the kernel and go back to sleep when they
697 discover there's no connection for them. This spinning is
698 hidden from the user-land code, but it's there nonetheless.
699 This can result in the same load-spiking wasteful behaviour
700 that a non-blocking solution to the multiple sockets case
703 <p>For this reason we have found that many architectures behave
704 more "nicely" if we serialize even the single socket case. So
705 this is actually the default in almost all cases. Crude
706 experiments under Linux (2.0.30 on a dual Pentium pro 166
707 w/128Mb RAM) have shown that the serialization of the single
708 socket case causes less than a 3% decrease in requests per
709 second over unserialized single-socket. But unserialized
710 single-socket showed an extra 100ms latency on each request.
711 This latency is probably a wash on long haul lines, and only an
712 issue on LANs. If you want to override the single socket
713 serialization you can define
714 <code>SINGLE_LISTEN_UNSERIALIZED_ACCEPT</code> and then
715 single-socket servers will not serialize at all.</p>
719 <h3>Lingering Close</h3>
723 <p>As discussed in <a href="http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-connection-00.txt">
724 draft-ietf-http-connection-00.txt</a> section 8, in order for
725 an HTTP server to <strong>reliably</strong> implement the
726 protocol it needs to shutdown each direction of the
727 communication independently (recall that a TCP connection is
728 bi-directional, each half is independent of the other).</p>
730 <p>When this feature was added to Apache it caused a flurry of
731 problems on various versions of Unix because of a
732 shortsightedness. The TCP specification does not state that the
733 <code>FIN_WAIT_2</code> state has a timeout, but it doesn't prohibit it.
734 On systems without the timeout, Apache 1.2 induces many sockets
735 stuck forever in the <code>FIN_WAIT_2</code> state. In many cases this
736 can be avoided by simply upgrading to the latest TCP/IP patches
737 supplied by the vendor. In cases where the vendor has never
738 released patches (<em>i.e.</em>, SunOS4 -- although folks with
739 a source license can patch it themselves) we have decided to
740 disable this feature.</p>
742 <p>There are two ways of accomplishing this. One is the socket
743 option <code>SO_LINGER</code>. But as fate would have it, this
744 has never been implemented properly in most TCP/IP stacks. Even
745 on those stacks with a proper implementation (<em>i.e.</em>,
746 Linux 2.0.31) this method proves to be more expensive (cputime)
747 than the next solution.</p>
749 <p>For the most part, Apache implements this in a function
750 called <code>lingering_close</code> (in
751 <code>http_main.c</code>). The function looks roughly like
754 <pre class="prettyprint lang-c">
755 void lingering_close (int s)
757 char junk_buffer[2048];
759 /* shutdown the sending side */
762 signal (SIGALRM, lingering_death);
766 select (s for reading, 2 second timeout);
768 if (s is ready for reading) {
769 if (read (s, junk_buffer, sizeof (junk_buffer)) <= 0) {
772 /* just toss away whatever is here */
781 <p>This naturally adds some expense at the end of a connection,
782 but it is required for a reliable implementation. As HTTP/1.1
783 becomes more prevalent, and all connections are persistent,
784 this expense will be amortized over more requests. If you want
785 to play with fire and disable this feature you can define
786 <code>NO_LINGCLOSE</code>, but this is not recommended at all.
787 In particular, as HTTP/1.1 pipelined persistent connections
788 come into use <code>lingering_close</code> is an absolute
789 necessity (and <a href="http://www.w3.org/Protocols/HTTP/Performance/Pipeline.html">
790 pipelined connections are faster</a>, so you want to support
795 <h3>Scoreboard File</h3>
799 <p>Apache's parent and children communicate with each other
800 through something called the scoreboard. Ideally this should be
801 implemented in shared memory. For those operating systems that
802 we either have access to, or have been given detailed ports
803 for, it typically is implemented using shared memory. The rest
804 default to using an on-disk file. The on-disk file is not only
805 slow, but it is unreliable (and less featured). Peruse the
806 <code>src/main/conf.h</code> file for your architecture and
807 look for either <code>USE_MMAP_SCOREBOARD</code> or
808 <code>USE_SHMGET_SCOREBOARD</code>. Defining one of those two
809 (as well as their companions <code>HAVE_MMAP</code> and
810 <code>HAVE_SHMGET</code> respectively) enables the supplied
811 shared memory code. If your system has another type of shared
812 memory, edit the file <code>src/main/http_main.c</code> and add
813 the hooks necessary to use it in Apache. (Send us back a patch
816 <div class="note">Historical note: The Linux port of Apache didn't start to
817 use shared memory until version 1.2 of Apache. This oversight
818 resulted in really poor and unreliable behaviour of earlier
819 versions of Apache on Linux.</div>
823 <h3>DYNAMIC_MODULE_LIMIT</h3>
827 <p>If you have no intention of using dynamically loaded modules
828 (you probably don't if you're reading this and tuning your
829 server for every last ounce of performance) then you should add
830 <code>-DDYNAMIC_MODULE_LIMIT=0</code> when building your
831 server. This will save RAM that's allocated only for supporting
832 dynamically loaded modules.</p>
836 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
837 <div class="section">
838 <h2><a name="trace" id="trace">Appendix: Detailed Analysis of a Trace</a></h2>
842 <p>Here is a system call trace of Apache 2.0.38 with the worker MPM
843 on Solaris 8. This trace was collected using:</p>
845 <div class="example"><p><code>
846 truss -l -p <var>httpd_child_pid</var>.
849 <p>The <code>-l</code> option tells truss to log the ID of the
850 LWP (lightweight process--Solaris' form of kernel-level thread)
851 that invokes each system call.</p>
853 <p>Other systems may have different system call tracing utilities
854 such as <code>strace</code>, <code>ktrace</code>, or <code>par</code>.
855 They all produce similar output.</p>
857 <p>In this trace, a client has requested a 10KB static file
858 from the httpd. Traces of non-static requests or requests
859 with content negotiation look wildly different (and quite ugly
862 <div class="example"><pre>/67: accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...)
863 /67: accept(3, 0x00200BEC, 0x00200C0C, 1) = 9</pre></div>
865 <p>In this trace, the listener thread is running within LWP #67.</p>
867 <div class="note">Note the lack of <code>accept(2)</code> serialization. On this
868 particular platform, the worker MPM uses an unserialized accept by
869 default unless it is listening on multiple ports.</div>
871 <div class="example"><pre>/65: lwp_park(0x00000000, 0) = 0
872 /67: lwp_unpark(65, 1) = 0</pre></div>
874 <p>Upon accepting the connection, the listener thread wakes up
875 a worker thread to do the request processing. In this trace,
876 the worker thread that handles the request is mapped to LWP #65.</p>
878 <div class="example"><pre>/65: getsockname(9, 0x00200BA4, 0x00200BC4, 1) = 0</pre></div>
880 <p>In order to implement virtual hosts, Apache needs to know
881 the local socket address used to accept the connection. It
882 is possible to eliminate this call in many situations (such
883 as when there are no virtual hosts, or when
884 <code class="directive"><a href="../mod/mpm_common.html#listen">Listen</a></code> directives
885 are used which do not have wildcard addresses). But
886 no effort has yet been made to do these optimizations. </p>
888 <div class="example"><pre>/65: brk(0x002170E8) = 0
889 /65: brk(0x002190E8) = 0</pre></div>
891 <p>The <code>brk(2)</code> calls allocate memory from the heap.
892 It is rare to see these in a system call trace, because the httpd
893 uses custom memory allocators (<code>apr_pool</code> and
894 <code>apr_bucket_alloc</code>) for most request processing.
895 In this trace, the httpd has just been started, so it must
896 call <code>malloc(3)</code> to get the blocks of raw memory
897 with which to create the custom memory allocators.</p>
899 <div class="example"><pre>/65: fcntl(9, F_GETFL, 0x00000000) = 2
900 /65: fstat64(9, 0xFAF7B818) = 0
901 /65: getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B910, 2190656) = 0
902 /65: fstat64(9, 0xFAF7B818) = 0
903 /65: getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B914, 2190656) = 0
904 /65: setsockopt(9, 65535, 8192, 0xFAF7B918, 4, 2190656) = 0
905 /65: fcntl(9, F_SETFL, 0x00000082) = 0</pre></div>
907 <p>Next, the worker thread puts the connection to the client (file
908 descriptor 9) in non-blocking mode. The <code>setsockopt(2)</code>
909 and <code>getsockopt(2)</code> calls are a side-effect of how
910 Solaris' libc handles <code>fcntl(2)</code> on sockets.</p>
912 <div class="example"><pre>/65: read(9, " G E T / 1 0 k . h t m".., 8000) = 97</pre></div>
914 <p>The worker thread reads the request from the client.</p>
916 <div class="example"><pre>/65: stat("/var/httpd/apache/httpd-8999/htdocs/10k.html", 0xFAF7B978) = 0
917 /65: open("/var/httpd/apache/httpd-8999/htdocs/10k.html", O_RDONLY) = 10</pre></div>
919 <p>This httpd has been configured with <code>Options FollowSymLinks</code>
920 and <code>AllowOverride None</code>. Thus it doesn't need to
921 <code>lstat(2)</code> each directory in the path leading up to the
922 requested file, nor check for <code>.htaccess</code> files.
923 It simply calls <code>stat(2)</code> to verify that the file:
924 1) exists, and 2) is a regular file, not a directory.</p>
926 <div class="example"><pre>/65: sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C) = 10269</pre></div>
928 <p>In this example, the httpd is able to send the HTTP response
929 header and the requested file with a single <code>sendfilev(2)</code>
930 system call. Sendfile semantics vary among operating systems. On some other
931 systems, it is necessary to do a <code>write(2)</code> or
932 <code>writev(2)</code> call to send the headers before calling
933 <code>sendfile(2)</code>.</p>
935 <div class="example"><pre>/65: write(4, " 1 2 7 . 0 . 0 . 1 - ".., 78) = 78</pre></div>
937 <p>This <code>write(2)</code> call records the request in the
938 access log. Note that one thing missing from this trace is a
939 <code>time(2)</code> call. Unlike Apache 1.3, Apache 2.x uses
940 <code>gettimeofday(3)</code> to look up the time. On some operating
941 systems, like Linux or Solaris, <code>gettimeofday</code> has an
942 optimized implementation that doesn't require as much overhead
943 as a typical system call.</p>
945 <div class="example"><pre>/65: shutdown(9, 1, 1) = 0
946 /65: poll(0xFAF7B980, 1, 2000) = 1
947 /65: read(9, 0xFAF7BC20, 512) = 0
948 /65: close(9) = 0</pre></div>
950 <p>The worker thread does a lingering close of the connection.</p>
952 <div class="example"><pre>/65: close(10) = 0
953 /65: lwp_park(0x00000000, 0) (sleeping...)</pre></div>
955 <p>Finally the worker thread closes the file that it has just delivered
956 and blocks until the listener assigns it another connection.</p>
958 <div class="example"><pre>/67: accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...)</pre></div>
960 <p>Meanwhile, the listener thread is able to accept another connection
961 as soon as it has dispatched this connection to a worker thread (subject
962 to some flow-control logic in the worker MPM that throttles the listener
963 if all the available workers are busy). Though it isn't apparent from
964 this trace, the next <code>accept(2)</code> can (and usually does, under
965 high load conditions) occur in parallel with the worker thread's handling
966 of the just-accepted connection.</p>
969 <div class="bottomlang">
970 <p><span>Available Languages: </span><a href="../en/misc/perf-tuning.html" title="English"> en </a> |
971 <a href="../fr/misc/perf-tuning.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
972 <a href="../ko/misc/perf-tuning.html" hreflang="ko" rel="alternate" title="Korean"> ko </a> |
973 <a href="../tr/misc/perf-tuning.html" hreflang="tr" rel="alternate" title="Türkçe"> tr </a></p>
974 </div><div class="top"><a href="#page-header"><img src="../images/up.gif" alt="top" /></a></div><div class="section"><h2><a id="comments_section" name="comments_section">Comments</a></h2><div class="warning"><strong>This section is experimental!</strong><br />Comments placed here should not be expected
975 to last beyond the testing phase of this system, nor do we in any way guarantee that we'll read them.</div>
976 <div id="disqus_thread">
977 </div><script type="text/javascript"><!--//--><![CDATA[//><!--
979 var disqus_shortname = 'httpd';
980 var disqus_identifier = window.location.href.replace(/(current|trunk)/, "2.4").replace(/\/[a-z]{2}\//, "/").replace(window.location.protocol, "http:") + '.' + lang;
981 if (disqus_identifier.indexOf("httpd.apache.org") != -1) {
983 var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
984 dsq.src = window.location.protocol + '//' + disqus_shortname + '.disqus.com/embed.js';
985 (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
988 var text = document.createTextNode("Comments have been disabled for offline viewing.");
989 document.getElementById('disqus_thread').appendChild(text);
991 //--><!]]></script></div><div id="footer">
992 <p class="apache">Copyright 2012 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
993 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div><script type="text/javascript"><!--//--><![CDATA[//><!--
994 if (typeof(prettyPrint) !== undefined) {