Remote procedure call (RPC)

(using the Bunny client)

Prerequisites

This tutorial assumes RabbitMQ is installed and running on localhost on standard port (5672). In case you use a different host, port or credentials, connections settings would require adjusting.

Where to get help

If you're having trouble going through this tutorial you can contact us through the mailing list.

In the second tutorial we learned how to use Work Queues to distribute time-consuming tasks among multiple workers.

But what if we need to run a function on a remote computer and wait for the result? Well, that's a different story. This pattern is commonly known as Remote Procedure Call or RPC.

In this tutorial we're going to use RabbitMQ to build an RPC system: a client and a scalable RPC server. As we don't have any time-consuming tasks that are worth distributing, we're going to create a dummy RPC service that returns Fibonacci numbers.

Client interface

To illustrate how an RPC service could be used we're going to create a simple client class. It's going to expose a method named call which sends an RPC request and blocks until the answer is received:

client   = FibonacciClient.new(ch, "rpc_queue")
response = client.call(30)
puts " [.] Got #{response}"

A note on RPC

Although RPC is a pretty common pattern in computing, it's often criticised. The problems arise when a programmer is not aware whether a function call is local or if it's a slow RPC. Confusions like that result in an unpredictable system and adds unnecessary complexity to debugging. Instead of simplifying software, misused RPC can result in unmaintainable spaghetti code.

Bearing that in mind, consider the following advice:

  • Make sure it's obvious which function call is local and which is remote.
  • Document your system. Make the dependencies between components clear.
  • Handle error cases. How should the client react when the RPC server is down for a long time?

When in doubt avoid RPC. If you can, you should use an asynchronous pipeline - instead of RPC-like blocking, results are asynchronously pushed to a next computation stage.

Callback queue

In general doing RPC over RabbitMQ is easy. A client sends a request message and a server replies with a response message. In order to receive a response we need to send a 'callback' queue address with the request. We can use the default queue. Let's try it:

q = ch.queue("", :exclusive => true)
x = ch.default_exchange

x.publish(message, :routing_key => "rpc_queue", :reply_to => q.name)

# ... then code to read a response message from the callback_queue ...

Message properties

The AMQP protocol predefines a set of 14 properties that go with a message. Most of the properties are rarely used, with the exception of the following:

  • :persistent: Marks a message as persistent (with a value of true) or transient (false). You may remember this property from the second tutorial.
  • :content_type: Used to describe the mime-type of the encoding. For example for the often used JSON encoding it is a good practice to set this property to: application/json.
  • :reply_to: Commonly used to name a callback queue.
  • :correlation_id: Useful to correlate RPC responses with requests.

Correlation Id

In the method presented above we suggest creating a callback queue for every RPC request. That's pretty inefficient, but fortunately there is a better way - let's create a single callback queue per client.

That raises a new issue, having received a response in that queue it's not clear to which request the response belongs. That's when the :correlation_id property is used. We're going to set it to a unique value for every request. Later, when we receive a message in the callback queue we'll look at this property, and based on that we'll be able to match a response with a request. If we see an unknown :correlation_id value, we may safely discard the message - it doesn't belong to our requests.

You may ask, why should we ignore unknown messages in the callback queue, rather than failing with an error? It's due to a possibility of a race condition on the server side. Although unlikely, it is possible that the RPC server will die just after sending us the answer, but before sending an acknowledgment message for the request. If that happens, the restarted RPC server will process the request again. That's why on the client we must handle the duplicate responses gracefully, and the RPC should ideally be idempotent.

Summary

