]> granicus.if.org Git - apache/blob - docs/manual/misc/perf-tuning.html.en
32e46b3e906414f54ac22d4048dd8f2e1f4012b6
[apache] / docs / manual / misc / perf-tuning.html.en
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
7       -->
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">
13 </script>
14
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="&lt;-" alt="&lt;-" src="../images/left.gif" /></a></div>
21 <div id="path">
22 <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://httpd.apache.org/">HTTP Server</a> &gt; <a href="http://httpd.apache.org/docs/">Documentation</a> &gt; <a href="../">Version 2.5</a> &gt; <a href="./">Miscellaneous Documentation</a></div><div id="page-content"><div id="preamble"><h1>Apache Performance Tuning</h1>
23 <div class="toplang">
24 <p><span>Available Languages: </span><a href="../en/misc/perf-tuning.html" title="English">&nbsp;en&nbsp;</a> |
25 <a href="../fr/misc/perf-tuning.html" hreflang="fr" rel="alternate" title="Français">&nbsp;fr&nbsp;</a> |
26 <a href="../ko/misc/perf-tuning.html" hreflang="ko" rel="alternate" title="Korean">&nbsp;ko&nbsp;</a> |
27 <a href="../tr/misc/perf-tuning.html" hreflang="tr" rel="alternate" title="Türkçe">&nbsp;tr&nbsp;</a></p>
28 </div>
29
30
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>
36
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>
47
48   </div>
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>
55 <div class="section">
56 <h2><a name="hardware" id="hardware">Hardware and Operating System Issues</a></h2>
57
58     
59
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>
71
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
75     experimentation.</p>
76
77     <p>Operating system choice is largely a matter of local
78     concerns. But some guidelines that have proven generally
79     useful are:</p>
80
81     <ul>
82       <li>
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>
87       </li>
88
89       <li>
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>
97       </li>
98     </ul>
99
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>
103
104     
105
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>
107
108     <h3><a name="dns" id="dns">HostnameLookups and other DNS considerations</a></h3>
109
110       
111
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>
120
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>
125
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>
133
134       <p>Note that it's possible to scope the directives, such as
135       within a <code>&lt;Location /server-status&gt;</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>
139
140       <pre class="prettyprint lang-config">
141 HostnameLookups off
142 &lt;Files ~ "\.(html|cgi)$"&gt;
143   HostnameLookups on
144 &lt;/Files&gt;
145       </pre>
146
147
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>
151
152     
153
154     <h3><a name="symlinks" id="symlinks">FollowSymLinks and SymLinksIfOwnerMatch</a></h3>
155
156       
157
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>
163
164       <pre class="prettyprint lang-config">
165 DocumentRoot /www/htdocs
166 &lt;Directory /&gt;
167   Options SymLinksIfOwnerMatch
168 &lt;/Directory&gt;
169       </pre>
170
171
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>
179
180       <pre class="prettyprint lang-config">
181 DocumentRoot /www/htdocs
182 &lt;Directory /&gt;
183   Options FollowSymLinks
184 &lt;/Directory&gt;
185
186 &lt;Directory /www/htdocs&gt;
187   Options -FollowSymLinks +SymLinksIfOwnerMatch
188 &lt;/Directory&gt;
189       </pre>
190
191
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>
200
201     
202
203     <h3><a name="htacess" id="htacess">AllowOverride</a></h3>
204
205       
206
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
210       example,</p>
211
212       <pre class="prettyprint lang-config">
213 DocumentRoot /www/htdocs
214 &lt;Directory /&gt;
215   AllowOverride all
216 &lt;/Directory&gt;
217       </pre>
218
219
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>
227
228     
229
230     <h3><a name="negotiation" id="negotiation">Negotiation</a></h3>
231
232       
233
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>
239
240       <pre class="prettyprint lang-config">DirectoryIndex index</pre>
241
242
243       <p>Use a complete list of options:</p>
244
245       <pre class="prettyprint lang-config">DirectoryIndex index.cgi index.pl index.shtml index.html</pre>
246
247
248       <p>where you list the most common choice first.</p>
249
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>
255
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>
262
263     
264
265     <h3>Memory-mapping</h3>
266
267       
268
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>
273
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>
277
278       <ul>
279         <li>
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>
284         </li>
285
286         <li>
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>
291         </li>
292       </ul>
293
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>
298
299     
300
301     <h3>Sendfile</h3>
302
303       
304
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>
309
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>
313
314       <ul>
315         <li>
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>
319         </li>
320         <li>
321           <p>With an NFS-mounted filesystem, the kernel may be unable
322           to reliably serve the network file through its own cache.</p>
323         </li>
324       </ul>
325
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>
330
331     
332
333     <h3><a name="process" id="process">Process Creation</a></h3>
334
335       
336
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>
350
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>
361       setting.</p>
362
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>
369
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>
378
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>
386
387     
388
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>
392
393     
394
395     <h3>Choosing an MPM</h3>
396
397       
398
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
407       of the httpd:</p>
408
409       <ul>
410
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>
416         
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>
422
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>
431
432       </ul>
433
434       <p>For more information on these and other MPMs, please
435       see the MPM <a href="../mpm.html">documentation</a>.</p>
436
437     
438
439     <h3><a name="modules" id="modules">Modules</a></h3>
440
441         
442
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>
449
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>
453
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>
462
463     
464
465     <h3>Atomic Operations</h3>
466
467       
468
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>
473
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>
486
487       <div class="example"><p><code>
488         ./buildconf<br />
489         ./configure --with-mpm=worker --enable-nonportable-atomics=yes
490       </code></p></div>
491
492       <p>The <code>--enable-nonportable-atomics</code> option is
493       relevant for the following platforms:</p>
494
495       <ul>
496
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
505             chips.
506         </li>
507
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).
515         </li>
516
517       </ul>
518
519     
520
521     <h3>mod_status and ExtendedStatus On</h3>
522
523       
524
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
533       default).</p>
534
535     
536
537     <h3>accept Serialization - multiple sockets</h3>
538
539       
540
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>
546     </div>
547
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
558       purposes):</p>
559
560       <pre class="prettyprint lang-c">
561         for (;;) {
562           for (;;) {
563             fd_set accept_fds;
564
565             FD_ZERO (&amp;accept_fds);
566             for (i = first_socket; i &lt;= last_socket; ++i) {
567               FD_SET (i, &amp;accept_fds);
568             }
569             rc = select (last_socket+1, &amp;accept_fds, NULL, NULL, NULL);
570             if (rc &lt; 1) continue;
571             new_connection = -1;
572             for (i = first_socket; i &lt;= last_socket; ++i) {
573               if (FD_ISSET (i, &amp;accept_fds)) {
574                 new_connection = accept (i, NULL, NULL);
575                 if (new_connection != -1) break;
576               }
577             }
578             if (new_connection != -1) break;
579           }
580           process_the(new_connection);
581         }
582       </pre>
583
584
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>
602
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>
616
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>
620
621       <pre class="prettyprint lang-c">
622         for (;;) {
623           <strong>accept_mutex_on ();</strong>
624           for (;;) {
625             fd_set accept_fds;
626             
627             FD_ZERO (&amp;accept_fds);
628             for (i = first_socket; i &lt;= last_socket; ++i) {
629               FD_SET (i, &amp;accept_fds);
630             }
631             rc = select (last_socket+1, &amp;accept_fds, NULL, NULL, NULL);
632             if (rc &lt; 1) continue;
633             new_connection = -1;
634             for (i = first_socket; i &lt;= last_socket; ++i) {
635               if (FD_ISSET (i, &amp;accept_fds)) {
636                 new_connection = accept (i, NULL, NULL);
637                 if (new_connection != -1) break;
638               }
639             }
640             if (new_connection != -1) break;
641           }
642           <strong>accept_mutex_off ();</strong>
643           process the new_connection;
644         }
645       </pre>
646
647
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>
658       directives.</p>
659
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
664       directive.</p>
665
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>
674
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.
678       But read on.</p>
679
680     
681
682     <h3>accept Serialization - single socket</h3>
683
684       
685
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
701       can.</p>
702
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>
716
717     
718
719     <h3>Lingering Close</h3>
720
721       
722
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>
729
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>
741
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>
748
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
752       this:</p>
753
754       <pre class="prettyprint lang-c">
755         void lingering_close (int s)
756         {
757           char junk_buffer[2048];
758           
759           /* shutdown the sending side */
760           shutdown (s, 1);
761
762           signal (SIGALRM, lingering_death);
763           alarm (30);
764
765           for (;;) {
766             select (s for reading, 2 second timeout);
767             if (error) break;
768             if (s is ready for reading) {
769               if (read (s, junk_buffer, sizeof (junk_buffer)) &lt;= 0) {
770                 break;
771               }
772               /* just toss away whatever is here */
773             }
774           }
775           
776           close (s);
777         }
778       </pre>
779
780
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
791       them).</p>
792
793     
794
795     <h3>Scoreboard File</h3>
796
797       
798
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
814       too please.)</p>
815
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>
820
821     
822
823     <h3>DYNAMIC_MODULE_LIMIT</h3>
824
825       
826
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>
833
834     
835
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>
839
840     
841
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>
844
845     <div class="example"><p><code>
846       truss -l -p <var>httpd_child_pid</var>.
847     </code></p></div>
848
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>
852
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>
856
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
860     in some cases).</p>
861
862     <div class="example"><pre>/67:    accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...)
863 /67:    accept(3, 0x00200BEC, 0x00200C0C, 1)            = 9</pre></div>
864
865     <p>In this trace, the listener thread is running within LWP #67.</p>
866
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>
870
871     <div class="example"><pre>/65:    lwp_park(0x00000000, 0)                         = 0
872 /67:    lwp_unpark(65, 1)                               = 0</pre></div>
873
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>
877
878     <div class="example"><pre>/65:    getsockname(9, 0x00200BA4, 0x00200BC4, 1)       = 0</pre></div>
879
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>
887
888     <div class="example"><pre>/65:    brk(0x002170E8)                                 = 0
889 /65:    brk(0x002190E8)                                 = 0</pre></div>
890
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>
898
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>
906
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>
911
912     <div class="example"><pre>/65:    read(9, " G E T   / 1 0 k . h t m".., 8000)     = 97</pre></div>
913
914     <p>The worker thread reads the request from the client.</p>
915
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>
918
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>
925
926     <div class="example"><pre>/65:    sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C)      = 10269</pre></div>
927
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>
934
935     <div class="example"><pre>/65:    write(4, " 1 2 7 . 0 . 0 . 1   -  ".., 78)      = 78</pre></div>
936
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>
944
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>
949
950     <p>The worker thread does a lingering close of the connection.</p>
951
952     <div class="example"><pre>/65:    close(10)                                       = 0
953 /65:    lwp_park(0x00000000, 0)         (sleeping...)</pre></div>
954
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>
957
958     <div class="example"><pre>/67:    accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...)</pre></div>
959
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>
967
968   </div></div>
969 <div class="bottomlang">
970 <p><span>Available Languages: </span><a href="../en/misc/perf-tuning.html" title="English">&nbsp;en&nbsp;</a> |
971 <a href="../fr/misc/perf-tuning.html" hreflang="fr" rel="alternate" title="Français">&nbsp;fr&nbsp;</a> |
972 <a href="../ko/misc/perf-tuning.html" hreflang="ko" rel="alternate" title="Korean">&nbsp;ko&nbsp;</a> |
973 <a href="../tr/misc/perf-tuning.html" hreflang="tr" rel="alternate" title="Türkçe">&nbsp;tr&nbsp;</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[//><!--
978 var lang = 'en';
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) {
982     (function() {
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);
986         })();
987 } else {
988     var text = document.createTextNode("Comments have been disabled for offline viewing.");
989     document.getElementById('disqus_thread').appendChild(text);
990 }
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) {
995     prettyPrint();
996 }
997 //--><!]]></script>
998 </body></html>