Lessons From The Book, “Pragmatic Programmer”​

Below are the lessons from the book,

  • As a software developer, care about what you are building.
  • Be individual pragmatic craftsmen in teams too.
  • Think beyond immediate problem.
  • Take charge of yourself, your work, your career growth and don’t blame others.
  • Rubber ducking. Talk to yourself if something you are going to say do will sound silly, how is it going to sound to your boss? Explain the options of solving a problem rather than giving excuses.
  • Don’t leave poor code, wrong decisions, bad designs.
  • One small loophole can cause the whole software to get compromised.
  • Quality should be a requirements issue.
  • Think of learning as an investment in yourself. Diversify your investments, invest frequently, buy low and sell high (dive into new tech early and you will be the top player when the tech matures).
  • Learn at-least one new language per year.
  • Read a technical book each quarter.
  • Read non-tech books too. See things from human side.
  • Take courses.
  • Participate in local groups of developers.
  • Try different things (Linux, Windows, Mac), (Android, iOS), different IDE’s.
  • Stay current. Read about current tech.
  • Surf the web for learning more about new things.
  • Critical thinking: Don’t think of anything of great value until you understand it is actually valuable.
  • Communicate! Learn to write, get back to people.
  • Its both what you say and how you say it (proofread, grammar check).
  • DRY (Don’t Repeat Yourself).
  • Avoid global data.
  • Avoid similar functions.
  • There Are No Final Decisions (Software keeps evolving).
  • Do good time estimation.
  • Do version controlling
  • When you find a bug (even its from someone else), fix the bug and try not to play the blame game.
  • Don’t assume! Proof it.
  • Try to crash your program as early as possible so you find bugs.
  • Finish what you start.
  • Decouple modules.
  • Refactor your code.
  • Don’t gather requirements, dig for it.
  • Test early, test often, test automatically.
  • Do code commenting.
Thanks: Fahad Uddin
Reference: https://www.linkedin.com/pulse/lessons-from-book-pragmatic-programmer-fahad-uddin/
Advertisements

A Beginner’s Guide to Machine Learning

Should I learn now… or later? Learning is a universal skill/trait that is acquired by any living organism on this planet. Learning is defined by: the acquisition of knowledge or skills through experience, study, or by being taught. Whether that be a plant learning how to respond to light and temperature, a monkey learning how to peel a banana, or us humans learning how to ride a bike. This commonality is what makes us unique and evolve over time.

But what if I said, “Machines can learn too”

We’re in the age where machines are no different. Machine Learning is still fairly a new concept. We can teach machines how to learn and some machines can even learn on its own. This is magical phenomenon is called Machine Learning.

Hopefully this article will provide some useful insights and open up your mind to what computers can do now a days. I won’t go in depth about what machine learning is, but rather a high-level overview.

If there is ONE thing that you should LEARN from reading this article, it is this:

Machines can predict the future, as long as the future doesn’t look too different from the past.

What is Machine Learning

Machine Learning involves a computer to recognize patterns by examples, rather than programming it with specific rules. These patterns are found within Data.

Machine = Your machine or computerLearning = Finding patterns in data

Machine Learning is about:

Creating algorithms (a set of rules) that learns from complex functions (patterns) from data to make predictions on it.

Essentially, it can be summarized in 3 Steps:

  1. It takes some data
  2. Finds pattern from the data
  3. Predicts new pattern from the data

Applications of Machine Learning

Before we get started, here is a quick overview of what machine learning is capable of:

  • Healthcare: Predicting patient diagnostics for doctors to review
  • Social Network: Predicting certain match preferences on a dating website for better compatibility
  • Finance: Predicting fraudulent activity on a credit card
  • E-commerce: Predicting customer churn
  • Biology: Finding patterns in gene mutations that could represent cancer

How Do Machines Learn?

To keep things simple, just know that machines “learn” by finding patterns in similar data. Think of data as information you acquire from the world. The more data given to a machine, the “smarter” it gets.

But not all data are the same. Imagine you’re a pirate and your life mission was to find the buried treasure somewhere in the island. In order to find the treasure, you’re going to need sufficient amount of information. Like data, this information can either lead you to the right direction or the wrong direction. The better the information/data that is obtained, the more uncertainty is reduced, and vice versa. So it’s important to keep in mind the type of data you’re giving to your machine to learn.

“More data beats better models. Better data beats more data.” — Riley Newman

