Speed up Magento without Varnish Cache – The Alternatives

More often than not you should probably stay clear of implementing varnish in Magento until you’ve exhausted all other options. It seems like the Holy Grail in terms of performance and will literally make your site fly, the problem is Magento is a complicated beast and any extension you use that claims a quick integration with Magento couldn’t be further from the truth! (unless of course your using a stock site, unmodified.) It’s likely you will need a ton of customisation and debugging to any of the Varnish plugins you can buy off the shelf. Not only that you will need to set up additional servers, learn how to debug varnish and it’s various admin tools and generally spend a lot of time getting it to work properly.

Turpentine offers the most reliable product from the one’s I tested but with limited documentation and help your going to struggle to get it set up correctly. The official Varnish Pagecache extension from the makers of Varnish isn’t much better, with a number of unfixed bugs and generally poor documentation, but before getting into all that you should really consider your options on improving the site speed without the use of Varnish.

Firstly set a benchmark for how your site is now, go over to http://tools.pingdom.com/fpt/ and record the speed of the homepage, category pages etc as you make each change you can run the tests again to track your progress

Optimisation for any platform

  • Tune .htaccess for speed , Creare have an excellent blueprint here
  • Use a CDN for images Pica CDN works with Amazon, Rackspace and many others
  • Install SOLR search free for CE edition alternatively this plugin works well and offers a more comprehensive set of features (be prepared for some debugging depending on your site) both these plugins require tomcat server to be installed
  • Use a CDN for content delivery e.g CloudFlare
  • Remove redundant code , php comments, html comments anything that adds to the page load however small
  • Minify your media files (JS,CSS etc) there’s a few extensions for this most widely used is the fooman speedster
  • Remove any unused styles or JS
  • Organise your main theme assets into CSS sprites
  • Reduce the quality of the images (save your images in the smallest file size possible) ideally combine the main images into a sprite
  • Use the cloud for your DNS, this can shave off an extra 50MS+ depending on your current provider, CloudFlare and other providers offer this service.
  • Use DNS pre-fetching , resolve the IP address for your assets before you use them. Something for modern browsers – Find out more in this guide from Mozilla
  • Use HTML5 browser caching through an app.manifest there’s an excellent guide on html5rocks
  • Move blocking JS to the footer, Google’s pagespeed insights offers a great tool for this (you can only do this for fonts, and external JS libaries. Don’t try moving Magento’s Core JS to the footer). Some libraries need to be in the header.

Client Side

A modern approach

Most browsers now support HTML5’s new app cache,  a cache on the users browser but browser already do that right? Yes they do – However AppCache works differently in that it’s designed for Apps where the user isn’t always online and in doing so when a cache is created on the clients side and when a page is loaded, cached resources are loaded directly from the cache, no connections to the live site, no checking if there’s a newer version –  a big speed increase.

However there’s some downsides to using this approach on how the cache expires and clearing it,  rather than re-iterate a very good explanation can be found on http://alistapart.com/article/application-cache-is-a-douchebag. I’m working on a module for Magento the makes use of AppCache if you have any thoughts please leave a comment.

Server Side

Tune Apache

Apache users can achieve quite a performance boost from tweaking the configuration:

  • Put .htaccess rules directly in your vhost conf and turn off htaccess – Magento has hundreds of directories and files each time a call is made to a file apache has to recursively loop through all these to check for .htaccess files. It might not sound like much but it can make a difference. Not only this you will be securing your server from exploits.
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>

You can find more about some of the settings here http://httpd.apache.org/docs/2.2/misc/perf-tuning.html

  • Check the apache config,  are the settings correct for your server spec? There’s numerous guide on this so I won’t detail this here, you could also try adjusting settings and running the benchmark several times to see what works best, in normal load and under stress.
  • There’s 25 tips here on tweaking apache

Use Nginx + PHP-FPM

Nginx uses much less resources as it works a bit differently from Apache, if your already familiar with Apache and don’t have the time to learn how to use Nginx it’s probably best to take it as far as you can with Apache before considering this option, if you already use it then it works pretty well out of the box. What you might need though is some extra configuration settings there’s a guide here on that.

