> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-rabbitmq.md).

# RabbitMQ consumers

{% hint style="info" %}
Availability of the functionality depends on the license and may not be available in all deployments.
{% endhint %}

## Purpose

Processes in Eximee may consist of steps that require asynchronous communication with external systems. Example: we send a request for document verification, but it is time-consuming, so we will have to wait for a response. This task may be performed asynchronously in an external system and it may notify the Eximee process via a RabbitMQ queue. RabbitMQ consumers are used precisely to handle such responses. We use them to receive the message, pre-process the data contained in it, and notify Eximee BPMS to continue process execution.

## How it works

The whole flow consists of four elements:

```
1. Eximee process sends a request to the external system, including the process instance ID,
                           and stops at the "Message Intermediate Catch Event" step
                           
2. External system performs the work and publishes the response to the RabbitMQ queue,
                           sending back the process instance ID in it
                           
3. lowcode-queue-consumer receives the message from the queue and runs the consumer script
                           assigned to that queue
                           
4. Consumer script reads the process instance ID and sends to Eximee BPMS
                           a message that resumes the process
```

Message reception is handled by the application `lowcode-queue-consumer`. The application knows which consumer handles which queue, thanks to the mapping set by the administrator in its configuration. The consumer itself does not contain queue information.

## Step 1. Agree on the details with the administrators

Before preparing the process, agree with the administrators on:

* **queue**, from which the consumer is to receive messages. The queue is created on the broker by the RabbitMQ administrator,
* **DLQ queue**, to which messages that the consumer does not process will be sent,
* **connection name** with the broker, in which the administrators will configure the queue, for example `integration`. The process designer may suggest a name, and the administrators confirm it or indicate an existing connection. The consumer script does not use this name; the administrators need it for configuration,
* **consumer name**, for example `message_consumer_demo`. The name is chosen by the process designer, and the administrators enter it in the queue-to-consumer mapping.

Without mapping the queue to a consumer, the consumer does not receive any messages.

### Example request

Send the agreed details to the administrators in a request, for example:

```
Request for RabbitMQ consumer configuration in the lowcode-queue-consumer application:
- queue: eximee_demo_integration
- consumer: message_consumer_demo
- DLQ: eximee_demo_integration.dlq
- connection: integration
```

The configuration that the administrators prepare based on this is described on the page [RabbitMQ consumer configuration](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-rabbitmq/konfiguracja.md).

{% hint style="warning" %}
Register the consumer in Eximee Designer before messages start arriving on the queue. A message that arrives when the consumer with the mapped name does not yet exist will go to the DLQ.
{% endhint %}

## Step 2. Prepare the process

### Add a message wait step