Nonetheless, after a sufficient amount of data is given, then the machine can make predictions. Machines can predict the future, as long as the future doesn’t look too different from the past.

Machine “learns” really by using old data to get information about whats the most likelihood that will happen. If the old data looks a lot like the new data, then the things you can say about the old data will probably be relevant to the new data. It’s like looking back to look forward.

Types of Machine Learning

There are three main categories of machine learning:

  • Supervised learning: The machine learns from labeled data. Normally, the data is labeled by humans.
  • Unsupervised learning: The machine learns from un-labeled data. Meaning, there is no “right” answer given to the machine to learn, but the machine must hopefully find patterns from the data to come up with an answer.
  • Reinforcement learning: The machine learns through a reward-based system.

Supervised Machine Learning

Supervised learning is the most common and studied type of learning because it is easier to train a machine to learn with labeled data than with un-labeled data. Depending on what you want to predict, supervised learning can used to solve two types of problems: regression or classification.

Regression:

If you want to predict continuous values, such as trying to predict the cost of a house or the weather outside in degrees, you would use regression. This type of problem doesn’t have a specific value constraint because the value could be any number with no limits.

Classification:

If you want to predict discrete values, such as classifying something into categories, you would use classification. A problem like, “Will he make this purchase” will have an answer that falls into two specific categories: yes or no. This is also called a, binary classification problem.

Unsupervised Machine Learning

Since there is no labeled data for machines to learn from, the goal for unsupervised machine learning is to detect patterns in the data and to group them. Unsupervised learning are machines trying to learn “on their own”, without help. Imagine someone throwing you piles of data and says “Here you go boy, find some patterns and group them out for me. Thanks and have fun.”

Depending on what you want to group together, unsupervised learning can group data together by: clustering or association.

Clustering Problem:

Unsupervised learning tries to solve this problem by looking for similarities in the data. If there is a common cluster or group, the algorithm would then categorize them in a certain form. An example of this could be trying to group customers based on past buying behavior.

Association Problem:

Unsupervised learning tries to solve this problem by trying to understand the rules and meaning behind different groups. Finding a relationship between customer purchases is a common example of an association problem. Stores may want to know what type of products were purchased together and could possibly use this information to organize the placement of these products for easier access. One store found out that there was a strong association between customers buying beer and diapers. They deduced from this statement that males who had went out to buy diapers for their babies also tend to buy beer as well.

Reinforcement Machine Learning

This type of machine learning requires the use of a reward/penalty system. The goal is to reward the machine when it learns correctly and to penalize the machine when it learns incorrectly.

Reinforcement Machine Learning is a subset of Artificial Intelligence. With the wide range of possible answers from the data, the process of this type of learning is an iterative step. It continuously learns.

Examples of Reinforcement Learning:

  • Training a machine to learn how to play (Chess, Go)
  • Training a machine how to learn and play Super Mario by itself
  • Self-driving cars

 

Thanks to: Randy Lao
Reference: https://www.linkedin.com/pulse/beginners-guide-machine-learning-randy-lao-/

Jquery Smooth-Scroll

jquery.smooth-scroll.js

/*!
 * jQuery Smooth Scroll - v2.2.0 - 2017-05-05
 * https://github.com/kswedberg/jquery-smooth-scroll
 * Copyright (c) 2017 Karl Swedberg
 * Licensed MIT
 */

