Ever play the telephone game when you were a kid? You’d give a message to someone standing next to you, and see what the words morphed into as it made its way back to you. Sometimes you’d say curse words just to see what your friends would say next. Message buses are a lot like that. Except they’re much better at remembering what you said than a room full of primary schoolers.

Message Bus Example

A very serious example of the message bus pattern.

A message bus is a way for discrete parts of a program to communicate with each other without knowing that any other components exist. Think of it like playing the telephone game with ghosts that respond sometimes. If one part needs a piece of data, for example, it sends out a request on the message bus. Other parts of the program listen for these messages and supply the requested data. Because all of the communication is handled via a third-party, each part of our program is free of references to another.

VW Bus

Good for carrying messages to the Grateful Dead.

What are the benefits of a message bus? The short answer is modular code. Since none of our methods/functions/classes contain direct calls to other parts of our code, we can easily swap out processors, responders, and requesters. If the specifications for our program change, we just modify the code affected by the change.

It should be noted that a message bus is different than a helper function. In PHP, for example, you might create helper methods or classes that pass and receive data, but in the end, the thing that calls the helper method is specifically aware of what it’s communicating with. If my code calls a get_all_fields() helper method, it has to know the name of the method. Changing the helper method name to something like get_all_fields_now() means that we have to change every reference to that helper method in our code. Using a message bus alleviates this, because the piece of code requesting the information from the helper doesn’t interact with it directly. It just sends out a message saying, “I need this piece of data.” In the very serious example above, the user view doesn’t call a database function for retrieving information, it sends a message out into the message bus. The database controller is listening for the request and responds anonymously.

Jerome “The Bus” Bettis

Jerome “The Bus” Bettis. Good for carrying American football (hand-egg) messages.

This concept may seem a bit foreign if you’ve only done web or server-side development. Message buses aren’t very feasible in state-less environments; if a listener doesn’t exist when its value is requested, it can’t respond. If you do any work in Javascript, though, this pattern can be very, very useful. In that vein, next we’ll dig into specifics by using the Backbone Radio plugin to create a message bus pattern in Javascript.