At the point where the process should wait for the response, add a step of type **Message Intermediate Catch Event**. In the step panel, expand the **Message** section **Name** field enter the message name. The name must meet Eximee BPMS requirements ([Message Events](https://docs.eximeebpms.org/manual/latest/reference/bpmn20/events/message-events/)). The same name will later go into the consumer script.

In the examples on this page, the message name is `lowcodeDemoMessage`.

![Illustration 1. Example process with a "Message Intermediate Catch Event" step](https://2112972046-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2CssJT0zIo4SJQLbSZ6l%2Fuploads%2Fgit-blob-74ec36fdac49329c020b3a5f516809e7a7124e17%2Fi1.png?alt=media)

![Illustration 2. Example configuration of a "Message Intermediate Catch Event" step](https://2112972046-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2CssJT0zIo4SJQLbSZ6l%2Fuploads%2Fgit-blob-166b74f6b97fb0a70f393eee8e1f0025ff8763e7%2Fi2.png?alt=media)

### Send the process instance ID to the external system

The consumer resumes the process solely based on the process instance ID (`processInstanceId`). Resumption by business key is not available. So the external system must receive this ID in the request and return it in the response.

In the examples on this page, a message with the process instance ID goes to the queue `eximee_demo_integration`. Such a message can be sent from a script with Eximee's help; this is described on the page [Lowcode to RabbitMQ](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/lowcode-do-rabbitmq.md#przykladowy-skrypt-uslugowy). Such a message can also be sent by an external system.

{% hint style="warning" %}
The process must wait at the "Message Intermediate Catch Event" step before the response arrives. If the response arrives earlier, for example when the external system responds immediately and the process has not yet reached the wait step, Eximee BPMS will reject the message. The platform then does not retry: the message goes to the DLQ or, if no DLQ is configured, is lost. Design the process so that after the request is sent, the wait step is reached without unnecessary intermediate steps.
{% endhint %}

## Step 3. Agree on the message format

The platform does not impose a message format. Agree it with the external system team before writing the consumer. The message must contain the process instance ID.

Example of the format used later on this page:

```json
{
  "processInstanceId": "8f0b7a52-0c43-11ef-9a1c-0242ac120002",
  "data": "sample value"
}
```

The message content is read as text in UTF-8 encoding. If the message is JSON, the script converts it to an object itself using `JSON.parse`.

## Step 4. Create a consumer in Eximee Designer

1. In Eximee Designer open **Library** → **Consumers**.
2. Click **Add Consumer**.
3. Enter the consumer name agreed with the administrators in step 1, for example `message_consumer_demo`.
4. Write the consumer script and save it.

{% hint style="warning" %}
Currently the consumer is not part of the application. When migrating the application to another environment, the consumer will not be migrated with it. Move it separately, in addition to the application.
{% endhint %}

The same consumer can handle messages from RabbitMQ and Kafka. Where the messages come from is determined solely by the administrator configuration.

### Example consumer script

Consumer script `message_consumer_demo` receives the message in the format from step 3, validates it, and resumes the process:

```javascript
function consumeMessage(context) {
    const MESSAGE_NAME = 'lowcodeDemoMessage';
    const message = context.getMessage();

    let payload;
    try {
        payload = JSON.parse(message.value);
    } catch (e) {
        // exception: the message will go to the DLQ
        throw new Error('The message content is not valid JSON');
    }

    if (!payload.processInstanceId) {
        // exception: the message will go to the DLQ
        throw new Error('Missing processInstanceId in the message content');
    }
    const processInstanceId = String(payload.processInstanceId);

    // process variables set together with the message; values must be text
    const variables = {
        rabbitData: (payload.data === undefined || payload.data === null) ? '' : String(payload.data)
    };

    // if the process is not waiting for this message, the function will throw an error and the message will go to the DLQ
    api.process.v1.byInstanceId(processInstanceId).correlateMessage(MESSAGE_NAME, variables);
    Logger.info('Process resumed [processInstanceId={}]', nonsensitive(processInstanceId));
}
```

After receiving the sample message from step 3, the process with ID `8f0b7a52-0c43-11ef-9a1c-0242ac120002` continues and receives the variable `rabbitData` = `sample value`.

### Writing rules for the consumer

* Resume the process by calling `api.process.v1.byInstanceId(processInstanceId).correlateMessage(nazwaWiadomosci, zmienne)`. The consumer does not run in the context of any process, so always specify the instance ID explicitly, through `byInstanceId`.
* Variables passed to `correlateMessage` must have text values. Convert numbers and boolean values to text with the function `String()`. The second parameter can be omitted if the process does not need any variables.

{% hint style="info" %}
Consumers have limited access to the API. They can use only the `Logger` object and the functions `api.process.v1.byInstanceId(processInstanceId)`: `correlateMessage`, `getProcessInfo` and `getUserTaskInfo`. Other functions `api.process`, for example `startProcess` and `setAccessGroups`, are unavailable in the consumer, as are REST calls and message sending. More about the process API: [Operations and access to process data](https://github.com/Consdata/eximee-docs/tree/main/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/operacje-i-dostep-do-danych-procesu.md)
{% endhint %}

### Ending the script and the fate of the message

What happens to the message depends solely on how the script ends:

| Script ending                                                                            | What happens to the message                                                                |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| The script ends normally or via `return`                                                 | The message is considered handled and removed from the queue.                              |
| The script throws an exception (`throw`), including an exception from `correlateMessage` | The message is rejected and sent to the DLQ. If no DLQ is configured, the message is lost. |

{% hint style="danger" %}
Do not catch errors in the script just to log them. If the script catches an error and ends normally, the message will be removed from the queue and will not go to the DLQ, so it cannot be analyzed or processed again. Use `return` only for messages you intentionally want to skip.
{% endhint %}

The platform does not retry processing of a message that the script failed to process. Such a message goes directly to the DLQ.

## Message data available in the script

Function `context.getMessage()` returns the message along with metadata:

| Field              | Type     | Description                                                                                                       |
| ------------------ | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `value`            | `string` | Message content.                                                                                                  |
| `headers`          | object   | Message headers. Read a header value with the function `headers.get('name')`.                                     |
| `key`              | `string` | Message ID (property `message_id`). `null`, if the sender did not set it.                                         |
| `topic`            | `string` | Queue name from which the message originates.                                                                     |
| `timestamp`        | `number` | Message creation time in milliseconds since 1970-01-01 (property `timestamp`). `0`, if the sender did not set it. |
| `queue.queue`      | `string` | Queue name from which the message originates.                                                                     |
| `queue.exchange`   | `string` | Exchange from which the message was routed to the queue. Empty for the default exchange.                          |
| `queue.routingKey` | `string` | Routing key with which the message was routed to the queue.                                                       |

Field `event` is filled in only for messages from Kafka. In a RabbitMQ message it has the value `null`, so a script handling both sources will be able to tell from it where the message came from.

{% hint style="warning" %}
Read headers with the function `get`: `message.headers.get('x-correlation-id')`. The expression `message.headers['x-correlation-id']` returns `undefined`.
{% endhint %}

Example of reading metadata:

```javascript
function consumeMessage(context) {
    const message = context.getMessage();

    const correlationId = message.headers.get('x-correlation-id');
    Logger.info('Received message [queue={}, exchange={}, routingKey={}, correlationId={}]',
        nonsensitive(message.queue.queue),
        nonsensitive(message.queue.exchange),
        nonsensitive(message.queue.routingKey),
        nonsensitive(correlationId));
}
```

## Troubleshooting

| Symptom                                                                                                          | Possible cause                                                                                                                                                      | Solution                                                                                                                                       |
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| The message goes to the DLQ and the process does not continue                                                    | The process was not waiting at the wait step, the message name in `correlateMessage` differs from the name in the process, or the process instance ID is incorrect. | Check the application log `lowcode-queue-consumer` for this message. Make sure the message name is identical in the process and in the script. |
| The message disappears and is in no queue                                                                        | The script ended by `return` either by catching an error, or no DLQ was configured for the queue.                                                                   | Raise an exception for messages that cannot be processed, and ask the administrators to configure a DLQ.                                       |
| After migrating the application to another environment, messages go to the DLQ and the process does not continue | The consumer was not migrated to this environment. The consumer is not part of the application and is not migrated with it.                                         | Move the consumer to this environment separately, in addition to the application.                                                              |
| Change in the consumer script does not work                                                                      | The consumer was not saved or the cache has a long TTL.                                                                                                             | Save the consumer and ask the administrators to clear the cache.                                                                               |

Problems starting the application, connecting to the broker, and queue mapping are described on the page [RabbitMQ consumer configuration](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-rabbitmq/konfiguracja.md#rozwiazywanie-problemow). There you will also find how to verify the consumer works using a test message.

## Related pages

* [RabbitMQ consumer configuration](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-rabbitmq/konfiguracja.md) — application configuration `lowcode-queue-consumer`, queues, and DLQ.
* [Lowcode to RabbitMQ](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/lowcode-do-rabbitmq.md) — sending messages to a queue from scripts and script tasks.
* [Kafka consumers](https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-kafka.md) — the same mechanism for messages from Kafka.
* [Operations and access to process data](https://github.com/Consdata/eximee-docs/tree/main/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/operacje-i-dostep-do-danych-procesu.md) — API `api.process`.
* [Script Task API](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/zadanie-skryptowe-scripttask/api-zadan-skryptowych.md) — writing script tasks in a process.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eximee.com/documentation/documentation-en/eksploatacja-aplikacji/obsluga-zdarzen/konsumenci-rabbitmq.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