(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function($) {

    var version = '2.2.0';
    var optionOverrides = {};
    var defaults = {
        exclude: [],
        excludeWithin: [],
        offset: 0,

        // one of 'top' or 'left'
        direction: 'top',

        // if set, bind click events through delegation
        //  supported since jQuery 1.4.2
        delegateSelector: null,

        // jQuery set of elements you wish to scroll (for $.smoothScroll).
        //  if null (default), $('html, body').firstScrollable() is used.
        scrollElement: null,

        // only use if you want to override default behavior
        scrollTarget: null,

        // automatically focus the target element after scrolling to it
        autoFocus: false,

        // fn(opts) function to be called before scrolling occurs.
        // `this` is the element(s) being scrolled
        beforeScroll: function() {},

        // fn(opts) function to be called after scrolling occurs.
        // `this` is the triggering element
        afterScroll: function() {},

        // easing name. jQuery comes with "swing" and "linear." For others, you'll need an easing plugin
        // from jQuery UI or elsewhere
        easing: 'swing',

        // speed can be a number or 'auto'
        // if 'auto', the speed will be calculated based on the formula:
        // (current scroll position - target scroll position) / autoCoeffic
        speed: 400,

        // coefficient for "auto" speed
        autoCoefficient: 2,

        // $.fn.smoothScroll only: whether to prevent the default click action
        preventDefault: true
    };

    var getScrollable = function(opts) {
        var scrollable = [];
        var scrolled = false;
        var dir = opts.dir && opts.dir === 'left' ? 'scrollLeft' : 'scrollTop';

        this.each(function() {
            var el = $(this);

            if (this === document || this === window) {
                return;
            }

            if (document.scrollingElement && (this === document.documentElement || this === document.body)) {
                scrollable.push(document.scrollingElement);

                return false;
            }

            if (el[dir]() > 0) {
                scrollable.push(this);
            } else {
                // if scroll(Top|Left) === 0, nudge the element 1px and see if it moves
                el[dir](1);
                scrolled = el[dir]() > 0;

                if (scrolled) {
                    scrollable.push(this);
                }
                // then put it back, of course
                el[dir](0);
            }
        });

        if (!scrollable.length) {
            this.each(function() {
                // If no scrollable elements and has scroll-behavior:smooth because
                // "When this property is specified on the root element, it applies to the viewport instead."
                // and "The scroll-behavior property of the … body element is *not* propagated to the viewport."
                // → https://drafts.csswg.org/cssom-view/#propdef-scroll-behavior
                if (this === document.documentElement && $(this).css('scrollBehavior') === 'smooth') {
                    scrollable = [this];
                }

                // If still no scrollable elements, fall back to,
                // if it's in the jQuery collection
                // (doing this because Safari sets scrollTop async,
                // so can't set it to 1 and immediately get the value.)
                if (!scrollable.length && this.nodeName === 'BODY') {
                    scrollable = [this];
                }
            });
        }

        // Use the first scrollable element if we're calling firstScrollable()
        if (opts.el === 'first' && scrollable.length > 1) {
            scrollable = [scrollable[0]];
        }

        return scrollable;
    };

    var rRelative = /^([\-\+]=)(\d+)/;

    $.fn.extend({
        scrollable: function(dir) {
            var scrl = getScrollable.call(this, {dir: dir});

            return this.pushStack(scrl);
        },
        firstScrollable: function(dir) {
            var scrl = getScrollable.call(this, {el: 'first', dir: dir});

            return this.pushStack(scrl);
        },

        smoothScroll: function(options, extra) {
            options = options || {};

            if (options === 'options') {
                if (!extra) {
                    return this.first().data('ssOpts');
                }

                return this.each(function() {
                    var $this = $(this);
                    var opts = $.extend($this.data('ssOpts') || {}, extra);

                    $(this).data('ssOpts', opts);
                });
            }

            var opts = $.extend({}, $.fn.smoothScroll.defaults, options);

            var clickHandler = function(event) {
                var escapeSelector = function(str) {
                    return str.replace(/(:|\.|\/)/g, '\\$1');
                };

                var link = this;
                var $link = $(this);
                var thisOpts = $.extend({}, opts, $link.data('ssOpts') || {});
                var exclude = opts.exclude;
                var excludeWithin = thisOpts.excludeWithin;
                var elCounter = 0;
                var ewlCounter = 0;
                var include = true;
                var clickOpts = {};
                var locationPath = $.smoothScroll.filterPath(location.pathname);
                var linkPath = $.smoothScroll.filterPath(link.pathname);
                var hostMatch = location.hostname === link.hostname || !link.hostname;
                var pathMatch = thisOpts.scrollTarget || (linkPath === locationPath);
                var thisHash = escapeSelector(link.hash);

                if (thisHash && !$(thisHash).length) {
                    include = false;
                }

                if (!thisOpts.scrollTarget && (!hostMatch || !pathMatch || !thisHash)) {
                    include = false;
                } else {
                    while (include && elCounter < exclude.length) {
                        if ($link.is(escapeSelector(exclude[elCounter++]))) {
                            include = false;
                        }
                    }

                    while (include && ewlCounter < excludeWithin.length) {
                        if ($link.closest(excludeWithin[ewlCounter++]).length) {
                            include = false;
                        }
                    }
                }

                if (include) {
                    if (thisOpts.preventDefault) {
                        event.preventDefault();
                    }

                    $.extend(clickOpts, thisOpts, {
                        scrollTarget: thisOpts.scrollTarget || thisHash,
                        link: link
                    });

                    $.smoothScroll(clickOpts);
                }
            };

            if (options.delegateSelector !== null) {
                this
                    .off('click.smoothscroll', options.delegateSelector)
                    .on('click.smoothscroll', options.delegateSelector, clickHandler);
            } else {
                this
                    .off('click.smoothscroll')
                    .on('click.smoothscroll', clickHandler);
            }

            return this;
        }
    });

    var getExplicitOffset = function(val) {
        var explicit = {relative: ''};
        var parts = typeof val === 'string' && rRelative.exec(val);

        if (typeof val === 'number') {
            explicit.px = val;
        } else if (parts) {
            explicit.relative = parts[1];
            explicit.px = parseFloat(parts[2]) || 0;
        }

        return explicit;
    };

    var onAfterScroll = function(opts) {
        var $tgt = $(opts.scrollTarget);

        if (opts.autoFocus && $tgt.length) {
            $tgt[0].focus();

            if (!$tgt.is(document.activeElement)) {
                $tgt.prop({tabIndex: -1});
                $tgt[0].focus();
            }
        }

        opts.afterScroll.call(opts.link, opts);
    };

    $.smoothScroll = function(options, px) {
        if (options === 'options' && typeof px === 'object') {
            return $.extend(optionOverrides, px);
        }
        var opts, $scroller, speed, delta;
        var explicitOffset = getExplicitOffset(options);
        var scrollTargetOffset = {};
        var scrollerOffset = 0;
        var offPos = 'offset';
        var scrollDir = 'scrollTop';
        var aniProps = {};
        var aniOpts = {};

        if (explicitOffset.px) {
            opts = $.extend({link: null}, $.fn.smoothScroll.defaults, optionOverrides);
        } else {
            opts = $.extend({link: null}, $.fn.smoothScroll.defaults, options || {}, optionOverrides);

            if (opts.scrollElement) {
                offPos = 'position';

                if (opts.scrollElement.css('position') === 'static') {
                    opts.scrollElement.css('position', 'relative');
                }
            }

            if (px) {
                explicitOffset = getExplicitOffset(px);
            }
        }

        scrollDir = opts.direction === 'left' ? 'scrollLeft' : scrollDir;

        if (opts.scrollElement) {
            $scroller = opts.scrollElement;

            if (!explicitOffset.px && !(/^(?:HTML|BODY)$/).test($scroller[0].nodeName)) {
                scrollerOffset = $scroller[scrollDir]();
            }
        } else {
            $scroller = $('html, body').firstScrollable(opts.direction);
        }

        // beforeScroll callback function must fire before calculating offset
        opts.beforeScroll.call($scroller, opts);

        scrollTargetOffset = explicitOffset.px ? explicitOffset : {
            relative: '',
            px: ($(opts.scrollTarget)[offPos]() && $(opts.scrollTarget)[offPos]()[opts.direction]) || 0
        };

        aniProps[scrollDir] = scrollTargetOffset.relative + (scrollTargetOffset.px + scrollerOffset + opts.offset);

        speed = opts.speed;

        // automatically calculate the speed of the scroll based on distance / coefficient
        if (speed === 'auto') {

            // $scroller[scrollDir]() is position before scroll, aniProps[scrollDir] is position after
            // When delta is greater, speed will be greater.
            delta = Math.abs(aniProps[scrollDir] - $scroller[scrollDir]());

            // Divide the delta by the coefficient
            speed = delta / opts.autoCoefficient;
        }

        aniOpts = {
            duration: speed,
            easing: opts.easing,
            complete: function() {
                onAfterScroll(opts);
            }
        };

        if (opts.step) {
            aniOpts.step = opts.step;
        }

        if ($scroller.length) {
            $scroller.stop().animate(aniProps, aniOpts);
        } else {
            onAfterScroll(opts);
        }
    };

    $.smoothScroll.version = version;
    $.smoothScroll.filterPath = function(string) {
        string = string || '';

        return string
            .replace(/^\//, '')
            .replace(/(?:index|default).[a-zA-Z]{3,4}$/, '')
            .replace(/\/$/, '');
    };

    // default options
    $.fn.smoothScroll.defaults = defaults;

}));

 