Make sure you install php-fpm if your running nginx.

apt-get install php5-fpm

In most cases the above configuration can be left as is in nginx, if your using port 9000, you will want to edit the php-fpm configuration usually www.conf found in:

/etc/php5/fpm/pool.d/

Change the user and group to match that of your nginx installation as default this is www-data

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

There are three different ways of running php-fpm and that is ondemand,dynamic or static I won’t go into the detail of these, but i’ve found ondemand to work better for Magento which basically runs as many process’s as is required up to a maximum rather than fixing a certain amount to be running all the time. It’s worth noting here you can enable a status page that gives you some information about what’s going on.

pm.status_path = /status

In your php-fpm uncomment this line, you can then visit website.com/status to get an output, there’s a great tutorial on using php-fpm status page here.

Tweak Mysql

There’s many guides out there on mysql and I make no claims to be an expert these settings have helped

skip-name-resolve
log_slow_queries       = /var/log/mysql/mysql-slow.log

If your mysql is listening locally e.g bind-address in my.cnf says localhost or 127.0.0.1 etc then you don’t need to resolve the name , this will avoid any delay from the DNS.

The rest of your config should be configured as per the report from mysqltuner, if that’s new to you check out this post on how to use it.

Redis

I have recently come across Redis It’s an extremely fast cache storage engine and works seamlessly with Magento, it does require some server configuration but I would say this is one of the easiest to configure and get up and running quickly. There’s also support for sessions via Redis Sessions have not tried this yet but also looks very solid as of CE 1.8 Redis comes part of the default install so it’s as simple as configuring it via the local.xml if you want to find out more there’s some benchmark information here and a guide to using Magento with Redis on the Magento Site.

HHVM

Review coming soon on this.

APC caching

Install it onto your server

sudo apt-get install php-apc
sudo service apache2 restart

Whilst it’s installing make a note of the version, we will need this later to tweak the settings e.g

Get:1 http://uk.archive.ubuntu.com/ubuntu/ precise/universe php-apc i386 3.1.7-1 [79.2 kB]

Enable it via/magento/app/etc/local.xml and add the following lines (note if you have more than one Magento Install on the same server make sure the prefix is unique for each one)

<global>
        ...
        <cache>
            <backend>apc</backend>
            <prefix>alphanumeric</prefix>
        </cache>
        ...
</global>

Tweaking APC couldn’t be easier, first check what version is installed (as noted earlier) download and browse the archive which matches on http://pecl.php.net/package/APC

Inside there will be a file called apc.php , you need to put this somewhere that is served by Apache or Nginx ideally on a password protected area of your site.

What you want to achieve here is a high Hit ratio and little fragmentation, usually this happens because there is not enough memory allocated to APC. You can alter this setting by changing the config file in /etc/php5/conf.d/apc.ini or wherever your php install is located until you achieve the desired result.

it should look something like this:

extension=apc.so
apc.enabled=1
apc.shm_size=500M
apc.max_file_size=3M
apc.enable_cli=1

shm_size
The maximum amount of memory APC can use, one it runs out it has to purge cached items which leads to fragmentation.

max_file_size
The maximum file size that can be cached by APC, this defaults to a low value and I would recommend changing this to 3M or 5M.

Memcache

There’s a decent guide here on installing Memcache once you’ve done that follow this guide on enabling it in Magento

Single split servers

This is generally a good idea for failover, and that’s to have a separate MySQL and Web Server, this takes the load off one server and allows you to upscale each individually. Ideally if you have enough traffic also separate out the SOLR instance. Splitting the connection between mysql and your web server can have negative effect though depending on the connection between each you will need a gigabit connection to remove network latency so if you haven’t got much load coming from apache/nginx then it’s probably not worth it.

Google PageSpeed

This can be installed server side on Apache as a module or Nginx (Nginx requires a re-build) , this allows you to do a lot of optimisation on the fly like removing whitespace, minifying JS/CSS and even optimising images. more about Google PageSpeed

