Warning: Under Construction. I am using this site as my playground as I build gatsby-mdx and gatsby themes. During this time I will also repost new content to Medium

Consistant Hash Routing in Riak Core


To build the project
## Relevant Files
Project on Github
[chapp.erl](https://github.com/ChristopherBiscardi/Riak-Core-Consistent-Hash-Routing-Example/blob/master/a pps/chapp/src/chapp.erl)
Holds the different routing code
[chapp_vnode.erl](https://github.com/ChristopherBiscardi/Riak-Core-Consistent-Hash-Routing-Example/blob/master/apps/chapp/src /chapp_vnode.erl)
The ping function on the vnodes. This function is the same on every vnode, the difference is which vnode is processing the request.

The Code

%% @doc Pings a random vnode
ping() ->
DocIdx = riak_core_util:chash_key({>, term_to_binary(now())}),
PrefList = riak_core_apl:get_primary_apl(DocIdx, 1, chapp),
[{IndexNode, _Type}] = PrefList,
riak_core_vnode_master:sync_spawn_command(IndexNode, ping, chapp_vnode_master).

The first function, shown above, pings a random (random enough for our purposes) vnode and returns the partition identifier. The code we’re interested in is in the first line of the function – specifically the chash_key() function.

The chash_key function takes a two-tuple and returns a binary identifier we can use to get a PrefList. Much of the terminology in the Riak Core source refers to Riak KV. In this case, the variables are named Bucket and Key in the chash_key function.

Each function in [chapp.erl](https://github.com/ChristopherBiscardi/Riak-Core-Consistent-Hash-Routing-Example/blob/master/a pps/chapp/src/chapp.erl) has different tuples which affect which vnode gets called.

% ping()
{>, term_to_binary(now())}
% pingsame()
{>, >}
% pinginput(X)
{>, term_to_binary(X)}

so if we build the project.

cd path/to/project
make rel

and run the console

./rel/chapp/bin/chapp console

we can then execute the various ping() functions as such:


which gives us a tuple that contains pong and the partition id that processed the request.

We can see the results from running the ping() function a couple times below. Notice that each time we run ping(), a different partition handles the call.


Looking at the next function pingsame which we call as such:


we can see that by calling this function multiple times, we get the same partition handling the call, because the hash of the tuple is always the same.


The pinginput function allows us to take a more interactive look at where our requests go. pinginput uses the input we give it as the second element in the chash_key function tuple.


we can see that by calling this function multiple times with the same input, the same vnode processes the request.


We can also see that by calling pinginput with a different input results in a different vnode handling the request.