Add Js Code:

$(document).ready(function() {
    $('#navbarSupportedContent a').offsetScroller({offsetPixels: 182});
    $('.navbar-nav a').offsetScroller({animationSpeed: 500});
    // to enable for all anchor links...
    //$('a[href*=#]:not([href=#])').offsetScroller({offsetPixels:92});
    $().offsetScroller.scrollToHash(window.location.hash, {offsetPixels: 92});
});

Capistrano Rails

Capistrano

Capistrano is something completely different. In all the previous sections, “deployment” refers to the act of starting your Ruby app in an application server, so that it becomes accessible to visitors, but before that can happen one typically needs to do some preparation work, such as:

  • Uploading the Ruby app’s code and files to the server machine.
  • Installing libraries that your app depends on.
  • Setting up or migrating the database.
  • Starting and stopping any daemons that your app might rely on, such as Sidekiq/Resque workers or whatever.
  • Any other things that need to be done when you’re setting up your application.

In the context of Capistrano, “deployment” refers to doing all this preparation work. Capistrano is not an application server. Instead, it is a tool for automating all that preparation work. You tell Capistrano where your server is and which commands need to be run every time you deploy a new version of your app, and Capistrano will take care of uploading the Rails app to the server for you and running the commands you specified.

Capistrano is always used in combination with an application server. It does not replace application servers. Vice-versa, application servers do not replace Capistrano, they can be used in combination with Capistrano.

