Apache optimization: KeepAlive On or Off?

May 1st, 2011

Apache

Apache is the most widely used web server on the Internet. Knowing how to get the most out of Apache is very important for a systems administrator. Optimizing Apache is always a balancing act. It’s a case of sacrificing one resource in order to obtain savings in another.

What is KeepAlive?

HTTP is a session less protocol. A connection is made to transfer a single file and closed once the transfer is complete. This keeps things simple but it’s not very efficient.

To improve efficiency something called KeepAlive was introduced. With KeepAlive the web browser and the web server agree to reuse the same connection to transfer multiple files.

Advantages of KeepAlive

  • Improves website speed: It reduces latency associated with HTTP transfers and delivers a better user experience.
  • Reduces CPU usage: On the server side enabling KeepAlive reduces CPU usage. Consider that a typical web page has dozens of different files such as images, stylesheets, javascript files etc. If KeepAlive is disabled a separate connection must be made for each of those files. Creating and closing connections has an overhead and doing it for every single file wastes CPU time.

Disadvantages of Keepalive

  • Increases memory usage: Enabling KeepAlive  increases memory usage on the server. Apache processes have to keep connections open waiting for new requests from established connections. While they are waiting they are occupying RAM that could be used to service other clients. If you turn off KeepAlive fewer apache processes will remain active. This will lower memory usage and allow Apache to serve more users.

When should you enable KeepAlive?

Deciding whether to enable KeepAlive or not depends on a number of different factors:

  • Server resources: How much RAM vs. how much CPU power you have? RAM is often the biggest limiting factor in a webserver. If you have little RAM you should turn off KeepAlive because having Apache processes hanging around while they wait for more requests from persistent connections is a waste of precious memory. If CPU power is limited then you want KeepAlive on because it reduces CPU load.
  • Types of sites: If you have pages with a lot of images or other files linked into them, KeepAlive will improve the user experience significantly. This is because a single connection will be used to transfer multiple files.
  • Traffic patterns: The type of traffic you get. If your web traffic is spread out evenly throughout a day then you should turn on KeepAlive. OTOH, if you have bursty traffic where a lot of concurrent users access your sites during a short time period KeepAlive will cause your RAM usage to skyrocket so you should turn it off.

Namecheap VPS Hosting

Namecheap has great prices on Xen VPS hosting. These come with root access so you can customize Apache as mentioned in this article. What's more, Namecheap is renowned for its great customer service. Check them out if you are in the market for hosting.

Configure Apache KeepAlive settings

Open up apache’s configuration file and look for the following settings. On CentOS this file is called httpd.conf and is located in /etc/httpd/conf. The following settings are noteworthy:

  • KeepAlive: Switches KeepAlive on or off. Put in “KeepAlive on” to turn it on and “KeepAlive off” to turn it off.
  • MaxKeepAliveRequests: The maximum number of requests a single persistent connection will service. A number between 50 and 75 would be plenty.
  • KeepAliveTimeout: How long should the server wait for new requests from connected clients. The default is 15 seconds which is way too high. Set it to between 1 and 5 seconds to avoid having processes wasting RAM while waiting for requests.
Other settings

KeepAlive affects other settings in your Apache configuration file even though they are not directly related. Here are the settings in an Apache prefork MPM webserver:

  • MaxClients: MaxClients is the maximum number of child processes launched by Apache to service incoming requests. With KeepAlive enabled you have will have a higher number of child processes active during peak times. So your MaxClients value may have to be increased.
  • MaxRequestsPerChild: The number of requests a child process will serve before it is killed and recreated. This is done to prevent memory leaks. When KeepAlive is turned on each persistent connection will count as one request. That effectively turns MaxRequestsPerChild into a maximum connections per child value. As a result you can set a lower MaxRequestsPerChild value if you allow KeepAlive. If you don’t allow KeepAlive you should increase the MaxRequestsPerChild value to prevent excessive CPU usage.

Conclusion

There is no one universal solution to tuning Apache. It all depends on the resources at your disposal and the type of sites you have. When used properly KeepAlive can improve the user experience at minimal cost in terms of server resources. But it can also be a liability when you are faced with a large number of concurrent users.

