Hide navigation sidebar
Hide table of contents sidebar
Skip to content
Back to top
View this page
Edit this page
Toggle table of contents sidebar

# Remote procedure call (RPC)

Warning

This is a beta version of the port from official tutorial. Please when you found an error create issue or pull request for me.

This implementation is a part of official tutorial. Since version 1.7.0 aio-pika has patterns submodule.

You might use `aio_pika.patterns.RPC` for real projects.

Note

Using the aio-pika async Python client

Note

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:

    async def main():
        fibonacci_rpc = FibonacciRpcClient()
        result = await fibonacci_rpc.call(4)
        print("fib(4) is %r" % result)

Note

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 the client needs to send a ‘callback’ queue address with the request. Let’s try it:

    async def main():
        ...

        # Queue for results
        callback_queue = await channel.declare_queue(exclusive=True)

        await channel.default_exchange.publish(
            Message(
                request,
                reply_to=callback_queue.name
            ),
            routing_key='rpc_queue'
        )

        # ... and some code to read a response message from the callback_queue ...

    ...

Note

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:

- delivery_mode: Marks a message as persistent (with a value of 2) or transient (any other value). 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.

See additional info in `aio_pika.Message`

## 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

Our RPC will work like this:

- When the Client starts up, it creates an anonymous exclusive callback queue.

- For an RPC request, the Client sends a message with two properties: reply_to, which is set to the callback queue and correlation_id, which is set to a unique value for every request.

- The request is sent to an rpc_queue queue.

- The RPC worker (aka: server) is waiting for requests on that queue. When a request appears, it does the job and sends a message with the result back to the Client, using the queue from the reply_to field.

- The client waits for data on the callback queue. When a message appears, it checks the correlation_id property. If it matches the value from the request it returns the response to the application.

## Putting it all together

The code for `rpc_server.py`:

     1import asyncio
     2import logging
     3
     4from aio_pika import Message, connect
     5from aio_pika.abc import AbstractIncomingMessage
     6
     7
     8def fib(n: int) -> int:
     9    if n == 0:
    10        return 0
    11    elif n == 1:
    12        return 1
    13    else:
    14        return fib(n - 1) + fib(n - 2)
    15
    16
    17async def main() -> None:
    18    # Perform connection
    19    connection = await connect("amqp://guest:guest@localhost/")
    20
    21    # Creating a channel
    22    channel = await connection.channel()
    23    exchange = channel.default_exchange
    24
    25    # Declaring queue
    26    queue = await channel.declare_queue("rpc_queue")
    27
    28    print(" [x] Awaiting RPC requests")
    29
    30    # Start listening the queue with name 'hello'
    31    async with queue.iterator() as qiterator:
    32        message: AbstractIncomingMessage
    33        async for message in qiterator:
    34            try:
    35                async with message.process(requeue=False):
    36                    assert message.reply_to is not None
    37
    38                    n = int(message.body.decode())
    39
    40                    print(f" [.] fib({n})")
    41                    response = str(fib(n)).encode()
    42
    43                    await exchange.publish(
    44                        Message(
    45                            body=response,
    46                            correlation_id=message.correlation_id,
    47                        ),
    48                        routing_key=message.reply_to,
    49                    )
    50                    print("Request complete")
    51            except Exception:
    52                logging.exception("Processing error for message %r", message)
    53
    54if __name__ == "__main__":
    55    asyncio.run(main())

The server code is rather straightforward:

- 34. As usual we start by establishing the connection and declaring the queue.

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

- (15) We declare a callback for basic_consume, the core of the RPC server. It’s executed when the request is received. It does the work and sends the response back.

The code for `rpc_client.py`:

     1import asyncio
     2import uuid
     3from typing import MutableMapping
     4
     5from aio_pika import Message, connect
     6from aio_pika.abc import (
     7    AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue,
     8)
     9
    10
    11class FibonacciRpcClient:
    12    connection: AbstractConnection
    13    channel: AbstractChannel
    14    callback_queue: AbstractQueue
    15
    16    def __init__(self) -> None:
    17        self.futures: MutableMapping[str, asyncio.Future] = {}
    18
    19    async def connect(self) -> "FibonacciRpcClient":
    20        self.connection = await connect("amqp://guest:guest@localhost/")
    21        self.channel = await self.connection.channel()
    22        self.callback_queue = await self.channel.declare_queue(exclusive=True)
    23        await self.callback_queue.consume(self.on_response, no_ack=True)
    24
    25        return self
    26
    27    async def on_response(self, message: AbstractIncomingMessage) -> None:
    28        if message.correlation_id is None:
    29            print(f"Bad message {message!r}")
    30            return
    31
    32        future: asyncio.Future = self.futures.pop(message.correlation_id)
    33        future.set_result(message.body)
    34
    35    async def call(self, n: int) -> int:
    36        correlation_id = str(uuid.uuid4())
    37        loop = asyncio.get_running_loop()
    38        future = loop.create_future()
    39
    40        self.futures[correlation_id] = future
    41
    42        await self.channel.default_exchange.publish(
    43            Message(
    44                str(n).encode(),
    45                content_type="text/plain",
    46                correlation_id=correlation_id,
    47                reply_to=self.callback_queue.name,
    48            ),
    49            routing_key="rpc_queue",
    50        )
    51
    52        return int(await future)
    53
    54
    55async def main() -> None:
    56    fibonacci_rpc = await FibonacciRpcClient().connect()
    57    print(" [x] Requesting fib(30)")
    58    response = await fibonacci_rpc.call(30)
    59    print(f" [.] Got {response!r}")
    60
    61
    62if __name__ == "__main__":
    63    asyncio.run(main())

The client code is slightly more involved:

- 15. We establish a connection, channel and declare an exclusive ‘callback’ queue for replies.

- 22. We subscribe to the ‘callback’ queue, so that we can receive RPC responses.

- (26) The ‘on_response’ callback executed on every response is doing a very simple job, for every response message it checks if the correlation_id is the one we’re looking for. If so, it saves the response in self.response and breaks the consuming loop.

- 30. Next, we define our main call method - it does the actual RPC request.

- (31) In this method, first we generate a unique correlation_id number and save it - the ‘on_response’ callback function will use this value to catch the appropriate response.

- (36) Next, we publish the request message, with two properties: reply_to and correlation_id. And finally we return the response back to the user.

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

    $ python rpc_server.py
    [x] Awaiting RPC requests

To request a fibonacci number run the client:

    $ python rpc_client.py
    [x] Requesting fib(30)

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

If the RPC server is too slow, you can scale up by just running another one. Try running a second rpc_server.py in a new console. On the client side, the RPC requires sending and receiving only one message. No synchronous calls like queue_declare are required. As a result the RPC client needs only one network round trip for a single RPC request. Our code is still pretty simplistic and doesn’t try to solve more complex (but important) problems, like:

- How should the client react if there are no servers running?

- Should a client have some kind of timeout for the RPC?

- If the server malfunctions and raises an exception, should it be forwarded to the client?

- Protecting against invalid incoming messages (eg checking bounds) before processing.

Note

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

Note

This material was adopted from official tutorial on rabbitmq.org.