<p>Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques.</p>

<hr>

<p>I'm developing a tool in <strong>PHP</strong> that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well).</p>

<h2>Databases</h2>

<p>At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually <em>need</em> multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server?</p>

<h2>Caching</h2>

<p>I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called it's cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load.</p>

<p>My question on this:</p>

<p>Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached.</p>

<h2>Finally</h2>

<p>Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for?</p>

[{'answer_id': 24679, 'author': 'tslocum', 'author_id': 1662, 'author_profile': 'https://Stackoverflow.com/users/1662', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://us.php.net/apc" rel="nofollow noreferrer">APC</a> is an absolute must.  Not only does it make for a great caching system, but the gain from the auto-cached PHP files is a godsend.  As for the multiple database idea, I don\'t think you would get much out of having different databases on the same server.  It may give you a bit of a gain in speed during query time, but I doubt the effort it would take to deploy and maintain the code for all three while making sure they are in sync would be worth it.</p>\n\n<p>I also highly recommend running <a href="http://www.xdebug.org/" rel="nofollow noreferrer">Xdebug</a> to find bottlenecks in your program.  It made optimization a breeze for me.</p>\n'}, {'answer_id': 24681, 'author': 'Eric Scrivner', 'author_id': 2594, 'author_profile': 'https://Stackoverflow.com/users/2594', 'pm_score': 3, 'selected': False, 'text': '<p>Firstly, as I think Knuth said, "Premature optimization is the root of all evil".  If you don\'t have to deal with these issues right now then don\'t, focus on delivering something that works correctly first.  That being said, if the optimizations can\'t wait.</p>\n\n<p>Try profiling your database queries, figure out what\'s slow and what happens alot and come up with an optimization strategy from that.</p>\n\n<p>I would investigate <a href="http://es.php.net/memcache" rel="noreferrer" title="Memcached">Memcached</a> as it\'s what a lot of the higher load sites use for efficiently caching content of all types, and the PHP object interface to it is quite nice.</p>\n\n<p>Splitting up databases among servers and using some sort of load balancing technique (e.g. generate a random number between 1 and # redundant databases with necessary data - and use that number to determine which database server to connect to) can also be an excellent way to increase efficiency.</p>\n\n<p>These have all worked out pretty well in the past for some fairly high load sites.  Hope this helps to get you started :-)</p>\n'}, {'answer_id': 24685, 'author': 'Ryan Doherty', 'author_id': 956, 'author_profile': 'https://Stackoverflow.com/users/956', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve worked on a few sites that get millions/hits/month backed by PHP &amp; MySQL. Here are some basics:</p>\n\n<ol>\n<li>Cache, cache, cache. Caching is one of the simplest and most effective ways to reduce load on your webserver and database. Cache page content, queries, expensive computation, anything that is I/O bound. Memcache is dead simple and effective.</li>\n<li>Use multiple servers once you are maxed out. You can have multiple web servers and multiple database servers (with replication).</li>\n<li>Reduce overall # of request to your webservers. This entails caching JS, CSS and images using expires headers. You can also move your static content to a CDN, which will speed up your user\'s experience.</li>\n<li>Measure &amp; benchmark. Run Nagios on your production machines and load test on your dev/qa server. You need to know when your server will catch on fire so you can prevent it.</li>\n</ol>\n\n<p>I\'d recommend reading <a href="https://rads.stackoverflow.com/amzn/click/com/0596102356" rel="noreferrer" rel="nofollow noreferrer">Building Scalable Websites</a>, it was written by one of the Flickr engineers and is a great reference. </p>\n\n<p>Check out my blog post about scalability too, it has a lot of links to presentations about scaling with multiple languages and platforms:\n<a href="http://www.ryandoherty.net/2008/07/13/unicorns-and-scalability/" rel="noreferrer">http://www.ryandoherty.net/2008/07/13/unicorns-and-scalability/</a></p>\n'}, {'answer_id': 24686, 'author': 'Bob Somers', 'author_id': 1384, 'author_profile': 'https://Stackoverflow.com/users/1384', 'pm_score': 3, 'selected': False, 'text': '<p>Profiling your app with something like Xdebug (like tj9991 recommended) is definitely going to be a must. It doesn\'t make a whole lot of sense to just go around optimizing things blindly. Xdebug will help you find the real bottlenecks in your code so you can spend your optimization time wisely and fix chunks of code that are actually causing slow downs.</p>\n\n<p>If you\'re using Apache, another utility that can help in testing is <a href="http://www.joedog.org/JoeDog/Siege" rel="noreferrer">Siege</a>. It will help you anticipate how your server and application will react to high loads by really putting it through its paces.</p>\n\n<p>Any kind of opcode cache for PHP (like APC or one of the many others) will help a lot as well.</p>\n'}, {'answer_id': 24689, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 8, 'selected': True, 'text': '<p>No two sites are alike. You really need to get a tool like <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">jmeter</a> and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won\'t see real results until you measure and compare your changes. </p>\n\n<p>For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you\'d never know.</p>\n\n<p>And don\'t forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you\'re lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well.</p>\n\n<h1>Databases</h1>\n\n<ul>\n<li>Don\'t use MySQLi -- <a href="http://ca.php.net/pdo" rel="noreferrer">PDO</a> is the \'modern\' OO database access layer. The most important feature to use is placeholders in your queries. It\'s smart enough to use server side prepares and other optimizations for you as well.</li>\n<li>You probably don\'t want to break your database up at this point. If you do find that one database isn\'t cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines.</li>\n</ul>\n\n<h1>Caching</h1>\n\n<ul>\n<li>You probably don\'t want to cache in your database. The database is typically your bottleneck, so adding more IO\'s to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like <a href="http://ca.php.net/apc" rel="noreferrer">APC</a> and Zend. </li>\n<li>Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. </li>\n<li>If it takes a long time to build your comments and article data from the db, integrate <a href="http://www.danga.com/memcached/" rel="noreferrer">memcache</a> into your system. You can cache the query results and store them in a memcached instance. It\'s important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit.</li>\n<li>If your articles aren\'t dynamic, or you have simple dynamic changes after it\'s generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it\'s there, it streams it to the client. If it isn\'t, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated.</li>\n</ul>\n'}, {'answer_id': 25011, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 1, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24689">Gary</a></p>\n\n<blockquote>\n  <p>Don\'t use MySQLi -- PDO is the \'modern\' OO database access layer. The most important feature to use is placeholders in your queries. It\'s smart enough to use server side prepares and other optimizations for you as well.</p>\n</blockquote>\n\n<p>I\'m loking over PDO at the moment and it looks like you\'re right - however I know that MySQL are developing the MySQLd extension for PHP - I think to succeed either MySQL or MySQLi - what do you think about that?</p>\n\n<hr>\n\n<p>@<a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24685">Ryan</a>, <a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24681">Eric</a>, <a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24679">tj9991</a></p>\n\n<p>Thanks for the advice on PHP\'s caching extensions - could you explain reasons for using one over another? I\'ve heard great things about memcached through IRC but have never heard of APC - what are your opinions on them? I assume using multiple caching systems is pretty counter-effective.</p>\n\n<p>I will definitely be sorting out some profiling testers - thank you very much for your recommendations on those.</p>\n'}, {'answer_id': 25056, 'author': 'Berzemus', 'author_id': 2452, 'author_profile': 'https://Stackoverflow.com/users/2452', 'pm_score': 2, 'selected': False, 'text': '<p>Sure pdo is nice, but there <a href="http://dealnews.com/developers/php-mysql.html" rel="nofollow noreferrer">has</a> <a href="http://www.santosj.name/php/mysqli-vs-pdo/" rel="nofollow noreferrer">been</a> <a href="http://brian.moonspot.net/2006/08/06/mysqli-vs-pdo-my-version/" rel="nofollow noreferrer">some</a> controversy about it\'s performance versus mysql and mysqli, although it seems fixed now.</p>\n\n<p>You should use pdo if you envision portability, but if not, mysqli should be the way. It has an OO interface, prepared statements, and most of what pdo offers (except, well, portability).</p>\n\n<p>Plus, if performance is really needed, prepare for the (native mysql) <a href="http://dev.mysql.com/downloads/connector/php-mysqlnd/" rel="nofollow noreferrer">MysqLnd</a> driver in PHP 5.3, who will be much more tightly integrated with php, with better performance and improved memory usage (and statistics for performance tuning).</p>\n\n<p>Memcache is nice if you have clustered servers (and YouTube-like load), but i\'d try out <a href="http://be.php.net/manual/en/book.apc.php" rel="nofollow noreferrer">APC</a> first too.</p>\n'}, {'answer_id': 25070, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 2, 'selected': False, 'text': '<p>It looks like <a href="http://forge.mysql.com/wiki/Which_PHP_Driver_for_MySQL_should_I_use" rel="nofollow noreferrer">I was wrong</a>. MySQLi is still being developed. But according to the article, PDO_MySQL is now being contributed to by the MySQL team. From the article:</p>\n\n<blockquote>\n  <p>The MySQL Improved Extension - mysqli\n  - is the flagship. It supports all features of the MySQL Server including\n  Charsets, Prepared Statements and\n  Stored Procedures. The driver offers a\n  hybrid API: you can use a procedural\n  or object-oriented programming style\n  based on your preference. mysqli comes\n  with PHP 5 and up. Note that the End\n  of life for PHP 4 is 2008-08-08.</p>\n  \n  <p>The PHP Data Objects (PDO) are a\n  database access abstraction layer. PDO\n  allows you to use the same API calls\n  for various databases. PDO does not\n  offer any degree of SQL abstraction.\n  PDO_MYSQL is a MySQL driver for PDO.\n  PDO_MYSQL comes with PHP 5. As of PHP\n  5.3 MySQL developers actively contribute to it. The PDO benefit of a\n  unified API comes at the price that\n  MySQL specific features, for example\n  multiple statements, are not fully\n  supported through the unified API.</p>\n  \n  <p>Please stop using the first MySQL\n  driver for PHP ever published:\n  ext/mysql. Since the introduction of\n  the MySQL Improved Extension - mysqli\n  - in 2004 with PHP 5 there is no reason to still use the oldest driver\n  around. ext/mysql does not support\n  Charsets, Prepared Statements and\n  Stored Procedures. It is limited to\n  the feature set of MySQL 4.0. Note\n  that the Extended Support for MySQL\n  4.0 ends at 2008-12-31. Don\'t limit yourself to the feature set of such\n  old software! Upgrade to mysqli, see\n  also Converting_to_MySQLi. mysql is in\n  maintenance only mode from our point\n  of view.</p>\n</blockquote>\n\n<p>To me, it seems the article is biased towards MySQLi. I suppose I\'m biased towards PDO.\nI really like PDO over MySQLi. It\'s straight forward to me. The API is a lot closer to other languages I\'ve programmed in. OO Database interfaces seem to work better.</p>\n\n<p>I haven\'t come across any specific MySQL features that weren\'t available through PDO. I would be surprised if I ever did.</p>\n'}, {'answer_id': 25072, 'author': 'davidmytton', 'author_id': 2183, 'author_profile': 'https://Stackoverflow.com/users/2183', 'pm_score': 5, 'selected': False, 'text': '<p><em>Re: PDO / MySQLi / MySQLND</em></p>\n\n<p>@<a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24689">gary</a></p>\n\n<p>You cannot just say "don\'t use MySQLi" as they have different goals. PDO is almost like an abstraction layer (although it is not actually) and is designed to make it easy to use multiple database products whereas MySQLi is specific to MySQL conections. It is wrong to say that PDO is the modern access layer in the context of comparing it to MySQLi because your statement implies that the progression has been mysql -> mysqli -> PDO which is not the case.</p>\n\n<p>The choice between MySQLi and PDO is simple - if you need to support multiple database products then you use PDO. If you\'re just using MySQL then you can choose between PDO and MySQLi.</p>\n\n<p>So why would you choose MySQLi over PDO? See below...</p>\n\n<p><a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#25011">@ross</a></p>\n\n<p>You are correct about MySQLnd which is the newest MySQL core language level library, however it is not a replacement for MySQLi. MySQLi (as with PDO) remains the way you would interact with MySQL through your PHP code. Both of these use libmysql as the C client behind the PHP code. The problem is that libmysql is outside of the core PHP engine and that is where mysqlnd comes in i.e. it is a Native Driver which makes use of the core PHP internals to maximise efficiency, specifically where memory usage is concerned.</p>\n\n<p>MySQLnd is being developed by MySQL themselves and has recently landed onto the PHP 5.3 branch which is in RC testing, ready for a release later this year. You will then be able to use MySQLnd with MySQLi...but not with PDO. This will give MySQLi <a href="http://blog.ulf-wendel.de/?p=136" rel="nofollow noreferrer">a performance boost</a> in many areas (not all) and will make it the best choice for MySQL interaction if you do not need the abstraction like capabilities of PDO.</p>\n\n<p>That said, MySQLnd <a href="http://blog.ulf-wendel.de/?p=193" rel="nofollow noreferrer">is now available in PHP 5.3</a> for PDO and so you can get the advantages of the performance enhancements from ND into PDO, however, PDO is still a generic database layer and so will be <a href="http://blog.ulf-wendel.de/?p=191" rel="nofollow noreferrer">unlikely to be able to benefit as much from the enhancements in ND as MySQLi can</a>.</p>\n\n<p><a href="http://brian.moonspot.net/2006/08/25/pdo-turbo-button/" rel="nofollow noreferrer">Some useful benchmarks can be found here</a> although they are from 2006. You also need to be aware of things like <a href="http://netevil.org/uuid/444a6017-0548-2459-2943-44a601714d58" rel="nofollow noreferrer">this option</a>.</p>\n\n<p>There are a lot of considerations that need to be taken into account when deciding between MySQLi and PDO. It reality it is not going to matter until you get to rediculously high request numbers and in that case, it makes more sense to be using an extension that has been specifically designed for MySQL rather than one which abstracts things and happens to provide a MySQL driver. </p>\n\n<p>It is not a simple matter of which is best because each has advantages and disadvantages. You need to read the links I\'ve provided and come up with your own decision, then test it and find out. I have used PDO in past projects and it is a good extension but my choice for pure performance would be MySQLi with the new MySQLND option compiled (when PHP 5.3 is released).</p>\n'}, {'answer_id': 25078, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 1, 'selected': False, 'text': "<p>I don't see myself switching from MySQL anytime soon - so I guess I don't need the abstraction capabilities of PDO. Thanks for those articles DavidM, they've helped me a lot.</p>\n"}, {'answer_id': 25079, 'author': 'ceejayoz', 'author_id': 1902010, 'author_profile': 'https://Stackoverflow.com/users/1902010', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>Thanks for the advice on PHP\'s caching extensions - could you explain reasons for using one over another? I\'ve heard great things about memcached through IRC but have never heard of APC - what are your opinions on them? I assume using multiple caching systems is pretty counter-effective.</p>\n</blockquote>\n\n<p>Actually, <a href="http://www.mysqlperformanceblog.com/2006/09/27/apc-or-memcached/" rel="noreferrer">many do use APC and memcached together</a>...</p>\n'}, {'answer_id': 26352, 'author': 'Till', 'author_id': 2859, 'author_profile': 'https://Stackoverflow.com/users/2859', 'pm_score': 2, 'selected': False, 'text': "<p>PDO is also very slow and its API is pretty complicated. No one in their sane mind should use it if portability is not a concern. And let's face it, in 99% of all webapps it is not. You just stick with MySQL or PostrgreSQL, or whatever it is you are working with.</p>\n\n<p>As for the PHP question and what to take into account. I think premature optimization is the root of all evil. ;) Get your application done first, try to keep it clean when it comes to programming, do a little documentation and write unit tests. With all of the above you will have no issues refactoring code when the time comes. But first you want to be done and push it out to see how people react to it.</p>\n"}, {'answer_id': 27641, 'author': 'Vegard Larsen', 'author_id': 1606, 'author_profile': 'https://Stackoverflow.com/users/1606', 'pm_score': 3, 'selected': False, 'text': '<p>I run a website with 7-8 million page views a month. Not terribly much, but enough that our server felt the load. The solution we chose was simple: Memcache at the database level. This solution works well if the database load is your main problem.</p>\n\n<p>We started out using Memcache to cache entire objects and the database results that were most frequently used. It did work, but it also introduced bugs (we might have avoided some of those if we had been more careful).</p>\n\n<p>So we changed our approach. We built a database wrapper (with the exact same methods as our old database, so it was easy to switch), and then we subclassed it to provide memcached database access methods.</p>\n\n<p>Now all you have to do is decide whether a query can use cached (and possibly out of date) results or not. Most of the queries run by the users are now fetched directly from Memcache. The exceptions are updates and inserts, which for the main website only happens because of logging. This rather simple measure reduced our server load by about 80%.</p>\n'}, {'answer_id': 31191, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>For what it's worth, caching is DIRT SIMPLE in PHP even without an extension/helper package like memcached. </p>\n\n<p>All you need to do is create an output buffer using <code>ob_start()</code>. </p>\n\n<p>Create a global cache function. Call <code>ob_start</code>, pass the function as a callback. In the function, look for a cached version of the page. If exists, serve it and end. </p>\n\n<p>If it doesn't exist, the script will continue processing. When it reaches the matching ob_end() it will call the function you specified. At that time, you just get the contents of the output buffer, drop them in a file, save the file, and end. </p>\n\n<p>Add in some expiration/garbage collection. </p>\n\n<p>And many people don't realize you can nest <code>ob_start()</code>/<code>ob_end()</code> calls. So if you're already using an output buffer to, say, parse in advertisements or do syntax highlighting or whatever, you can just nest another <code>ob_start/ob_end</code> call. </p>\n"}, {'answer_id': 36558, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 1, 'selected': False, 'text': '<p>Look into <a href="http://httpd.apache.org/docs/2.0/mod/mod_cache.html" rel="nofollow noreferrer">mod_cache</a>, an output cache for the Apache web server, simillar to the output caching in ASP.NET.</p>\n\n<p>Yes, I can see that it\'s still experimental but it will be final someday.</p>\n'}, {'answer_id': 148194, 'author': 'Paul Kroll', 'author_id': 6280, 'author_profile': 'https://Stackoverflow.com/users/6280', 'pm_score': 5, 'selected': False, 'text': '<p><strong>General</strong></p>\n\n<ul>\n<li>Do not try to optimize before you start to see real world load.  You might guess right, but if you don\'t, you\'ve wasted your time.  </li>\n<li>Use <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">jmeter</a>, <a href="http://www.xdebug.org/" rel="noreferrer">xdebug</a> or another tool to benchmark the site. </li>\n<li>If load starts to be an issue, either object or data caching will likely be involved, so generally read up on caching options (memcached, MySQL caching options)</li>\n</ul>\n\n<p><strong>Code</strong></p>\n\n<ul>\n<li>Profile your code so that you know where the bottleneck is, and whether it\'s in code or the database</li>\n</ul>\n\n<p><strong>Databases</strong></p>\n\n<ul>\n<li>Use <a href="http://www.php.net/mysqli" rel="noreferrer">MYSQLi</a> if portability to other databases is not vital, <a href="http://www.php.net/pdo" rel="noreferrer">PDO</a> otherwise</li>\n<li>If benchmarks reveal the database is the issue, check the queries before you start caching.  Use <a href="http://dev.mysql.com/doc/refman/5.0/en/explain.html" rel="noreferrer">EXPLAIN</a> to see where your queries are slowing down.</li>\n<li>After the queries are optimized and the database is cached in some way, you may want to use multiple databases. Either replicating to multiple servers or sharding (splitting the data over multiple databases/servers) may be appropriate, depending on the data, the queries, and the kind of read/write behavior.</li>\n</ul>\n\n<p><strong>Caching</strong></p>\n\n<ul>\n<li>Plenty of writing has been done on caching code, objects, and data. Look up articles on <a href="http://www.php.net/apc" rel="noreferrer">APC</a>, <a href="http://www.zend.com/en/products/guard/optimizer/" rel="noreferrer">Zend Optimizer</a>, <a href="http://www.danga.com/memcached/" rel="noreferrer">memcached</a>, <a href="http://sourceforge.net/projects/quickcache" rel="noreferrer">QuickCache</a>, <a href="http://www.polarlava.com/projects/jpcache/" rel="noreferrer">JPCache</a>.  Do some of this before you really need to, and you\'ll be less concerned about starting off unoptimized.</li>\n<li>APC and Zend Optimizer are opcode caches, they speed up PHP code by avoiding reparsing and recompilation of code.  Generally simple to install, worth doing early.</li>\n<li>Memcached is a generic cache, that you can use to cache queries, PHP functions or objects, or entire pages.  Code must be specifically written to use it, which can be an involved process if there are no central points to handle creation, update and deletion of cached objects.</li>\n<li>QuickCache and JPCache are file caches, otherwise similar to Memcached.  The basic concept is simple, but also requires code and is easier with central points of creation, update and deletion.</li>\n</ul>\n\n<p><strong>Miscellaneous</strong></p>\n\n<ul>\n<li>Consider alternative web servers for high load.  Servers like <a href="http://www.lighttpd.net/" rel="noreferrer">lighthttp</a> and <a href="http://nginx.net/" rel="noreferrer">nginx</a> can handle large amounts of traffic in much less memory than <a href="http://www.apache.org/" rel="noreferrer">Apache</a>, if you can sacrifice Apache\'s power and flexibility (or if you just don\'t need those things, which often, you don\'t).</li>\n<li>Remember that hardware is surprisingly cheap these days, so be sure to cost out the effort to optimize a large block of code versus "let\'s buy a monster server." </li>\n<li>Consider adding the "MySQL" and "scaling" tags to this question</li>\n</ul>\n'}, {'answer_id': 248825, 'author': 'staticsan', 'author_id': 28832, 'author_profile': 'https://Stackoverflow.com/users/28832', 'pm_score': 1, 'selected': False, 'text': "<p>I can't believe no-one has already mentioned this: Modularisation and Abstraction. If you think your site is going to have to grow to lots of machines, you <em>must</em> design it so it can! That means stupid things like don't assume the database is on localhost. It also means things that are going to be a bother at first, like writing a database abstraction layer (like PDO, but much much lighter because it only does what you need it to do). </p>\n\n<p>And it means things like working with a framework. You will need layers to your code so that you can later gain performance by refactoring the data-abstraction layer, for example, by teaching it that some objects are in a different database -- <em>and the code doesn't have to know or care</em>. </p>\n\n<p>Finally, be careful of memory-intensive operations, for example, unnecessary string copying. If you can keep PHP's memory usage down, then you will get more performance out of your webserver and this is something that will scale when you go to a load-balanced solution.</p>\n"}, {'answer_id': 294239, 'author': 'hangy', 'author_id': 11963, 'author_profile': 'https://Stackoverflow.com/users/11963', 'pm_score': 2, 'selected': False, 'text': '<p>A lot of good answers were given already, but I would like to point you to an alternate opcode cache called <a href="http://xcache.lighttpd.net/" rel="nofollow noreferrer">XCache</a>. It is created by a lighty contributor.</p>\n\n<p>Also, if you may need load balancing your database server in future, <a href="http://jan.kneschke.de/projects/mysql/mysql-proxy/" rel="nofollow noreferrer">MySQL Proxy</a> could very well help you to achieve this.</p>\n\n<p>Both of those tools should plug into an existing application quite easily, so this optimization can be done when you need it, without too much hassle.</p>\n'}, {'answer_id': 459826, 'author': 'thesmart', 'author_id': 20176, 'author_profile': 'https://Stackoverflow.com/users/20176', 'pm_score': 6, 'selected': False, 'text': "<p>I'm a lead developer on a site with over 15M users.  We have had very little scaling problems because we planned for it EARLY and scaled thoughtfully.  Here are some of the strategies I can suggest from my experience.</p>\n\n<p><strong>SCHEMA</strong>\nFirst off, denormalize your schemas. This means that rather than to have multiple relational tables, you should instead opt to have one big table.  In general, joins are a waste of precious DB resources because doing multiple prepares and collation burns disk I/O's.  Avoid them when you can.  </p>\n\n<p>The trade-off here is that you will be storing/pulling redundant data, but this is acceptable because data and intra-cage bandwidth is very cheap (bigger disks) whereas multiple prepare I/O's are orders of magnitude more expensive (more servers).</p>\n\n<p><strong>INDEXING</strong>\nMake sure that your queries utilize at least one index.  Beware though, that indexes will cost you if you write or update frequently. There are some experimental tricks to avoid this.</p>\n\n<p>You can try adding additional columns that aren't indexed which run parallel to your columns that are indexed. Then you can have an offline process that writes the non-indexed columns over the indexed columns in batches. This way, you can control better when mySQL will need to recompute the index.</p>\n\n<p>Avoid computed queries like a plague.  If you must compute a query, try to do this once at write time.  </p>\n\n<p><strong>CACHING</strong>\nI highly recommend Memcached.  It has been proven by the biggest players on the PHP stack (Facebook) and is very flexible.  There are two methods to doing this, one is caching in your DB layer, the other is caching in your business logic layer.</p>\n\n<p>The DB layer option would require caching the result of queries retrieved from the DB.  You can hash your SQL query using md5() and use that as a lookup key before going to database.  The upside to this is that it is pretty easy to implement. The downside (depending on implementation) is that you lose flexibility because you're treating all caching the same with regard to cache expiration.</p>\n\n<p>In the shop I work in, we use business layer caching, which means each concrete class in our system controls its own caching schema and cache timeouts.  This has worked pretty well for us, but be aware that items retrieved from DB may not be the same as items from cache, so you will have to update cache and DB together.</p>\n\n<p><strong>DATA SHARDING</strong>\nReplication only gets you so far. Sooner than you expect, your writes will become a bottleneck.  To compensate, make sure to support data sharding early as possible. You will likely want to shoot yourself later if you don't.  </p>\n\n<p>It is pretty simple to implement.  Basically, you want to separate the key authority from the data storage.  Use a global DB to store a mapping between primary keys and cluster ids.  You query this mapping to get a cluster, and then query the cluster to get the data.  You can cache the hell out of this lookup operation which will make it a negligible operation.</p>\n\n<p>The downside to this is that it may be difficult to piece together data from multiple shards. But, you can engineer your way around that as well.</p>\n\n<p><strong>OFFLINE PROCESSING</strong>\nDon't make the user wait for your backend if they don't have to.  Build a job queue and move any processing that you can offline, doing it separate from the user's request.</p>\n"}, {'answer_id': 752659, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>If you are working with large amounts of data, and caching isn't cutting it, look into Sphinx.  We've had great results with using SphinxSearch not only for better text searching, but also as a data retrieval replacement for MySQL when dealing larger tables.  If you use SphinxSE (MySQL plugin), it surpassed our performance gains we had from caching several times over, and application-implementation is a sinch.</p>\n"}, {'answer_id': 2181013, 'author': 'Johannes Gorset', 'author_id': 206684, 'author_profile': 'https://Stackoverflow.com/users/206684', 'pm_score': 1, 'selected': False, 'text': '<p>The points made about cache are spot-on; it is the least complicated and most important part of building an efficient application. I\'d like to add that while memcached is great, APC is about five times faster if your application lives on a single server.</p>\n\n<p>The "Cache Performance Comparison" post at the MySQL performance blog has some interesting benchmarks on the subject - <a href="http://www.mysqlperformanceblog.com/2006/08/09/cache-performance-comparison/" rel="nofollow noreferrer">http://www.mysqlperformanceblog.com/2006/08/09/cache-performance-comparison/</a>.</p>\n'}, {'answer_id': 2524840, 'author': 'symcbean', 'author_id': 223992, 'author_profile': 'https://Stackoverflow.com/users/223992', 'pm_score': 2, 'selected': False, 'text': "<p>First question is how big do you really expect it to be? And how much do you plan on investing in your infrastructure. Since you feel the need to ask the question here, I'm guessing that you expect to start small on a limited budget.</p>\n\n<p>Performance is irrelevant if the site is not available. And for availability you need horizontal scaling.  The minimum you can sensibly get away with is 2 servers, both running apache, php and mysql. Set up one DBMS as a slave to the other. Do all the writes on the master, and all the reads on the local database (whatever that is) - unless for some reason you need to read back the data you've just read (use master). Make sure you've got the machinery in place to automatically promote the slave and fence the master. Use round-robin DNS for the webserver addresses to give more affinity for the slave node.</p>\n\n<p>Partitioning your data across different database nodes at this stage is a very bad idea - however you might want to consider splitting it across different databases on the same server (which will facilitate partitioning across nodes when you overtake facebook).</p>\n\n<p>Do make sure you've got the monitoring and data analysis tools in place to measure your sites performance and identify bottlenecks. Most performance problems can be fixed by writing better SQL / fixing the database schema.</p>\n\n<p>Keeping your template cache on the database is a dumb idea - the database should be a central common repository for structured data. Keep your template cache on the local filesystem of your webservers - it will be available faster and won't slow down your database access.</p>\n\n<p>Do use a op-code cache.</p>\n\n<p>Spend plenty of time studying your site and its logs to understand why its going so slow.</p>\n\n<p>Push as much caching as possible onto the client.</p>\n\n<p>Use mod_gzip to compress everything you can.</p>\n\n<p>C.</p>\n"}, {'answer_id': 3137260, 'author': 'lod', 'author_id': 378566, 'author_profile': 'https://Stackoverflow.com/users/378566', 'pm_score': 2, 'selected': False, 'text': "<p>My first piece of advice is to think about this issue and keep it in mind when designing the site but <strong>don't go overboard</strong>.  It's often difficult to predict the success of a new site and I your time will be better spent getting up finished early and optimising it later.</p>\n\n<p>In general, <strong>Simple is fast</strong>.\nTemplates slow you down.  Databases slow you down.  Complex libraries slow you down.  Layering templates over each other retrieving them from databases and parsing it in a complex library --> the time delays multiply with each other.</p>\n\n<p>Once you have the basic site up and running <strong>do tests</strong> to show you where to spend your efforts.  It's difficult to see where to target.  Often to speed things up you will have to unravel the complexity of the code, this makes it larger and harder to maintain, so you only want to do it where necessary.</p>\n\n<p>In my experience establishing the database connection was relatively expensive.  If you can get away with it, don't connect to the database for general visitors on the most trafficed pages like the front page to the site.  Creating multiple database connections is madness with very little benefit.</p>\n"}]
['https://Stackoverflow.com/questions/24675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2025/']