8.1. What are notifications?

Notifications are nothing new. It's a very popular software design pattern, although you might know it with a different name such as Observer/Observable. Let's suppose that our software had several distinct parts (e.g. a GUI and the application logic, a client and a server, etc.) and that one of the parts of the software needs to be aware of the changes that happen in one of the other parts. For example, the GUI might need to know when a value is changed in a database, so that the new value is immediately displayed to the user. Taking this to the client/server world is easy: suppose a client needs to know when the server reaches a certain state, so the client can perform a certain action.

The most crude approach to keep the client informed is a polling approach. The client periodically polls the server (asks if there are any changes). For example, let's suppose a client applications wants to know when the load of a server drops below 50%. The server is called the producer of events (in this case, the event is a drop in the server load). The client, on the other hand, is called the consumer of events. The polling approach would go like this:

Figure 8.1. Keeping track of changes using polling

Keeping track of changes using polling
  1. The consumer asks the producer if there are any changes. The producer replies "No", so the consumer waits a while before making another call.

  2. Once again, the consumer asks the producer if there are any changes. The producer replies "No", so the consumer waits a while before making another call.

  3. As you can see, this step can be repeated ad nauseam until the server finally replies that there has been a change.

This approach isn't very efficient, specially if you consider the following:

The answer to this problem is actually terribly simple (and common sense). Instead of periodically asking the producer if there are any changes, we make an initial call asking the producer to notify the consumer whenever a certain event occurs. This is the notification approach.

Figure 8.2. Keeping track of changes using notifications

Keeping track of changes using notifications
  1. The consumer asks the producer to notify him as soon as the server load drops below 50%. The producer keeps a list of all its registered consumers. This step is normally called the subscription or registration step.

  2. The consumer and the producer go about their business until the server load drops below 50%.

  3. Once the server load drops below 50%, the producer notifies all its consumers (remember, there can be more than one) of that event.

As you can see, this approach is much more efficient (in this simple example, network traffic has been sliced in half with respect to the polling approach).