ItecSoftware Logo

Nginx and memcached module

Written by Peter Gilg on - like this:
nginx memcache

Memcache is traditionally used as a module inside server side scripts, such as PHP, ASP, ColdFusion and others. And it’s doing a terrific job, as long as it’s implemented correctly.

But if we look under the hood of the actual Memcache application, and I’m not talking about the PHP or ASP extension, but rather the executable that’s running as a daemon under Linux, it is a rather simple, database like application running in memory. Now there are two basic actions that need to be performed to use it, one is writing info into memcache, the other is reading it. In a ideal scenario, there are many reads for one write, that’s the whole point, isn’t it. But what if we can isolate the reading away from the server side scripts, and let an external, small high speed module do that for us.

That’s where Nginx and Memcached Module comes in. In simple terms, we use PHP to fill up the cache and then let Nginx serve that content to the requesting client. This configuration is used at many high traffic websites at Breakmedia serving up to 1 million pageviews per day.

To be more specific, we configure to have Nginx listen on port 80. If a request comes in at this port, Nginx checks memcache if the requested page is in memory and if it is, serves it directly to the client. If not, it sends it to Apache (on port 88 for example) to produce the page in PHP. At the same time PHP code inserts the page into memcache, so it’s available to Nginx for the next request. A sample configuration Nginx script would look something like this:

 server{
  location / {
    set $memcached_key$uri;
    memcached_pass     name:11211;
    default_type       text/html;
    error_page         404 = /fallback;
  }

  location = /fallback {
    proxy_pass backend;
  }
}

With this method, we are able to serve many more pages per server than if we just used PHP only. Page load time is reduced, hardware cost reduced, and pages served per server is increased.

Additional Resources: Nginx Memcache Apache

Listed in Linux, MySQL, SEO, Shell Scripting, Useful Stuff, Web Development

Tags: apache, memcache, nginx, php

Leave a Reply

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