Of course you don’t have to use Capistrano. If you prefer to upload your Ruby app with FTP and manually running the same steps of commands every time, then you can do that. Other people got tired of it, so they automate those steps in Capistrano.

Ruby on Rails Web Server Options

Apache vs Nginx

They’re both web servers. They can serve static files but – with the right modules – can also serve dynamic web apps e.g. those written in PHP. Apache is more popular and has more features, Nginx is smaller and faster and has less features.

Neither Apache nor Nginx can serve Ruby web apps out-of-the-box, to do that you need to use Apache/Nginx in combination with some kind of add-on, described later.

Apache and Nginx can also act as reverse proxies, meaning that they can take an incoming HTTP request and forward it to another server, which also speaks HTTP. When that server responds with an HTTP response, Apache/Nginx will forward the response back to the client; You will learn later why this is relevant.

Mongrel and other production app servers vs WEBrick

Mongrel is a Ruby “application server”: In concrete terms this means that Mongrel is an application which:

  1. Loads your Ruby app inside its own process space.
  2. Sets up a TCP socket, allowing it to communicate with the outside world (e.g. the Internet). Mongrel listens for HTTP requests on this socket and passes the request data to the Ruby web app.
  3. The Ruby web app then returns an object, which describes what the HTTP response should look like, and Mongrel takes care of converting it to an actual HTTP response (the actual bytes) and sends it back over the socket.

However Mongrel is quite dated, nowadays it is no longer maintained. Newer alternative application servers are:

  • Phusion Passenger
  • Unicorn
  • Thin
  • Puma
  • Trinidad (JRuby only)
  • TorqueBox (JRuby only)

I’ll cover them later and describe how they differ from each other and from Mongrel.

WEBrick does the same thing as Mongrel, but the differences are:

  • WEBrick is not fit for production, unlike everything else that I mentioned before. WEBrick is written entirely in Ruby. Mongrel (and most other Ruby app servers) is part Ruby and part C (Mostly Ruby), but its HTTP parser is written in C for performance.
  • WEBrick is slower and less robust. It has some known memory leaks and some known HTTP parsing problems.
  • WEBrick is usually only used as the default server during development because WEBrick is included in Ruby by default. Mongrel and other app servers needs to be installed separately. It’s not recommended to use WEBrick in production environments, though for some reason Heroku chose WEBrick as its default server. They were using Thin before, so I have no idea why they switched to WEBrick.

The app server and the world

All current Ruby app servers speak HTTP, however some app servers may be directly exposed to the Internet on port 80, while others may not.

  • App servers that can be directly exposed to the Internet: Phusion Passenger, Rainbows
  • App servers that may not be directly exposed to the Internet: Mongrel, Unicorn, Thin, Puma. These app servers must be put behind a reverse proxy web server like Apache and Nginx.
  • I don’t know enough about Trinidad and TorqueBox, so I’ve omitted them.