App code

Non-Varnish Caching (build your own)

Magento’s built in cache

There’s a few ways to add caching that don’t involve varnish, first is that Magento comes with comprehensive caching out of the box.

There’s really only four methods available to us.

save($value, $key, $tags = array(), $lifeTime=null)
load($key)
remove($key)
clean($tags = array()

So let’s add something to the cache in this example we are retrieving the lowest price from a grouped product, it’s pretty intensive as it has to loop through each simple product to retrieve it’s price. The prices don’t change very often so we don’t have to do this everytime!

// load the cache
$cache = Mage::app()->getCache();

// The Code we are caching
if(!$cache->load($_product->getId())) {

// The cache doesn't exist
$aProductIds = $_product->getTypeInstance()->getChildrenIds($_product->getId());
                                    $prices = array();
                                    foreach ($aProductIds as $ids) {
                                        foreach ($ids as $id) {

                                            $aProduct = Mage::getModel('catalog/product')->load($id);
                                            if($aProduct->isSaleable()) {
                                            $prices[] = $aProduct->getPriceModel()->getPrice($aProduct);
                                            }
                                        }
                                    }
                                    asort($prices);
                                    $prices = array_shift($prices);
                                    $grouped_price = $helper->currency($prices,true,false);
// save
$cache->save($grouped_price, $_product->getId(), array("grouped_prices"), 3600);
} else {

// load the saved price
$grouped_price = $cache->load($_product->getId());

}

echo $grouped_price;

So in the above block we are:

  1. First checking if the the cache named “id of product” exists
  2. If it returns false we then run the code to save the price to the cache with a lifetime of 1 hour (3600 seconds) and with a tag of array(“grouped_prices”)
  3. If the cache doesn’t exist we run the code as usual
  4. In all scenarios $grouped_price is returned with the price

If you don’t set a lifetime value then the item would be cached until it’s removed manually, to remove this value earlier than 1 hour we would do so by using remove

$cache->remove($_product->getId());

We can also remove by the tag if for instance you wanted to clear the cache for all grouped product prices you can use clean.

$cache->clean(array("grouped_prices"));

Full Page caching and others

Unicache Inchoo

This builds on the default caching system but really only offers convenience and an admin section allowing you to clear the cache for individual items. check it out here

Lesti FPC

Gordon Lesti wrote his own FPC for Magento, it’s easy to install follow the guide on using it, although this suffers from the same problems as using Varnish if you have custom blocks you will need to configure them for the site to work properly. However it does not require additional servers or software so it cuts a lot of set up time.

Do you know of any other ways to speed up Magento?, get in touch.

Quafzi Performance Tweaks

Recently came across this module, that offers a lot of optimisations based on recommendations from Ecommerce devs

https://github.com/quafzi/magento-performance-tweaks

One thing I had to disable on this particular module is the CMS block caching if for example like me you are using it to load a template that changes for each product category. It’s well commented so it’s easy to see the particular changes that might affect your site.

Add affiliate window to Magento

It’s straight forward to add affiliate window into Magento, there are a few extensions but you don’t need them.

Edit your checkout success page which would usually be in app/design/frontend/yourpackage/yourtheme/checkout/success.phtml

Add near the top inside the php tags

// get the order
$order = Mage::getModel('sales/order')-&gt;loadByIncrementId($this-&gt;getOrderId());
// get the total
$total = $order-&gt;getGrandTotal();
// get order data
$_totalData = $order-&gt;getData();
// helper for the price formatting
$helper = Mage::helper('core');

Then add anywhere in html part of the page (replace MERCHANT_ID with your merchant ID). I’ve omitted the Category here as it’s optional

<!-- Image Pixel Tracking - Mandatory -->
    <img src="https://www.awin1.com/sread.img?tt=ns&tv=2&merchant=MERCHANT_ID&amount=<?php echo $helper->currency($order->getGrandTotal(),false,false); ?>&cr=<?php echo $_totalData['order_currency_code']; ?>&ref=<?php echo $this->getOrderId() ?>&parts=default:<?php echo $helper->currency($order->getGrandTotal(),false,false); ?>&vc=<?php echo $_totalData['coupon_code']; ?>&ch=aw&testmode=0&cr=<?php echo $_totalData['order_currency_code']; ?>" />

    <form style="display:none;" name="aw_basket_form">
        <textarea wrap="physical" id="aw_basket">
            <?php

            $items = $order->getAllItems();

            foreach ($items as $item) {

                echo "AW:P|MERCHANT_ID|".$this->getOrderId()."|".$item->getProductId()."|".$item->getName()."|".$helper->currency($item->getPrice(),false,false)."|".$item->getQtyToInvoice()."|".$item->getSku()."|default|";

            }

            ?>
        </textarea>
    </form>
    <!-- Javascript Tracking - Mandatory -->
    <script type="text/javascript">
        //<![CDATA[
        /*** Do not change ***/
        var AWIN = {};
        AWIN.Tracking = {};
        AWIN.Tracking.Sale = {};

        /*** Set your transaction parameters ***/
        AWIN.Tracking.Sale.amount = '<?php echo $helper->currency($order->getGrandTotal(),false,false); ?>';
        AWIN.Tracking.Sale.currency = '<?php echo $_totalData['order_currency_code']; ?>';
        AWIN.Tracking.Sale.orderRef = '<?php echo $this->getOrderId() ?>';
        AWIN.Tracking.Sale.parts = 'default:<?php echo $helper->currency($order->getGrandTotal(),false,false); ?>';
        AWIN.Tracking.Sale.voucher = '<?php echo $_totalData['coupon_code']; ?>';
        AWIN.Tracking.Sale.test = '0';
        AWIN.Tracking.Sale.channel = 'aw';
        //]]>
    </script>

Finally in your footer app/design/frontend/yourpackage/yourtheme/page/html/footer.phtml

<script src="https://www.dwin1.com/5715.js" type="text/javascript" defer="defer"></script>

How to redirect simple products to grouped product in Magento

For a quick and dirty way of doing this, you can modify the viewAction() on the product controller tested in 1.7,1.8,.19

Make a copy of

app/code/core/Mage/Catalog/controllers/ProductController.php

and place it in

app/code/local/Mage/Catalog/controllers/ProductController.php

Modify the viewAction() after this section:

// Prepare helper and params
 $viewHelper = Mage::helper('catalog/product_view');

$params = new Varien_Object();
 $params->setCategoryId($categoryId);
 $params->setSpecifyOptions($specifyOptions);

Add the following:

// Does the product have a parent product?
 $p = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($productId);

if(!empty($p)) {

// redirect to parent

$prod = Mage::helper('catalog/product')->getProduct($p[0], null, null);
 header('HTTP/1.1 301 Moved Permanently');
 header('Location: '.$prod->getData('url_path'));
 exit;

 }

This will give you a 301 redirect to the parent.

Character encoding issues utf8 & MySQL – How To

Any developer working with php and MySQL will have come across this issue whilst developing.
And often the problem doesn’t rear it’s ugly head until after you’ve captured a lot of data.

If your getting strange characters in your database like question marks and , then follow this simple guide to check each part is set to UTF8.

UT8 is best practice for handling all types of characters and that’s the charset we will be using.

If your just trying to retrieve the unreadable data then see a solution at  the bottom of this post.

MySQL DB

First let’s check the MySQL server, open up your favourite GUI like MySQL Tools or via command line and run:

SHOW SESSION VARIABLES LIKE 'character_set%';

charset

The important parts to notice here

  • character_set_database
  • character_set_results
  • character_set_connection.

These should all be utf8 , if they aren’t then you need configure your database to use utf8.

You can reverse engineer your table using

SHOW CREATE TABLE table_name;

At the very end you will see “DEFAULT CHARSET=charset” change this to utf8.

As further final checks run

show variables like "collation_database";

This should show ‘utf8_general_ci’

And you can check each column individually like so.

SHOW FULL COLUMNS FROM table_name;

PHP Connection

All connections to MySQL need to use utf8, you can do this by using SET NAMES.

For PDO connections you can either include this in the SQL statement before “SET NAMES UTF8;” or you can include it in the connection e.g

$pdo = new PDO('mysql:host=myhost.com;dbname=db_name', 'db_user', 'db_password',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");

For standard mysqli connections use:

$mysqli->set_charset("utf8");

It’s important you place that straight after the connection before any queries are run.

What to do if you haven’t set this up from the start?

Thankfully there is a way to retrieve data that might otherwise look garbled in php you can use:

//ISO code for most browsers default encoding

mb_convert_encoding($text, "ISO-8859-1")

Note that you must connect to the DB the way you where doing before you fixed any issues. If you try and retrieve data using SET NAME utf8 then the above will not work as your requesting the data in a different format.

ISO-8859-1 is the character encoding used for most browsers, however there are others so this may not work in every case.

Forwarding the User IP from a Rackspace Cloud Load Balancer

If you have a setup which includes one of the rackspace cloud load balancers you will notice that in apache or php the ip of the client is the load balancers, the easiest way to fix this is install an apache module called mod_rpaf.

Here’s how under Ubuntu & Apache 2.2:

Install the apache dev tools (may not be required)

Check which version of apache your running

apache2 -l

The output here tells me i’m using the perfork module.

Compiled in modules:
  core.c
  mod_log_config.c
  mod_logio.c
  prefork.c
  http_core.c
  mod_so.c

Install the prefork development tools

apt-get install apache2-prefork-dev

The alternative here is to install apache2-threaded-dev if you see threaded instead of prefork.c

 

Install the mod_rpaf 

Download the mod_rpaf module and extract the latest version to check the latest see http://stderr.net/apache/rpaf/download/

wget http://stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz
tar -xzf mod_rpaf-0.6.tar.gz

Install and compile the apache module

cd apache-2.2-mod_remoteip.c
apxs2 -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c

The script will compile and install the module giving you the output of the path to the module e.g

/usr/lib/apache2/modules/mod_rpaf-2.0.so

Configure

Make a new config file for rpaf and edit

touch /etc/apache2/conf.d/rpaf.conf
nano /etc/apache2/conf.d/rpaf.conf

Enter the following details in rpaf.conf, change 10.000.000.0 to your load balancer IP comma seperate for more than one

# Your module path
LoadModule rpaf_module /usr/lib/apache2/modules/mod_rpaf-2.0.so


RPAFenable On
RPAFsethostname On
# Your loadbalancer IP seperate with a space for more than one
RPAFproxy_ips 10.000.000.0
RPAFheader X-CLUSTER-CLIENT-IP

 Check the apache configuration

service apache2 reload

If you see any errors here check your configuration.

 Restart apache and apply the changes

service apache2 restart

You should then see the correct user ip showing up in $_SERVER[‘REMOTE_ADDR’] for php

 Update:

To get the correct IP from the Load Balancer to .htaccess

If your looking to restrict access from .htaccess this still doesn’t give apache the correct IP to do that you simply use a pre configured environment variable:

order deny,allow
deny from all
allow from env=allowclient
SetEnvIf X-Cluster-Client-Ip 000.000.000.000 allowclient

High traffic sites using Magento

We recently had a client debate on what is the best ecommerce solution I am a supporter of Magento the beast it may be, but it is robust. To back up my opinion I did some research although not conclusive.

Magento itself boasts some big clients using the Enterprise edition http://www.magentocommerce.com/product/enterprise-whos-using-magento

I analysed a few of these sites with leading analysis tool compete which estimates the traffic for a given url , the most high traffic site using Magento is Harbor Freight  with some 4 Million uniques at points over the last 2 years, and over 52 Million pageviews (per day) which isn’t to be sniffed at.

stat1

 

Other sites I checked out are:

(figures quoted per day)
Eastwood.com – 240K uniques, 2M page views
Toms.com – 1M uniques, 5M page view

Secondly with the help of BuiltWith there’s some interesting charts on Magento use:

stat2

 

stat3

stat4

 

This shows firstly that the top 1M sites Magento tops the usage worldwide, drilling down in to the most popular 10,000 Magento still tops the opensource solutions with the only other platform osCommerce coming close. Finally in the migration Magento has the highest migration to the platform from other platforms.

In all it’s good evidence to support using Magento now and for high traffic websites. What this does not show is the set up and configuration that may be needed to tweak Magento to run on high traffic sites.

Magento fix for Unable to reindex Product Flat Data – Stuck on Processing. ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row

If you’ve moved across sites from a development to live site or your encountering this error after importing/exporting then here’s the solution that works every time.

1. Search for “catalog_product_flat” . Under my installation its called catalog_product_flat_1

2. Then in mysql run:

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE catalog_product_flat_1

3. Last step open up SSH and run (or do this from the Magento admin)

php path/to/shell/indexer.php --reindex catalog_product_flat or navigate to the /shell directory and run php indexer.php --reindex catalog_product_flat

You should get “Product Flat Data index was rebuilt successfully”

Clean up linux boot partition

If your boot partition is getting full and your running the machine as a server and have no GUI you can run this command to remove all those unecessary kernel images if you update frequently they can take up quite a bit of space.

dpkg --get-selections|grep 'linux-image*'|awk '{print $1}'|egrep -v "linux-image-$(uname -r)|linux-image-generic" |while read n;do apt-get -y remove $n;done

You may also need to update GRUB  /usr/sbin/update-grub after this has completed.

Checking for a whole number in php

There may be a simpler way but I didn’t come across one except this handy function when dealing with decimal numbers.

////////////////////////////////////////////////////////////////////////////////////////////// 
//is_wholeNumber(string $value)
//Returns TRUE if a WHOLE NUMBER
//Returns FALSE if anything else (Float, String, Hex, etc)
//////////////////////////////////////////////////////////////////////////////////////////////   
function is_wholeNumber($value)
{
	if(preg_match ("/[^0-9]/", $value))
	{	return FALSE;	}
	return TRUE;
}

There is also ctype_digit but this seems to return false when using addition like so:

$numeric_string = '1'+'1';
$integer = 1+1;

if(ctype_digit($numeric_string)) { echo "true";} else { echo "false"; }  // false
if(ctype_digit($integer)){ echo "true";} else { echo "false"; }          // false 

if(is_numeric($numeric_string)){ echo "true";} else { echo "false"; }    // true
if(is_numeric($integer)){ echo "true";} else { echo "false"; }           // true

Both equal 2 yet ctype_digit returns false? , is_numeric works here but as i’m dealing with decimal places this returns true when it is not a whole number.

Credit for the function due to http://davidwalsh.name/php-validatie-numeric-digits

Javascript function to return device type

Here’s a simple JS function to return the type of device based on screen size and some other helpful variables for the main manufacturers.

// mobile check
function checkForMobile() {

	var x = screen.width;
	var y = screen.height;
	var agent = navigator.userAgent.toLowerCase();
	var mobileOS = typeof orientation != 'undefined' ? true : false;
	var touchOS = ('ontouchstart' in document.documentElement) ? true : false;
	var otherBrowser = (agent.indexOf("series60") != -1) || (agent.indexOf("symbian") != -1) || (agent.indexOf("windows ce") != -1) || (agent.indexOf("blackberry") != -1);
	var iOS = (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPad") != -1) ? true : false;
	var android = (agent.indexOf("android") != -1) || (!iOS &amp;&amp; !otherBrowser &amp;&amp; touchOS &amp;&amp; mobileOS) ? true : false;
	var istablet = (/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase()));
	var tablet = (istablet==true &amp;&amp; x &gt;= 768) ? true : false;

	// is it mobile

	if(x &gt;= 320) {
		whichDevice = "Mobile";
	}

	if(tablet==true) {

		whichDevice = "Tablet";

	} 	

	if(x &gt;= 800 &amp;&amp; tablet==false) {

		whichDevice = "Desktop";

	} 

	return whichDevice;

}
       //sets the device type
	checkForMobile();

Found something better? , please let me know.