Symphonious

Living in a state of accord.

Simple Long Poll Patterns in JavaScript

A couple of little patterns for writing long-poll based JavaScript applications have evolved in some internal apps I’ve been working on lately so I thought I’d document them for posterity.

Simple Long Poll Loop

(function($) {
    var longPollUrl = '/longpoll';

    var lastReceivedSequence;

    function poll() {
        $.ajax(longPollUrl, {
            data: { 'lastSequence': lastReceivedSequence },
            dataType: 'json',
            timeout: 15000,
            success: function(data) {
                if (!data) return;
                lastReceivedSequence = data.sequenceNumber;
                $(window).trigger('onLongPollEvent', data);
            },
            complete: poll
        });
    }
})(jQuery);
view raw basic.js This Gist brought to you by GitHub.

There’s very little special about this – it basically just uses jQuery to do a standard long poll. The pattern that I like is that instead of calling a particular function directly to handle events it just uses the jQuery trigger function to fire an event that can be handled by any interested code, without introducing tight coupling between the two bits of code. Listeners would receive events with:

$(window).bind('onLongPollEvent', function(eve, longPollData) { ... });
view raw listener.js This Gist brought to you by GitHub.

Automatically Reload JavaScript Changes

One of the internal tools I’ve been working on is our “big feedback” page for reporting build results. This page is displayed on a large monitor the whole team can see, so refreshing the page to load JavaScript changes requires actually getting up and walking over to it. Fortunately, there’s a simple pattern to get the JavaScript to reload itself:

var serverVersion;
...
if (data.serverVersion != serverVersion) {
    window.location.reload();
    return;
}
...
view raw reload.js This Gist brought to you by GitHub.

Each long poll event sent down to the browser includes the server version – when it changes, the JavaScript reloads the page. There are two nice little details here:

  1. Deploying a new version actually requires some downtime while the server restarts. Naive implementations will reload the page when the long poll request returns an error but that usually results in the page attempting to reload and also getting an error or no response from the server and now there’s no JavaScript running to recover. Instead, this will wait for the server to come back up and be answering requests again before reloading.
  2. So I don’t have to remember to update the server version, the server actually sends the UNIX time stamp from when it started up. Anytime the server restarts, that value changes and the JavaScript will reload. This can lead to some false positives but it’s extremely simple and effective. Another option would be for the build scripts to insert the SVN revision but that doesn’t work as well for development.

Usually I insert this reload code directly into the long poll loop so that it is guaranteed to run first and avoid any potential problems with data formats changing. Even the serverVersion data format can change since it doesn’t try to parse it in any way – any change, including data.serverVersion no longer being present, will cause the page to reload.

Put together the code comes out something like:

(function($) {
    var longPollUrl = '/longpoll';

    var lastReceivedSequence;
    var serverVersion;

    function poll() {
        $.ajax(longPollUrl, {
            data: { 'lastSequence': lastReceivedSequence },
            dataType: 'json',
            timeout: 15000,
            success: function(data) {
                if (!data) return;
                lastReceivedSequence = data.sequenceNumber;
                if (data.serverVersion != serverVersion) {
                    window.location.reload();
                    return;
                }
                $(window).trigger('onLongPollEvent', data);
            },
            complete: poll
        });
    }
})(jQuery);
view raw full.js This Gist brought to you by GitHub.

Nothing earth-shatteringly new, but handy little tools to have up your sleeve.

Background Logging with the Disruptor

Peter Lawrey posted an example of using the Exchanger class from core Java to implement a background logging implementation. He briefly compared it to the LMAX disruptor and since someone requested it, I thought it might be interesting to show a similar implementation using the disruptor.

Firstly, let’s revisit the very high level differences between the exchanger and the disruptor. Peter notes:

This approach has similar principles to the Disruptor. No GC using recycled, pre-allocated buffers and lock free operations (The Exchanger not completely lock free and doesn't busy wait, but it could)

Two keys difference are:

  • there is only one producer/consumer in this case, the disruptor supports multiple consumers.
  • this approach re-uses a much smaller buffer efficiently. If you are using ByteBuffer (as I have in the past) an optimal size might be 32 KB. The disruptor library was designed to exploit large amounts of memory on the assumption it is relative cheap and can use medium sized (MBs) to very large buffers (GBs). e.g. it was design for servers with 144 GB. I am sure it works well on much smaller servers. ;)

Actually, there’s nothing about the Disruptor that requires large amounts of memory. If you know that your producers and consumers are going to keep pace with each other well and you don’t have a requirement to replay old events, you can use quite a small ring buffer with the Disruptor. There are a lot of advantages to having a large ring buffer, but it’s by no means a requirement.

It’s also worth noting that the Disruptor does not require consumers to busy-spin, you can choose to use a blocking wait strategy, or strategies that combine busy-spin and blocking to handle both spikes and lulls in event rates efficiently.

There is also an important advantage to the Disruptor that wasn’t mentioned: it will process events immediately if the consumer is keeping up. If the consumer falls behind however, it can process events in a batch to catch up. This significantly reduces latency while still handling spikes in load efficiently.

The Code

First let’s start with the LogEntry class. This is a simple value object that is used as our entries on the ring buffer and passed from the producer thread over to the consumer thread.

Peter’s Exchanger based implementation – the use of StringBuilder in the LogEntry class is actually a race condition and not thread safe. Both the publishing side and the consumer side are attempting to modify it and depending on how long it takes the publishing side to write the log message to the StringBuilder, it will potentially be processed and then reset by the consumer side before the publisher is complete. In this implementation I’m instead using a simple String to avoid that problem.