46 Responses to “Apache optimization: KeepAlive On or Off?”

  1. Morgan says:

    Nice article. Its rare to find a post that explains the use of KeepAlive from a practical yet conversational perspective. Most sites just regurgitate whats already said on the apache site. Thanks.

    Posted on 05 Jul 2011 Reply
  2. Nikhil Korde says:

    hi this is best documents thanks

    Posted on 18 Oct 2011 Reply
  3. BiBi says:

    thanks for share

    Posted on 28 Oct 2011 Reply
  4. Alan says:

    On Centos this file is called httpd.conf and is located in /etc/httpd/conf.

    and in windows ?????????????

    Posted on 31 Oct 2011 Reply
    • abdussamad says:

      Depends on where you installed apache. Probably somewhere in the program files folder. An easy way to find it is to go via the shortcut. use the start menu -> programs -> apache. There even be an option to edit the config file there. If not you can right click on the short cut icon and then choose find target. It’s likely in the conf sub folder of the apache folder.

      Posted on 31 Oct 2011 Reply
  5. PetrosZ says:

    That was really helpful. Thanks for the thorough analysis of KeepAlive.

    Posted on 16 Jan 2012 Reply
  6. HK says:

    This is awesome. Thanks !!

    Posted on 17 Apr 2012 Reply
  7. waro says:

    Like this article. I have one question though:

    If you have little RAM you should turn off KeepAlive

    How much is little?

    Posted on 08 May 2012 Reply
    • Abdussamad says:

      I guess that depends on your traffic. Are you regularly hitting the limits of memory on your server? If yes then try turning off keep alive. If not then keep it on. You can also try tuning it by limiting the keepalivetimeout to 1-5 seconds and reducing the maxkeepaliverequests to something like 75.

      Posted on 08 May 2012 Reply
  8. Jasper says:

    If i have 16GB of RAM, is that enough to turn on Keep-Alive with a lot of active users?? how many is a lot of users with this size of RAM?

    Posted on 14 May 2012 Reply
    • Abdussamad says:

      Yeah. It doesn’t just depend on the amount of RAM you have but also the amount of traffic you have and whether that is causing you to run out of RAM. For instance this site runs on a VPS with just 256MB of RAM and I have keepalive on. Just don’t get a lot of bursty traffic so I never run out of RAM.

      Posted on 15 May 2012 Reply
  9. Jasper says:

    By the way, what is First-Byte time and how to configure for best optimizations for my site??

    How do i configure server/DB to compress texts?

    In this link:
    http://www.webpagetest.org/result/120510_KX_4AK1T/1/performance_optimization/#compress_text

    What is Combine 0% and Cookies 8%……how do i configure the server/DB to pass all those tests (Combine, Cookies, Keep-Alive, etc.)???

    Posted on 14 May 2012 Reply
    • Abdussamad says:

      You shouldn’t put too much stock in tests like the one you’ve linked to. Nevertheless since you asked, here are the answers to your questions:

      1. Compressing files can be done with mod_deflate. Look up mod_deflate and how to configure it. Just keep in mind that compressing web pages increases CPU load and IMO it’s better to not compress pages.

      2. Combining multiple CSS and javascript files into one large file requires support from your Content Management System. You will need to ask your web developer for help with this.

      Posted on 15 May 2012 Reply
  10. Evgeny says:

    I turned on a KeepAlive directive and set KeepAliveTimeout to 600 seconds (sometimes it takes a long time to my module to prepare a response to client).
    Although these configurations I see that Apache server doesn’t sends TCP keepalive messages and the connection is lost.
    So when my module is ready to send response back to client a TCP connection is already down.
    Do yo have any ideas what can it be?

    Posted on 20 May 2012 Reply
    • Abdussamad says:

      No idea but I think you need to redesign your “module” (whatever that is). 600 seconds is a long time to have apache waiting.

      Posted on 18 Jun 2012 Reply
  11. fawics says:

    Thanks for sharing such a helpful article…

    Posted on 28 Aug 2012 Reply
  12. kayce says:

    Hello, thanks for posting this, can you tell me what setting to use for a dedi server with 8gb ram on a video sharing website where users online can get to 100 at one time? thanks

    Posted on 14 Sep 2012 Reply
  13. [...] Apache optimization: KeepAlive On or Off?_kmq.push(["trackClickOnOutboundLink","link_505b2fa49de7f","Article link clicked",{"Title":"Apache optimization: KeepAlive On or Off?","Page":"How to Make Your Site Insanely Fast"}]); [...]

    Posted on 20 Sep 2012
  14. Jeremy says:

    That is well written article. Nice balance of explanation on a technical topic. It was very helpful and the changes were made on my server. Speed improvements are very evident.
    Thanks!
    Jer

    Posted on 13 Oct 2012 Reply
  15. David says:

    This was a very useful article! Haven’t seen anything this clear on Apache tuning on the web. Thanks!

    Posted on 29 Oct 2012 Reply
  16. Croc says:

    Very useful, thanks

    Posted on 19 Nov 2012 Reply
  17. Ashok Koparday says:

    Hi,

    How does one ‘Enable’ Keep Alive? Do I have to paste some script on .htaccess file?

    May be elementary question for you. Nonetheless, I will appreciate your guidance.

    Best wishes,
    Ashok Koparday

    Posted on 11 Jan 2013 Reply
    • Felipe says:

      Hi.

      You can’t control keepalive in a .htaccess file, because it’s a host-level feature, not something that can change between directories. You’ll have to locate and change the httpd.conf file.

      Posted on 11 Jan 2013 Reply
  18. [...] Before you do add this setting, it will be worth reading this article about turning on or off KeepAlive On. [...]

    Posted on 09 Feb 2013
  19. Jpe Franco says:

    Que se puede hacer si un servidor de hosting compartido no soporte KeepAlive ? Realizar una configuración en el .htaccess del tipo KeepAlive On produciría un error web. Alguna idea?

    Posted on 18 Feb 2013 Reply
    • Abdussamad says:

      You need root access to the server to enable KeepAlive. So it can’t be done on shared hosting.

      Posted on 19 Feb 2013 Reply
  20. [...] have the overhead of opening and closing a connection. I found this great overview of the options here which is worth reading if you want more [...]

    Posted on 12 Mar 2013
  21. Teno says:

    This is the very thing for which I’m looking!

    Posted on 31 Mar 2013 Reply
  22. Erlan says:

    This very helpful, 1 question I am running on SLES 2 GB memory, traffic quit high with dynamic http (Java Servlet with DB2), what is the recommended value for Keep Alive ? Thank you.

    Posted on 04 Apr 2013 Reply
    • Abdussamad says:

      Depends on how much free RAM you have. If you are currently well within your memory limits then enable keepalive using the values specified in the article above. But if you are running out of RAM then try turning keepalive off.

      Posted on 04 Apr 2013 Reply
  23. Erlan says:

    Thank very much, I’ll monitor my memory first ….

    Posted on 04 Apr 2013 Reply
  24. [...] actually think, we learnt the hard way. Many good articles have discussed the KeepAlive topic (e.g. KeepAlive On/Off) with good arguments. Here I’ll present rather a [...]

    Posted on 15 Apr 2013
  25. chavodie says:

    Excelent post!!!
    Thanks a lot.

    Posted on 17 Apr 2013 Reply
  26. [...] Keep-Alive es una fantástica feature de los servidores Apache que permite a servidor y cliente negociar una única petición HTTP para transferir varios recursos, en vez de abrir una nueva petición por recurso. Es fácil ver que esto congenia muy bien con nuestro objetivo de minimizar el número de peticiones HTTP. [...]

    Posted on 29 Apr 2013
  27. James says:

    Thanks for this well written article – a very clear and helpful explanation of Keep Alive.

    Posted on 10 May 2013 Reply
  28. rakesh kumar says:

    I am on a shared hosting service of hostgator? How can i do this for my website [removed] so that it would load in less time. Waiting for your response

    Posted on 02 Jul 2014 Reply
    • Abdussamad says:

      You need root access for this so it’s not possible on shared hosting.

      Posted on 03 Jul 2014 Reply
  29. Jay says:

    I learned a lot from your article, thanks!

    But not sure what my optimal setting should be. I have iphone app users who send requests to my server, which runs code and returns a small text file, just a few KB back to the app. So it is a single very small file, but over slow cell networks. Since it is a single file, should I turn keep alive off? Or, reduce the time? If I reduced it to 5 seconds, but the cell phone was slow, would I be in danger of losing their connection? Thank you.

    Posted on 13 Jul 2014 Reply
    • Jay says:

      Also, sometimes it might take 10 seconds for the server to finish calculations, and send the packet back to the iphone user. Is this relevant as far as keep alive goes? I assume it begins counting the instant the server receives the request? And if the server itself takes a long time like 15 seconds (more than the keepalive allotment of say 5 seconds), the connection will still be alive?

      Posted on 13 Jul 2014 Reply
      • Abdussamad says:

        No, a new connection will be made. If this application is all your server runs then set keep alive to higher than 10 seconds. You’ll have to experiment and try different configurations to see what works best for you.

        Posted on 19 Jul 2014 Reply
  30. Kunal says:

    Great Article.

    Posted on 18 Jul 2014 Reply

Leave a Reply

Your email address will not be published. Required fields are marked *