Tuning PHP for Windows & IIS

11,868 views
11,448 views

Published on

Mark Brown's talk at Dutch PHP Conference 2011 for tuning PHP on Windows and IIS.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
11,868
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
50
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • http://learn.iis.net/page.aspx/728/best-practices-for-php-on-the-microsoft-web-platform/
  • Fast CGIWith the release of FastCGI first time you could actually consider hosting php on win/iis, production quality, no more crashes.Previously you had two options to host PHP, CGI or PHP ISAPI.CGI was stable but very slow because you had to spin up a new process for each new PHP request.ISAPI was faster but since many popular extensions for PHP were not thread safe this caused major issues with stability.FastCGI handles PHP requests out of an app pool rather than spinning up a new one each time.FastCGI provides optimal PHP performance without having to manually tune:Fast CGI provides Automatic performance tuning.Determines: CPU usage, memory consumption, context switches. Based upon that information it changes the number of PHP processes to optimize your application automatically. (SetsDynamic Max Instances)Very important if you are a hoster managing many customers since it allows for a higher density of PHP applications on Windows than you could get before or a customer with an app that has large changes in requests over time.Automatic recycling of PHP processes in IIS when php.ini changes. No longer need to restart IIS.Version 1.5 now has a consistent set of features across all versions of IIS. This is important as a significant number of PHP developers still use XP. This will allow them to develop and deploy seamlessly to Windows Server. Version 1.5 of Fast-CGI is included in Windows Server 2008 R2 (IIS 7.5), an update is available for IIS 7 along with a back-port for those using XP.Another useful feature I wanted to point out here as well is you can provide to your customers developing or running PHP on Windows/IIS is the Advanced Logging module in IIS which you can use to consolidate event reporting for PHP itself as well as from IIS. This will help your customers consolidate application performance reporting, good for tracking failed requests or other issues in your php application. No need to have separate error log files for webserver and php.
  • So prior to PHP 5.3 the PHP engine itself wasn’t mature on Windows, causing compatibility and performance problems.Implemented with APR (Apache portable runtime) instead of directly on Win32 created subpar performanceAlso many Windows-specific PHP bugs hadn’t been fixedThere were as I mentioned earlier issues with hosting on IIS itself with the slow CGI or unstable ISAPI handler. Using FastCGI provided the fix for that part.PHP 5.3Has an updated code base, feature and security parity with the rest of PHP.Much of PHP for Windows completely rewritten to use native Win32 instead of through the POSIX layerAlso compiled using our latest compiler VC9 versus VC 6 which was 10 years oldUse the NTS version. No thread safety checks since PHP runs Single threaded on IIS in FastCGI.Reason for NTS is that many of the most popular community extensions themselves are NTS themselves, making NTS the default on Windows is the safest route for stability.The architecture of IIS and the FastCGI extension provide an isolation model that keeps requests separate, removing the need for a thread-safe version. The NTS doesn’t have any of the code that allows PHP to manage multiple threads. As a result, you will see a performance improvement on IIS when using the NTS version as compared to the tread-safe version.
  • Compile and file operations on Windows are slower than on linux. Many more security checks, etc.Many PHP developers on Linux use other caching mechanisms such as memcache or APC.There are no good open source solutions for caching on Windows WinCache is our solution to help provide even more performance for PHP on Windows.Opcode cache – this is a cache of the compiled PHP file. WinCache let PHP core compile the PHP file to generate opcodes first time it is executed. Then caches these opcodes in memory and is shared with other PHP processesIncreasing performance, especially on subsequent access to the executable code. Can expect a 100%-200% increase in performance.File cache – File IO operations on Windows are much more expensive than on Linux. For files on UNC’s or NFS in hosting environments scenarios it is even worse. File Cache stores the contents of opened files in shared memory. This increases performance 80-90% over accessing the files each time from a shared location.Resolve File Path cache – On first access a PHP application will work to determine the absolute path to a file to then open itThis feature is used to store the absolute path from relative file paths used in PHP applications.Again, anything to reduce usage of the file systems calls produces performance gains.Session Cache:The session cache will take and store session data in shared memory cache instead of file system for added performance benefits.Currently this feature cannot be used in a webfarm where there is no session affinity.User Data Cache API’s: Provides caching functions(API’s) with the Can be used by PHP applications for storing variables and objects in shared memory using WinCache instead of PHPs cache.You can cache database data, php data, classes, etc. Overall just closing the feature gap to APC, etc. trying to have a complete solution.WinCache Statistics Script – This thing is very cool and you should check it out. Great for helping you benchmark and fine tune your PHP applications on Windows. Is installed with the WinCache for PHP.PS: this file is protected by default with HTTP basic authentication so if you do provide this for your customers. Just an FYI.
  • Make sure that FastCGI always recycles the php-cgi.exe processes before the native PHP recycling kicks in. The FastCGI process recycling behavior is controlled by the configuration property instanceMaxRequests. This property specifies how many requests the FastCGI process will process before recycling. PHP also has a similar process recycling functionality that is controlled by an environment variable PHP_FCGI_MAX_REQUESTS. By setting instanceMaxRequests to be smaller or equal to PHP_FCGI_MAX_REQUESTS, you can ensure that the native PHP process recycling logic will never kick in.To set:Open FastCGISet instanceMaxRequest to 10000. Click on Environment VariablesCreatePHP_FCGI_MAX_REQUESTS as new variable and set that to 10000 too.If you use PHP Manager this is called out when you first install PHP and open PHP Manager
  • Another reason to be using PHP 5.3 is this is much easier now than it is using 5.2This is very easy to do with PHP 5.3 and IIS 7.Simply install PHP using the Web PI or install Windows binaries from PHP.NET. Select the FastCGI option.For your two websites simple enter in the ini settings you want to override for each site.Once you’re done. Save the php.ini file, and then recycle the application pools for these Web sites for the PHP.INI changes to take effect or if you have set the monitor changes to file set to monitor php.ini it will recycle the app pools for you.
  • Kernel Mode Output cache does not support modules and features that must run in user mode, such as authentication or authorization. Example: If authentication schemes like Basic or Windows authentication are enabled, the cache policy will not work. The content is served but not cached. Troubleshooting Output Caching:Failed Request Event Buffering (FREB) is the best way to find out whether or not your request gets cached. FREB tells you why something does not get cached. Here is a sample of a FREB log. In this case, the HTTPSYS_CACHEABLE event tells you that the request does not get cached because the kernel-mode cache is not enabled. Use this to show what is cached in kernel mode.netsh http show cachestatehttp://learn.iis.net/page.aspx/154/walkthrough-iis-70-output-caching/
  • When a user hits your site www.mysite.com IIS will go through the list of default documents for that site. This is inheirited from the server itself. It will cycle through each of them until it finds the correct one for your site. Set the default document for our site to whatever it should be for your php site. Generally this is index.php. This will short circuit this step and send users directly to the default document.Remove unused processes and services from your webserver, mail apps, anti-virus, screen savers, etc. This is just good practice for any webserver.Try to minimize logging on your production site. If you typically have verbose logging in use when you develop, try trimming that down or turning it off. Logging consumes resources.Keep-Alives: The HTTP keep-alive response header improves Web server performance by keeping a client/server connection open across multiple requests to the server. The open connection improves performance when a client makes multiple requests for Web page content, because the server can return the content for each request more quickly. Otherwise, the server has to open a new connection for every request. By default, the HTTP keep-alive response header is enabled in IIS 7. HTTP Compression: One of the most effective ways to reduce the bandwidth needed to deliver the application responses is to use HTTP compression. This can reduce the size of the response by a substantial amount, often by a factor of 10 when applied to easily compressible text content such as HTML. Since compression is based on Content-Encoding negotiation defined in the HTTP 1.1 protocol, enabling it is safe for clients that do not support compression—these clients simply receive an uncompressed version of the content. Dynamic compression usually does not have a prohibitive CPU overhead. In fact, dynamic compression often causes less than 5 percent of the total CPU utilization on a busy server. Dynamic compression can be deployed somewhat liberally to allow for maximum bandwidth savings for any application workloads.
  • When a user hits your site www.mysite.com IIS will go through the list of default documents for that site. This is inheirited from the server itself. It will cycle through each of them until it finds the correct one for your site. Set the default document for our site to whatever it should be for your php site. Generally this is index.php. This will short circuit this step and send users directly to the default document.Remove unused processes and services from your webserver, mail apps, anti-virus, screen savers, etc. This is just good practice for any webserver.Try to minimize logging on your production site. If you typically have verbose logging in use when you develop, try trimming that down or turning it off. Logging consumes resources.Keep-Alives: The HTTP keep-alive response header improves Web server performance by keeping a client/server connection open across multiple requests to the server. The open connection improves performance when a client makes multiple requests for Web page content, because the server can return the content for each request more quickly. Otherwise, the server has to open a new connection for every request. By default, the HTTP keep-alive response header is enabled in IIS 7. HTTP Compression: One of the most effective ways to reduce the bandwidth needed to deliver the application responses is to use HTTP compression. This can reduce the size of the response by a substantial amount, often by a factor of 10 when applied to easily compressible text content such as HTML. Since compression is based on Content-Encoding negotiation defined in the HTTP 1.1 protocol, enabling it is safe for clients that do not support compression—these clients simply receive an uncompressed version of the content. Dynamic compression usually does not have a prohibitive CPU overhead. In fact, dynamic compression often causes less than 5 percent of the total CPU utilization on a busy server. Dynamic compression can be deployed somewhat liberally to allow for maximum bandwidth savings for any application workloads.
  • Tuning PHP for Windows & IIS

    1. 1. Tips & Tricks<br />Tuning PHP<br />on Windows & IIS<br />Mark Brown<br />Microsoft Corporation<br />mark.brown@microsoft.com<br />@markjbrown<br />
    2. 2. Tip #1 – Use IIS 7<br />PHP on IIS6 and Prior<br />CGI – Slow as hell (1 request = 1 process)<br />ISAPI – Fast but unstable (mixed threading)<br />IIS 7<br />Blew up IIS6<br />Modular Architecture<br />Default Minimum Installation<br />Streamlined Processing Pipeline<br />Uses FastCGIto handle PHP requests<br />FastCGI now available for IIS 6<br />
    3. 3. Tip #2 – Use Fast CGI<br />Uses an App Pool to process requests<br />No CreateProc() for each Request!!!<br />App Pool Size is configurable<br />Adjust AppPoolSize according to load to maximize response time<br />Automatic Tuning Capability<br />Set AppPoolSize = 0<br />Memory, Context Switches, CPU<br />Auto Tuning useful if hosting many sites on same IIS server<br />Better density, site only uses resources it needs<br />
    4. 4. Tip #3 – Use PHP 5.3<br />Feature & Security parity<br />Faster File IO on network shares<br />Win32 Codebase, not POSIX<br />New Windows build scripts<br />Compiled with VC9 vs. VC6<br />Compile yourself to optimize further<br />Non-Thread Safe binary for Windows<br />No NTS checks<br />Make sure your extensions are NTS too!!!<br />
    5. 5. Tip #4 – Use WinCache<br />Boost your speed with no code changes<br />Opcode Cache<br />File Cache<br />Stores files in memory<br />Relative File Path Cache<br />Helpful for shared or NFS storage<br />Session Cache <br />Enable in php.ini<br />User Data Cache<br />Store Data in memory<br />APC interface<br />
    6. 6. Tip 4.5 If !(User Cache)<br />MySQL Reverse-Lookup Bug<br />FastCGI Bug?<br />Follow me on Twitter for updates<br />Use mysql_pconnect()<br />Can cause issues using temp tables<br />[mysqld] section of my.ini<br />Add skip-name-resolve<br />Use 127.0.0.1 in code<br />
    7. 7. Tip #5 – ConfigProc Recycling<br />Don’t allow native PHP to do it.<br />Allow FastCGI to manage PHP process recycling on IIS.<br />Set instanceMaxRequests <= to PHP_FCGI_MAX_REQUESTS<br />Default is 10K requests<br />
    8. 8. Tip #6 –Per-Site PHP Config<br />Only for PHP 5.3<br />Configure IIS to have unique PHP config for each site on server.<br />Eg. Photo upload site, vs long running scripts<br />Php.ini file website overrides<br />Insert at the end of php.ini<br />[PATH=C:/inetpub/website1.com/] max_execution_time = 300 <br />[PATH=C:/inetpub/website2.com/] upload_max_filesize = 12M<br />
    9. 9. Tip #7 – Use IIS Output Cache<br />Use for Semi-Dynamic Content<br />Product pages, etc.<br />User Mode Caching<br />Cached in IIS7 Worker Process<br />Authentication and Authorization<br />varyByHeadersattribute <br />varyByQuerystring attribute<br />Kernel Mode Caching<br />Cached in HTTP.SYS, a kernel mode driver<br />Much faster but lacks features that must execute in Worker Process<br />
    10. 10. Tip #8 – Fine Tuning Tips<br />Set Default Document (index.php)<br />Remove unused services & modules<br />Minimize Logging<br />Use HTTP Keep-Alives<br />Use HTTP Compression<br />Static & Dynamic<br />
    11. 11. DEMO<br />
    12. 12. More Information<br />http://php.iis.net<br />http://web.ms/php<br />http://windows.php.net<br />Source Code and WCAT tool:<br />http://dl.dropbox.com/u/23010264/PHP_Perf_Win-IIS.zip<br />
    13. 13. Thank You<br />Questions?<br />

    ×