import com.lmax.disruptor.EventFactory;

class LogEntry
{
    public static final EventFactory<LogEntry> FACTORY = new EventFactory<LogEntry>()
    {
        public LogEntry newInstance()
        {
            return new LogEntry();
        }
    };

    long time;
    int level;
    String text;
}

The one Disruptor-specific addition is that we create an EventFactory instance which the Disruptor uses to pre-populate the ring buffer entries.

Next, let’s look at the BackgroundLogger class that sets up the process and acts as the producer.

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BackgroundLogger
{
    private static final int ENTRIES = 64;

    private final ExecutorService executorService;
    private final Disruptor<LogEntry> disruptor;
    private final RingBuffer<LogEntry> ringBuffer;

    BackgroundLogger()
    {
        executorService = Executors.newCachedThreadPool();
        disruptor = new Disruptor<LogEntry>(LogEntry.FACTORY, ENTRIES, executorService);
        disruptor.handleEventsWith(new LogEntryHandler());
        disruptor.start();
        ringBuffer = disruptor.getRingBuffer();
    }

    public void log(String text)
    {
        final long sequence = ringBuffer.next();
        final LogEntry logEntry = ringBuffer.get(sequence);

        logEntry.time = System.currentTimeMillis();
        logEntry.level = level;
        logEntry.text = text;

        ringBuffer.publish(sequence);
    }

    public void stop()
    {
        disruptor.shutdown();
        executorService.shutdownNow();
    }
}



In the constructor we create an ExecutorService which the Disruptor will use to execute the consumer threads (a single thread in this case), then the disruptor itself. We pass in the LogEntry.FACTORY instance for it to use to create the entries and a size for the ring buffer.

The log method is our producer method. Note the use of two-phase commit. First claim a slot with the ringBuffer.next() method, then copy our values into that slot’s entry and finally publish the slot, ready for the consumer to process. We could have also used the Disruptor.publish method which can make this simpler for many use cases by rolling the two phase commit into call.

The producer doesn’t need to do any batching as the Disruptor will do that automatically if the consumer is falling behind, though there are also APIs that allow batching the producer which can improve the performance if it fits into your design (here it’s probably better to publish each log entry as it comes in).

The stop method uses the new shutdown method on the Disruptor which takes care of waiting until all consumers have processed all available entries for you, though the code for doing it yourself is quite straight-forward. Finally we shut down the executor.

Note that we don’t need a flush method since the Disruptor is always consuming log events as quickly as the consumer can.

Last of all, the consumer which is almost entirely implementation logic:


import com.lmax.disruptor.EventHandler;

public class LogEntryHandler implements EventHandler<LogEntry>
{

    public LogEntryHandler()
    {
    }

    public void onEvent(final LogEntry logEntry, final long sequence, final boolean endOfBatch) throws Exception
    {
        // Write
    }

}

The consumer’s onEvent method is called for each LogEntry put into the Disruptor. The endOfBatch flag can be used as a signal to flush written content to disk, allowing very large buffer sizes to be used causing writes to disk to be batched when the consumer is running behind, yet also ensure that our valuable log messages get to disk as quickly as possible.

The full code is available as a Gist.

The Disruptor Wizard is Dead, Long Live the Disruptor Wizard!

As of this morning, the Disruptor Wizard has been merged into the core LMAX Disruptor source tree. The .NET port had included the wizard style syntax for quite some time and it seemed to be generally popular, so why make people grab two jars instead of one?

I also updated it to reflect the change in terminology within the Disruptor. Instead of Consumers, there are now EventProcessors and EventHandlers. That better reflects the fact that consumers can actually add additional values to the events. Additionally, the ProducerBarrier has been merged into the ring buffer itself and the ring buffer entries are now called events. Again, that better reflects the fact that the programming model around the disruptor is most often event based.

It doesn’t make much difference for the wizard API, except that:

  • The consumeWith method has been changed to handleEventsWith
  • The getProducerBarrier method has been replaced with a start method which returns the ring buffer. This clears up the confusion that the getProducerBarrier function was also used as the trigger to start the event handler threads. Now the method name is explicit about the fact that it will have side-effects.

OS X Lion: iCal Repeatedly Asks for Google Calendar Password

The one problem I’ve found when upgrading to Lion is that suddenly iCal couldn’t sync to my Google Apps Calendar account – instead it repeatedly asked for the password. I’m still not really sure what caused this, but my solution was to simply delete both ~/Library/Preferences/*iCal* and ~/Library/Calendars. You really only want to do that if you exclusively use Google Calendar. If you have local calendars deleting ~/Library/Calendars will delete them.

Once I’d done that, I re-enabled the Calendars option for the account in System Preferences, “Mail, Contacts and Calendars”, entered my password one last time and it worked perfectly.

Martin Fowler on the LMAX Architecture

Martin Fowler has posted an excellent overview of the LMAX architecture which helps put the use-cases and key considerations that led to the LMAX disruptor pattern in context.

Good to see some focus being put on the programming model that LMAX uses as well. While convention suggests that to get the best performance you have to make heavy use of concurrency and multithreading, the measurements LMAX did showed that the cost of contention and communication between threads was too great. As such, the programming model at LMAX is largely single-threaded, achieving the best possible performance while avoiding the complexities of multithreaded programming.