Memcached brings your dynamic database-driven sites up to speed

On this article we discuss another web accelerator available in your Control Panel that can give a significant boost to your sites and applications. The first article was about Varnish – the web accelerator for content loaded sites with irregularly updated pages.

Memcached logo

Today, websites are faced with the challenge of delivering loads of dynamic content to visitors and with the decreasing attention span of those who are impatient to wait when the content is served too slow.

Normally, servers would load pages every time they are requested, which could have a slow-down effect on the speed at which a frequently accessed page is served to the visitor.

Also, the repeated queries to the database server can lead to a non-cost-effective resource usage. Luckily, there are tools like Memcached that can help you streamline the data reading process and hence reduce the load on the server and the waste of valuable resources.

What is Memcached?

Basically, Memcached works as a caching layer between the requests of the visitors and the server itself.

Technically speaking, Memcached caches data and objects in the server’s RAM so that the frequently requested data can be served directly from the memory instead of the database server/API.

Here is an illustration of the way Memcached works during the first and each following request:

First user request:

When a user opens a page for the first time, the request is sent straight to the database server and, in the meantime, the data is stored in the Memcached server:

Diagram of first request sequence

Second user request:

The next time the user makes a request for the same page, the data will be retrieved directly from the Memcached memory instead of the database server:

Diagram of second request sequence

This will significantly reduce the number of times a database is read and in the meantime will make pages load much faster.

If you have a traffic-intensive, database-driven website like a large e-store, a busy blog, a news portal, etc., which serves hundreds of visitors per day, then using Memcached is indispensable.

Memcached works as a caching layer for some of the most traffic-heavy sites such as YouTube, Reddit, Facebook, and Twitter. Some popular CMSs like Joomla and WordPress support it too.

How do I work with Memcached?

Working with Memcached requires a proper installation and a good control of its settings. This is why, we offer Memcached in our web hosting plans either free or as an add-on (check your plan features), so our system will take care of the installation and the memory allocation procedures for you.

Here is an example of how to create a basic Memcached instance on our servers:

In your Web Hosting Control Panel, select Memcached from the Advanced section and click on the Create an instance button on the top right.

In the popup window, leave the Status as it is selected by default and then just select the memory allocation that you want to use for this instance.

After you create the instance, you will see it listed in the Memcached table:

Set it up on your Control Panel

Now that you have your Memcached database setup, you can configure a script that will help you use Memcached effectively.

Here is an example of how you can use Memcached for your dynamic sites:

Let’s say that you want to enable object caching for your blog, so that after a visitor loads a given blog post from the database, the next time they request it – that post will be served directly from Memcached.

In this example, we’ll configure an object, i.e. a blog post, to be saved in the cache on the first visit and then retrieved back upon the second visit.

Here is an example of a blog post caching using Memcached:

<?php
define('MYSQL_HOSTNAME', 'localhost');
define('MYSQL_USERNAME', 'username');
define('MYSQL_DB', 'database');
define('MYSQL_PASSWORD', 'password');
define('MEMCACHED_SOCKET', 'unix:///home/sys/memcached.sock');
define('MEMCACHED_POSTS_KEY', 'posts');
define('MEMCACHED_POSTS_TTL', 10); //for how many seconds the posts are cached in memory
 
$db = $memcached = NULL;
 
if (!($posts = memcached_get_posts())) {
        if (!($posts = db_get_posts()))
                exit("Can't get posts");
 
        memcached_save_posts($posts);
}
 
foreach ($posts as $post) {
        echo "<p><a href='{$post['link']}'>{$post['title']}</a></p>";
}
 
function memcached_get_posts() {
        $mem = memcached_connect();
        return $mem->get(MEMCACHED_POSTS_KEY);
}
 
function memcached_save_posts($posts) {
        $mem = memcached_connect();
        $mem->set(MEMCACHED_POSTS_KEY, $posts, MEMCACHE_COMPRESSED, MEMCACHED_POSTS_TTL);
}
 
function memcached_connect() {
        global $memcached;
 
        if ($memcached)
                return $memcached;
 
        $memcached = new Memcache();
 
        $memcached->connect(MEMCACHED_SOCKET, 0) or exit("Could not connect to memcached");
        return $memcached;
}
 
function db_get_posts() {
        $db = db_connect();
 
        $query = 'SELECT * FROM posts ORDER BY id DESC';
        if (!($res = mysql_query($query, $db)))
                exit("Query failed.");
 
        $res = array();
        while ($row = mysql_fetch_assoc($res))
                $res[] = $row;
 
        return $res;
}
 
function db_connect() {
        global $db;
 
        if ($db)
             return $db;
 
        $db = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD) or exit("Can't connect to DB.");
        mysql_select_db(MYSQL_DB, $db) or exit("DB error.");
 
        return $db;
}
?>