Why must some app servers be put behind a reverse proxy?

  • Some app servers can only handle 1 request concurrently, per process. If you want to handle 2 requests concurrently you need to run multiple app server instances, each serving the same Ruby app. This set of app server processes is called an app server cluster (hence the name Mongrel Cluster, Thin Cluster, etc). You must then setup Apache or Nginx to reverse proxy to this cluster. Apache/Nginx will take care of distributing requests between the instances in the cluster (More on this in section “I/O concurrency models”).
  • The web server can buffer requests and responses, protecting the app server from “slow clients” – HTTP clients that don’t send or accept data very quickly. You don’t want your app server to do nothing while waiting for the client to send the full request or to receive the full response, because during that time the app server may not be able to do anything else. Apache and Nginx are very good at doing many things at the same time because they’re either multithreaded or evented.
  • Most app servers can serve static files, but are not particularly good at it. Apache and Nginx can do it faster.
  • People typically set up Apache/Nginx to serve static files directly, but forward requests that don’t correspond with static files to the app server, it’s good security practice. Apache and Nginx are very mature and can shield the app server from (perhaps maliciously) corrupted requests.

Why can some app servers be directly exposed to the Internet?

  • Phusion Passenger is a very different beast from all the other app servers. One of its unique features is that it integrates into the web server.
  • The Rainbows author publicly stated that it’s safe to directly expose it to the Internet. The author is fairly sure that there are no vulnerabilities in the HTTP parser (and similar). Still, the author provides no warranty and says that usage is at own risk.

Application servers compared

In this section I’ll compare most application servers I’ve mentioned, but not Phusion Passenger. Phusion Passenger is such a different beast from the rest that I’ve given it a dedicated section. I’ve also omitted Trinidad and TorqueBox because I do not know them well enough, but they’re only relevant anyway if you use JRuby.

  • Mongrel was pretty bare bones. As mentioned earlier, Mongrel is purely single-threaded multi-process, so it is only useful in a cluster. There is no process monitoring: if a process in the cluster crashes (e.g. because of a bug in the app) then it needs to be manually restarted. People tend to use external process monitoring tools such as Monit and God.
  • Unicorn is a fork of Mongrel. It supports limited process monitoring: if a process crashes it is automatically restarted by the master process. It can make all processes listen on a single shared socket, instead of a separate socket for each process. This simplifies reverse proxy configuration. Like Mongrel, it is purely single-threaded multi-process.
  • Thin uses the evented I/O model by utilizing the EventMachine library. Other than using the Mongrel HTTP parser, it is not based on Mongrel in any way. Its cluster mode has no process monitoring so you need to monitor crashes etc. There is no Unicorn-like shared socket, so each process listens on its own socket. In theory, Thin’s I/O model allows high concurrency, but in most practical situations that Thin is used for, one Thin process can only handle 1 concurrent request, so you still need a cluster. More about this peculiar property in section “I/O concurrency models”.
  • Puma was also forked from Mongrel, but unlike Unicorn, Puma is designed to be purely multi-threaded. There is therefore currently no builtin cluster support. You need to take special care to ensure that you can utilize multiple cores (More about this in section “I/O concurrency models”).
  • Rainbows supports multiple concurrency models through the use of different libraries.

Phusion Passenger

Phusion Passenger works very differently from all the other ones. Phusion Passenger integrates directly into Apache or Nginx, and so can be compared to mod_php for Apache. Just like mod_php allows Apache to serve PHP apps, almost magically, Phusion Passenger allows Apache (and also Nginx!) to serve Ruby apps, almost magically. Phusion Passenger’s goal is to make everything Just Work(tm) with as little hassle as possible.

Instead of starting a process or cluster for your app, and configuring Apache/Nginx to serve static files and/or reverse proxying requests to the process/cluster with Phusion Passenger you only need to:

  1. You edit the web server config file and specify the location of your Ruby app’s ‘public’ directory.
  2. There is no step 2.

All configuration is done within the web server config file. Phusion Passenger automates pretty much everything. There is no need to start a cluster and manage processes. Starting/stopping processes, restarting them when they crash, etc. – all automated. Compared to other app servers, Phusion Passenger has far fewer moving parts. This ease of use is one of the primary reasons why people use Phusion Passenger.

Also unlike other app servers, Phusion Passenger is primarily written in C++, making it very fast.

There’s also an Enterprise variant of Phusion Passenger with even more features, such as automated rolling restarts, multithreading support, deployment error resistance, etc.

For the above reasons, Phusion Passenger is currently the most popular Ruby app server, powering over 150,000 websites, including large ones such as New York Times, Pixar, Airbnb, etc.