digraph { bgcolor=transparent; truecolor=true; rankdir=LR; node [style="filled"]; // subgraph cluster_C { label="Client"; color=transparent; C [label="C", fillcolor="#00ffff"]; }; subgraph cluster_XXXa { color=transparent; subgraph cluster_Note { color=transparent; N [label="Request\nreplyTo=amqp.gen-Xa2...\ncorrelationId=abc", fontsize=12, shape=note]; }; subgraph cluster_Reply { color=transparent; R [label="Reply\ncorrelationId=abc", fontsize=12, shape=note]; }; }; subgraph cluster_XXXb { color=transparent; subgraph cluster_RPC { label="rpc_queue"; color=transparent; RPC [label="{<s>||||<e>}", fillcolor="red", shape="record"]; }; subgraph cluster_REPLY { label="replyTo=amq.gen-Xa2..."; color=transparent; REPLY [label="{<s>||||<e>}", fillcolor="red", shape="record"]; }; }; subgraph cluster_W { label="Server"; color=transparent; W [label="S", fillcolor="#00ffff"]; }; // C -> N; N -> RPC:s; RPC:e -> W; W -> REPLY:e; REPLY:s -> R; R -> C; }

Our RPC will work like this:

Putting it all together

The Fibonacci task:

def self.fib(n)
  case n
  when 0 then 0
  when 1 then 1
  else
    fib(n - 1) + fib(n - 2)
  end
end

We declare our fibonacci function. It assumes only valid positive integer input. (Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible).

The code for our RPC server rpc_server.rb looks like this:

#!/usr/bin/env ruby
# encoding: utf-8

require "bunny"

conn = Bunny.new
conn.start

ch   = conn.create_channel

class FibonacciServer

  def initialize(ch)
    @ch = ch
  end

  def start(queue_name)
    @q = @ch.queue(queue_name)
    @x = @ch.default_exchange

    @q.subscribe(:block => true) do |delivery_info, properties, payload|
      n = payload.to_i
      r = self.class.fib(n)

      @x.publish(r.to_s, :routing_key => properties.reply_to, :correlation_id => properties.correlation_id)
    end
  end

  def self.fib(n)
    case n
    when 0 then 0
    when 1 then 1
    else
      fib(n - 1) + fib(n - 2)
    end
  end
end

begin
  server = FibonacciServer.new(ch)
  " [x] Awaiting RPC requests"
  server.start("rpc_queue")
rescue Interrupt => _
  ch.close
  conn.close
end

The server code is rather straightforward:

The code for our RPC client rpc_client.rb:

#!/usr/bin/env ruby
# encoding: utf-8

require "bunny"
require "thread"

conn = Bunny.new(:automatically_recover => false)
conn.start

ch   = conn.create_channel

class FibonacciClient
  attr_reader :reply_queue
  attr_accessor :response, :call_id
  attr_reader :lock, :condition

  def initialize(ch, server_queue)
    @ch             = ch
    @x              = ch.default_exchange

    @server_queue   = server_queue
    @reply_queue    = ch.queue("", :exclusive => true)

    @lock      = Mutex.new
    @condition = ConditionVariable.new
    that       = self

    @reply_queue.subscribe do |delivery_info, properties, payload|
      if properties[:correlation_id] == that.call_id
        that.response = payload.to_i
        that.lock.synchronize{that.condition.signal}
      end
    end
  end

  def call(n)
    self.call_id = self.generate_uuid

    @x.publish(n.to_s,
      :routing_key    => @server_queue,
      :correlation_id => call_id,
      :reply_to       => @reply_queue.name)

    lock.synchronize{condition.wait(lock)}
    response
  end

  protected

  def generate_uuid
    # very naive but good enough for code
    # examples
    "#{rand}#{rand}#{rand}"
  end
end

client   = FibonacciClient.new(ch, "rpc_queue")
puts " [x] Requesting fib(30)"
response = client.call(30)
puts " [.] Got #{response}"

ch.close
conn.close

Now is a good time to take a look at our full example source code (which includes basic exception handling) for rpc_client.rb and rpc_server.rb.

Our RPC service is now ready. We can start the server:

$ ruby -rubygems rpc_server.rb
 [x] Awaiting RPC requests

To request a fibonacci number run the client:

$ ruby -rubygems rpc_client.rb
 [x] Requesting fib(30)

The design presented here is not the only possible implementation of a RPC service, but it has some important advantages:

Our code is still pretty simplistic and doesn't try to solve more complex (but important) problems, like:

If you want to experiment, you may find the rabbitmq-management plugin useful for viewing the queues.