In this example:

  • localhost is the name of your MySQL host;
  • in username and database you should put the name of the database where the blog posts are stored;
  • unix:///home/sys/memcached.sock is the Memcached socket that you will need to connect to;
  • posts is the Memcached key that the script will use to label the cached data and retrieve a blog post from the memory; you can name your keys the way you like (up to 250 characters are allowed);
  • 10 is the TTL (Time To Live) value, which defines the period (in seconds) in which the data - e.g. the blog post - will be stored in the cache;

Note: Please note that this code is just an example and it might not suit your website script without some modifications.

Memcached is included by default with all OpenVZ VPS and Virtuozzo VPS packages, semi-dedicated servers and dedicated servers. Other plans offer it as an upgrade option.

Kind Regards,
Support team

Using Varnish, a web accelerator for your site

Dear Customers,

If a website could be seen as a chemical reaction of code, style sheet and content, then web accelerator tools like Varnish, Memcached and Node.JS could be treated as catalyzers that make the ingredients react faster and deliver better results.

In a series of articles we’ll focus on the main capabilities of those tools and will include an example of how you could use them to leverage on the huge catalyzing effect they could have on your sites’ performance. Let’s start with Varnish.

Varnish Accelerator is available on our hosting!Varnish Cache, also known as a caching HTTP reverse proxy, is a web accelerator that can considerably speed up a website by reducing the load on the server.

Why do I need Varnish if servers now work faster?

In theory, a server should return a response immediately without needing to do any real work in the background. In practice, however, the server may need to do a great deal of work before returning a response to the client. To execute a simple request, the server may need to start a new process, to load script files from the disk, to perform database queries, as well as many other actions that could exhaust the system resources.

And in the case of a poorly scripted site, the server response burden will get even bigger. This is just how web servers are made to work. No better solution has been invented so far.

Here is where web accelerators like Varnish come into play – they streamline the response operation. Their main mission is to cache the not-so-often-updated pages of content-heavy websites and to make them load faster. Depending on the site’s architecture, it can be sped up 300 to 1000 times its current speed.

How exactly does Varnish work?

When a request is sent to the server for the first time, it is first checked by Varnish and then forwarded to the server. The server then returns a response to Varnish, which in turn gives the response to the client that sent the original request. At the end of the process, Varnish stores the response from the backend in its cache for future use.

That response is stored in memory for faster access, instead of being cached to disk. This helps Varnish to quickly serve the next response directly from its cache and to eliminate the need for any action from the backend server.

As a result, the load will be reduced significantly, the response times will be improved, and the server will be able to handle more requests per second. All those optimizations allow Varnish to process server requests at an incredibly fast speed, which will give a direct boost to the performance of your sites and applications.

How do I activate Varnish in my site?

Working with Varnish requires a proper installation and a good control of its settings. We offer Varnish with all our web hosting plans, so our system will take care of the installation and memory allocation procedures.

Here is an example of how to create a basic Varnish instance on our servers.

Let’s say you want to use Varnish to cache your WordPress blog.

In the Varnish section of the Web Hosting Control Panel, click on the Create an Instance button on the top right.

In the popup window, select the memory allocation that you will need for this instance. By default, Varnish will scan your website traffic using a custom algorithm and, starting with the most visited pages, will cache your website content until the memory quota is reached. So, even if you exceed your memory allocation limit, your most sought-after pages will still be served:

Creating a Varnish instance - Memory allocation

Next, you need to select the dedicated IP address that we’ll use to set up the instance on. You could get one from the Service Upgrades section of the Control Panel. If you do not want to use a dedicated IP address, we will assign a specific port to your host. In this case, however, you will need to make sure that all static links to your blog are changed to reflect the port allocation:

Creating a Varnish instance - Dedicated IP address setup

NOTE: If you decide to use a dedicated IP address for the Varnish instance, you will need to point your WordPress site to that IP address from the Hosted Domains section of the Control Panel.

If you are well familiar with Varnish, you could make a manual configuration on your own by selecting the ‘Manual configuration’ option. Otherwise, we will do that for you automatically.

In general, cookies enabled for a site interfere with the proper caching of the content. This is why, if you have enabled cookies for your site, you will need to have them neutralized for the purpose of caching. You can do that by marking the ‘Remove cookies’ box, which will configure Varnish to ignore the cookies on your site automatically.

Creating a Varnish instance - Removing cookies

The TTL box refers to the time within which the cached content will be left in the memory. The default value is set to 60 seconds.

Finally, specify the URL(s) of your site that you do not want to be cached by Varnish. In our case, these should be the /wp-admin and /wp-login.php URLs of your WordPress site, which are input in the ‘Exclude URL’ field as follows:

Creating a Varnish instance - Excluding URLs

Varnish is included by default with all OpenVZ VPS and Virtuozzo VPS packages, semi-dedicated servers and dedicated servers.

All other packages offer it as an upgrade option. Also, you can always upgrade the current Varnish memory quota pertaining to your plan from the Service Upgrades section of the Control Panel.

Kind Regards,
Web Hosting team

A LiveChat option added to the Control Panel

Dear Customers,

You can now connect with our Sales Department team from within your Control Panel by using the LiveChat button featured on all service ordering pages.

Whenever you need advice before upgrading your hosting account or moving to a more powerful service - a Sales Representative will be happy to help.

Note:
Please keep in mind that the LiveChat service is intended for general and sales enquiries only.

For technical issues and questions, please open a trouble ticket from the My Tickets section of the Control Panel.

Kind Regards,
Web Hosting team

The site security options on our platform that are under your control

Dear Customers,

100 percent secure!In a previous article dedicated to guaranteed security, we touched upon all the features and functionalities implemented on our servers that help you maintain a secure web presence.

Now we review in greater detail the security tools on our platform that you can use to customize the level of protection on your site according to your particular needs.

All of these security tools are intuitively integrated into the Web Hosting Control Panel.

ModSecurity

This is a very effective anti-hack firewall, which is activated on all our servers. It has been configured to automatically prevent all common URL forgery or “brute force” attacks and forum spamming attempts targeted at your website and applications. By default, ModSecurity is enabled for all hosts within your account. However, you can control its behaviour from the ModSecurity section of the Control Panel. You can select if you want the firewall to either be working in detect mode only, i.e. to only detect all potential inbound threats without taking action, or even disable it completely.

Modsecurity option

ModSecurity’ is located in the Advanced section of the Control Panel.

Outgoing Connections

To prevent sensitive data from leaking off your site to an external host, we have disabled all outgoing connections from the hosting account by default. However, you can take full control of the outbound traffic on the Outgoing Connections section of the Control Panel. With a click of the mouse, you can disable the restriction on outgoing connections or only allow external connections for certain IP addresses.

Outgoing connections control option

‘Outgoing Connections’ is located in the Advanced section of the Control Panel.

IP Blocking

The IP Blocking tool allows you to prevent malicious users or scripts from attacking your sites by blocking the IP address they are coming from. With a click of the mouse, you can deny a specific IP address access to your site or to a section of your website. You can even block an entire range of IP addresses, since a hacker might use a dynamic IP from a certain network to attack your site.

ip blocking option

'IP Blocking’ is located in the Advanced section of the Control Panel.

Password Protected Areas

The Password Protection Areas tool allows you to easily protect a specific folder of your hosting account, i.e. a directory on your site, with a username and a password. This way, when a visitor tries to open a protected folder or a file located inside the folder, a pop-up window will come up asking for the username and password that have been set by you.

Password protected areas option

‘Password Protection Areas’ is located in the Advanced section of the Control Panel.

Hotlink Protection

With the Hotlink Protection tool, you can easily prevent other websites from stealing your traffic resources by directly linking to files and images on your sites.

You can forbid hotlinking either for the whole domain name or for a specific folder, for instance – an image gallery folder like my-domain-name/gallery/.

Hotlink protection option

‘Hotlink Protection’ is located in the Advanced section of the Control Panel.

.htaccess Generator

This multi-functional tool allows you to shield your website contents by password-protecting certain folders, by enabling hotlink protection, by blocking different IP addresses from accessing your website, etc.

The ‘.htaccess Generator’ is located in the Advanced section of the Control Panel.

Extra protection services:

Apart from the security services included by default with each hosting package, you can also take advantage of some optional services such as:

Whois Protection

You can easily enable Whois privacy protection for your domains to hide your personal or business information, which is publicly available by default.

SSL certificates

A SSL certificate is a must-have security attribute for any e-commerce site. It encrypts and protects all the sensitive information submitted onto a site (login form details, credit card information, etc.) and serves as a solid proof of a site’s reliability. We offer two types of SSL certificates – standard and wildcard, at good wholesale prices. Recently, we have made SSLs even more affordable by allowing you to tie a SSL certificate to a shared IP address for free (* the shared ip address is free, not the certificate).

Both tools can be found in the ‘My Domains’ section of the Control Panel.

These are all tools and features that you can make use of to tweak the level of protection we have implemented on our servers depending on your particular security requirements.

Kind Regards,
Web Hosting team

You might like

  • AUD $71.83 each Basic plan
  • AUD $31.51 each Base VPS
  • AUD $63.01 each Semi-Dedicated 1