Phusion Passenger vs other app servers

Phusion Passenger provides a lot more features and provides many advantages over other app servers, such as:

  • Dynamically adjusting the number of processes based on traffic. We run a ton of Rails apps on our resource-constrainted server that are not public-facing, and that people in our organization only use at most a few times a day. Things like Gitlab, Redmine, etc. Phusion Passenger can spin down those processes when they’re not used, and spinning them up when they’re used, allowing more resources to be available for more important apps. With other app servers, all your processes are turned on all the time.
  • Some app servers are not good at certain workloads, by design. For example Unicorn is designed for fast-running requests only: See the Unicorn website section “Just Worse in Some Cases”.

Workloads that Unicorn is not good at are:

  • Streaming workloads (e.g. Rails 4 live streaming or Rails 4 template streaming).
  • Workloads in which the app performs HTTP API calls.

The hybrid I/O model in Phusion Passenger Enterprise 4 or later makes it an excellent choice for these kinds of workloads.

  • Other app servers require the user to run at least one instance per application. By contrast, Phusion Passenger supports multiple applications in a single instance. This greatly reduces administration overhead.
  • Automatic user switching, a convenient security feature.
  • Phusion Passenger supports many MRI Ruby, JRuby and Rubinius. Mongrel, Unicorn and Thin only support MRI. Puma also supports all 3.
  • Phusion Passenger actually supports more than just Ruby! It also supports Python WSGI, so it can for example also run Django and Flask apps. In fact Phusion Passenger is moving into the direction of becoming a polyglot server. Node.js support on the todo list.
  • Out-of-band garbage collection. Phusion Passenger can run the Ruby garbage collector outside the normal request/response cycle, potentially reducing request times by hundreds of milliseconds. Unicorn also has a similar feature, but Phusion Passenger’s version is more flexible because 1) it’s not limited to GC and can be used for arbitrary work. 2) Phusion Passenger’s version works well with multithreaded apps, while Unicorn’s does not.
  • Automated rolling restarts. Rolling restarts on Unicorn and other servers require some scripting work. Phusion Passenger Enterprise completely automates this way for you.

There are more features and advantages, but the list is really long. You should refer to the comprehensive Phusion Passenger manual (Apache versionNginx version) or the Phusion Passenger website for information.

I/O concurrency models

  • Single-threaded multi-process. This is traditionally the most popular I/O model for Ruby app servers, partially because multithreading support in the Ruby ecosystem was very bad. Each process can handle exactly 1 request at a time. The web server load balances between processes. This model is very robust and there is little chance for the programmer to introduce concurrency bugs. However, its I/O concurrency is extremely limited (limited by the number of processes). This model is very suitable for fast, short-running workloads. It is very unsuitable for slow, long-running blocking I/O workloads, e.g. workloads involving the calling of HTTP APIs.
  • Purely multi-threaded. Nowadays the Ruby ecosystem has excellent multithreading support, so this I/O model has become very viable. Multithreading allows high I/O concurrency, making it suitable for both short-running and long-running blocking I/O workloads. The programmer is more likely to introduce concurrency bugs, but luckily most web frameworks are designed in such a way that this is still very unlikely. One thing to note however is that the MRI Ruby interpreter cannot leverage multiple CPU cores even when there are multiple threads, due to the use of the Global Interpreter Lock (GIL). You can work around this by using multiple multi-threaded processes, because each process can leverage a CPU core. JRuby and Rubinius have no GIL, so they can fully leverage multiple cores in a single process.
  • Hybrid multi-threaded multi-process. Primarily implemented by Phusion Passenger Enterprise 4 and later. You can easily switch between single-threaded multi-process, purely multithreaded, or perhaps even multiple processes each with multiple threads. This model gives the best of both worlds.
  • Evented. This model is completely different from the previously mentioned model. It allows very high I/O concurrency and is therefore excellent for long-running blocking I/O workloads. To utilize it, explicit support from the application and the framework is required. However all the major frameworks like Rails and Sinatra do not support evented code. This is why in practice a Thin process still cannot handle more than 1 request at a time, making it effectively behave the same as the single-threaded multi-process model. There are specialized frameworks that can take advantage of evented I/O, such as Cramp.

An article was recently posted on the Phusion blog about optimally tuning the number of processes and threads given your workload. See Tuning Phusion Passenger’s concurrency settings.