Operations On Single Nodes

At times, you may have a piece of code (e.g., a user listener) that is executed on all nodes. On one of the nodes, however, you may need to execute some additional code in order to update a external database.

How do you decide where to execute the additional piece of code?

Here's an example of how this can be done for a user event..

There are three types of user events:

  • insert
  • update
  • remove

You can extract the user ID for each of these types and use the user ID in the following function:

Copy
Cluster:IsLocalKey($userId)

This call returns true on a single node only. On all other nodes it returns false. If the call returns true, you execute the additional code.

The functionality behind Cluster:IsLocalKey() is provided by Hazelcast. Hazelcast uses a hash algorithm to decide, for every key, which node owns that key.

Note: Be aware that ownership of a key may change when the topology of the cluster changes.

Here is a complete example which simply counts the number of local user IDs:

Copy
Indexed String $userIds := USERIDS();
Integer $count := 0;
Integer $countLocal := 0;
ForEach String $userId In $userIds Do
    $count := $count + 1;
    If Cluster:IsLocalKey($userId) Then
        $countLocal := $countLocal + 1;
    End
End
PRINTLN('Count = ' & $count);
PRINTLN('Count local = ' & $countLocal);

In general, the pattern described above can also be used in all situations where you have a clear identifier. This includes all kinds of listeners, as well as distributed tasks. You could use the name of the task to decide which node should do some extra work.