Skip to main content

Update Queue

Overview​

The update queue is part of the Genesis database layer and is the underlying technology that powers real-time updates.

Genesis provides an update queue so that processes can be kept up-to-date with the latest changes in the database, without needing to poll the database:

In the above example, the data_server exposes the all_trades resource. This should provide all trades within the application. When the data_server starts, it will contact the db_server and read all the trades from the database. At the same time, the data_server also starts listening to the update queue.

When the event_handler receives a trade insert event, it writes this to the db_server database, using its local database connection (event_db). After the update has been written, the process publishes the update on the update queue to be consumed by any subscribers.

As the data_server is automatically subscribed to those updates from the update queue, it gets the updates without having to re-query the database.

There are three different update queue technologies to choose from, depending on your requirements:

  • ZeroMQ (Default) - a decentralized peer-to-peer set-up, which relies on a fixed cluster size
  • MQTT - use an independent MQTT broker if you want to allow dynamic scaling
  • JMS - use an independent Jakarta Messaging broker (former JMS)

Update order with MQTT and JMS​

From versions 8.15.45 and 10.0.1, the MQTT and JMS update queues publish updates one at a time, in the order they were submitted, and deliver updates for the same record in the order they arrive. Updates for different records may be delivered in a different order.

ZeroMQ​

The Genesis Application Platform uses ZeroMQ out of the box to provide a zero-configuration decentralized peer-to-peer update queue.

It works because the GENESIS_CLUSTER process knows (via clustering) all the nodes within the cluster - so it can broadcast and consume appropriately.

  • ZeroMQ is best suited for fixed-sized deployments.
  • MQTT or JMS are recommended for set-ups that require dynamic scaling.

Proxy mode​

All processes have a ZeroMQ port, which is their process port + 10000. Additionally, GENESIS_CLUSTER has two additional ports (ZeroMQProxyInboundPort and ZeroMQProxyOutboundPort) to act as proxy ports. This is necessary so that:

  • scripts can publish to ZeroMQ without having an allocated port
  • it can run in ZeroMQ “proxy” mode

The platform can be configured to run with or without proxy mode, and this setting applies to all processes.

When running under non-proxy mode, each process binds to its ZeroMQ port and all other processes need to connect to that port to receive updates. This mode isn't recommended for large apps, as 10 microservices will have 10 publishers - which will give us 100 connections.

When in non-proxy mode, all processes need to connect to the GENESIS_CLUSTER proxy ports, as scripts or other non-genesis processes could be publishing updates through those.

When running under proxy mode, each process connects to the ZeroMQProxyInboundPort to publish data and subscribes to the ZeroMQProxyOutboundPort to receive data, therefore reducing the total number of connections.

ZeroMQ configuration options​

ZeroMQ is the default MQ system in Genesis, but it can be set explicitly with the following config:

genesis-system-definition.kts
systemDefinition {
global {
...
item(name = "MqLayer", value = "ZeroMQ")
...
}
}

Other config values that are available are listed below:

Config ItemDescriptionDefault
ZeroMQProxyInboundPort (required)The port used for ZeroMQ inbound connections. See the example system definition-
ZeroMQProxyOutboundPort (required)The port used for ZeroMQ outbound connections. See the example system definition-
ZeroMQProxyModeEnabledEnable proxy mode (recommended for large apps)false
ZeroMQProxyUnicastRelayEnabledCreates a point-to-point connection between GENESIS_CLUSTER processes for all the nodes in the cluster. This connection is used to send local update queue events to the remote nodes in the cluster in order to ensure every node has access to all the updates. The relay connects to each peer GENESIS_CLUSTER's service port (from its service definition), so that port must be open between nodes. In the standard service list for containers, GENESIS_CLUSTER uses port 9000; check your own service definition for the port your project usesfalse
ZeroMQProxyUnicastRelayExcludedTopicsString based comma-separated list of topics to be excluded from Unicast relay retransmission. Useful to avoid unnecessary data transfer between GENESIS_CLUSTER services for topics that do not need real-time processing. Example: "TRADE_AUDIT,ORDER_AUDIT"""
ZeroMQConnectToLocalhostViaLoopbackDepending on the OS, routing may be subject to network flapping (quick changes in network routing) - this setting binds ZeroMQ communication to the local interface (localhost). Do not use in Production.false
important

If you are using a cloud environment that does not allow multicast traffic (e.g. AWS), then ZeroMQProxyModeEnabled and ZeroMQProxyUnicastRelayEnabled must be set to true

Securing ZeroMQ with CURVE​

CURVE is ZeroMQ's built-in public-key security. You can use it to encrypt and authenticate update-queue traffic between processes. It applies only when MqLayer is ZeroMQ, and it is off by default.

With CURVE on, each update-queue connection starts with a CURVE handshake. The connecting process proves who it is with the client key, and everything sent over the connection is encrypted. This works with or without proxy mode:

  • Without proxy mode, it covers the connections from subscribers to each process's publisher, and the connections that every process makes to the GENESIS_CLUSTER proxy ports.
  • In proxy mode, it covers the connections from publishers to the GENESIS_CLUSTER proxy, and from the proxy to subscribers.
  • With ZeroMQProxyUnicastRelayEnabled, it does not cover the link between nodes. That link is Genesis messaging on the GENESIS_CLUSTER service port, not ZeroMQ. Service TLS covers it instead; under selective TLS it is encrypted only if the GENESIS_CLUSTER service is marked secure. A multi-node deployment with the relay enabled therefore needs both CURVE and TLS to encrypt the whole update-queue path.
  • Without the relay, subscribers connect directly to the other nodes over ZeroMQ, and CURVE covers those connections.

All processes share one server keypair and one client keypair. A server accepts a client only if the client's public key has a certificate in the server's allowedClientCertDirectory.

Enabling CURVE​

  1. Generate the keys and the client certificate with GenerateZeroMqCurveKeys.
  2. Add the zeroMqEncryption block that the command prints to site-specific/cfg/network-config.yaml. In a project, including local development with Genesis Start, put this file in your application module's src/main/genesis/cfg/ directory, named exactly network-config.yaml (not prefixed with the product name), and the build copies it to site specific; edits made directly to the deployed copy are overwritten by the next build. The block refers to the keys through ${...} environment variable placeholders, which are resolved when the configuration is loaded. Every key is listed in the network configuration YAML reference.
  3. On every host, export the four ZMQ_CURVE_* environment variables in the environment that the processes start from. The keys can contain $ and other shell-special characters, so single-quote each value when you export it, and in a Docker Compose env file write each $ as $$. When you run locally with Genesis Start, export them in the shell (or IDE run configuration) that launches Genesis Start (./gradlew genesisStart); Genesis Start's .properties overrides can't set them. If Genesis Start is already running, stop it and launch it again from the shell where you exported the variables. Restarting processes from Genesis Start is not enough: they inherit its environment, which was fixed when it started.
  4. On every host, make sure the client certificate is in the directory that allowedClientCertDirectory names.
  5. On every host, run GenerateZeroMqCurveKeys --verify. It checks the deployed network-config.yaml, not the copy in your project source, so if you work from a project, the project must be synced to your local Genesis home first. In a project, run it from Genesis Start: choose Add Config → Run Script, select the script GenerateZeroMqCurveKeys and enter --verify as the arguments. Genesis Start syncs the project to your local Genesis home before it runs the script, so --verify checks your current file, and the script runs in the environment that Genesis Start was launched with, including the ZMQ_CURVE_* variables you exported in step 3. The output is in the script's log in Genesis Start. Without Genesis Start, run ./gradlew genesisSync and then run GenerateZeroMqCurveKeys --verify from the deployed Genesis home. The command prints Read <path> with the file it checked, so you can confirm it read the right one. In a project this is the file in the synced home, for example generated/cfg/network-config.yaml, not the one in src/main/genesis/cfg/.
  6. Restart every process on every node. --verify checks only the configuration, so confirm delivery by checking that update-driven parts of the application, such as a Data Server subscription or a UI grid, still receive changes after the restart.

How the client .key certificate file is copied to each host, and which secret manager supplies the four ZMQ_CURVE_* values, are left to your own tooling; Genesis provides neither.

warning

Turn CURVE on everywhere at the same time. A process with CURVE on can't exchange update-queue messages with a process that has it off, or with one that uses different keys. You can't switch it on one process at a time. Turn it on for every process on every node, GENESIS_CLUSTER included, in a single restart window. A zeroMqEncryption block in a process-level network-config-<PROCESS_NAME>.yaml is honoured: it is merged key by key over network-config.yaml, so a process given different keys fails its handshakes with its peers. Never do this in production, but you can use it to give one process a different keypair (point its placeholders at different variables, or for a throwaway test, paste a second generated keypair) when you want to test a mismatch.

Configuration errors​

If zeroMqEncryption.enabled is true, a process won't start unless:

  • all four keys are set, and each one is a 40-character Z85 key
  • allowedClientCertDirectory is set to a directory that exists and can be read

The error names the YAML key that's wrong. For example: curveServerPublicKey is required when ZeroMQ CURVE is enabled.

For the full list of error messages, see the Validation table in the zeroMqEncryption section of the network configuration YAML reference.

If an environment variable isn't set, the error names it. For example: curveServerSecretKey was not resolved: set the ZMQ_CURVE_SERVER_SECRET environment variable, or disable ZeroMQ CURVE. GenerateZeroMqCurveKeys --verify reports unset variables before you restart.

Handshake failures​

A configuration that passes these checks can still fail its handshake with a peer. The usual causes are:

  • CURVE is on in one process and off in the other.
  • The two processes have different server keys.
  • The client key has no certificate in the peer's allowedClientCertDirectory.

ZeroMQ doesn't retry a connection whose handshake failed, so update-queue messages to and from that peer are lost. For a process with CURVE on, what happens next depends on its other connections:

  • The handshake failed with every peer it connects to. This process is most likely the one that's misconfigured. It logs an ERROR with the likely cause, then shuts down. In proxy mode, a process connects to just one peer, the proxy, so one failure is enough to stop it. A misconfigured GENESIS_CLUSTER therefore stops every process that connects to its proxy.
  • The handshake failed with some peers, but others are connected. The process keeps running. It logs an ERROR naming the failed peer and the likely cause, and repeats it every minute.
  • Some peers haven't connected yet. The process doesn't shut down while it waits for them. A peer counts only once its first handshake has either succeeded or failed.

The side that accepts a connection never shuts down because of a bad handshake from a peer. It logs the rejected handshake at ERROR, at most once a minute for each host and cause. A process with CURVE off never shuts down either. If its handshake with a CURVE peer fails, it logs the error and keeps running.

note

A process doesn't reconnect to a peer whose handshake failed, even after the peer is fixed and restarted. After you fix a misconfigured process, restart the processes that logged errors about it.

Subscriber readiness​

A subscriber isn't connected until its handshake completes. So that messages aren't lost in the meantime, a publisher with CURVE on holds each message for up to readinessTimeoutMillis (default: 5 seconds) until a subscriber has subscribed to its topic. If nobody subscribes in time, the publisher logs a warning, Publishing ZeroMQ topic '<topic>' before subscriber readiness was observed, sends the message anyway, and from then on sends messages on that topic without waiting. With CURVE off, messages are sent straight away, as they were before.

Using loopback (development environments)​

If you are developing on a laptop, you might be affected by automatic switching between networks; for example, the operating system could suddenly switch to a hotspot. When this happens, the message queue could stop receiving updates. As a result, your processes could go down inexplicably.

To avoid this, set ZeroMQConnectToLocalhostViaLoopback = true. This setting uses the local network stack to ensure that no messages are lost.

warning

Never use this setting in a production environment.

MQTT​

The Genesis Application Platform provides the option to use an external MQTT broker such as Mosquitto or RabbitMQ as the transport mechanism for the Genesis update queue.

Using a centralized external broker is highly recommended for complex, large or dynamically scaled clusters, as it reduces the complexity and overhead of peer-to-peer connectivity.

MQTT configuration options​

To use MQTT in your Genesis application, you need to set the MqLayer in the system definition.

genesis-system-definition.kts
systemDefinition {
global {
...
item(name = "MqLayer", value = "MQTT")
...
}
}

Other config values that are available are listed below:

Config ItemDescriptionDefault
MqttBrokerUrlThe URL of the MQTT brokertcp://localhost:1883
MqttQosThe MQTT Quality of Service level

At most once (0)
At least once (1)
Exactly once (2)
2
MqttClientIdA template pattern for the client ID. You can use {{PROCESS_NAME}}, {{HOST_NAME}} (the local host name) and environment variables; the default's {{HOSTNAME}} is the HOSTNAME environment variablegenesis/{{HOSTNAME}}/{{PROCESS_NAME}}
MqttQueueNamePatternA template pattern for the queue name using TABLE_NAMEgenesis/database/{{TABLE_NAME}}
MqttThreadPoolSizeNumber of threads to use4
MqttUsernameMQTT Usernamenull
MqttPasswordMQTT Passwordnull
MqttTlsVerifySetting to false ignores certificate verification. This should only be set to false in a dev or test environment.true

JMS​

The Genesis platform enables you to use a Jakarta Messaging (former JMS) compliant message broker as its real-time update-queue back-end via ArtemisMQ.

Using a centralized external broker is highly recommended for complex, large or dynamically scaled clusters, as it reduces the complexity and overhead of peer-to-peer connectivity at the cost of maintaining or (re-using) a message broker.

Prerequisites​

To use Genesis Jakarta Messaging on the platform, you must install ArtemisMQ in the host (or hosts in case of High Availability). This is described in the ArtemisMQ documentation.

info

Genesis does not ship Artemis MQ server, just its client library.

JMS configuration options​

Basic configuration​

To use Jakarta Messaging in your Genesis application, set the MqLayer in your application's system definition file.

genesis-system-definition.kts
systemDefinition {
global {
...
item(name = "MqLayer", value = "JMS")
...
}
}

The Config variables are listed below.

Config ItemDescriptionDefault
JmsHostThe host name, can hold multiple values separated by comma; this enables you to use HA failovertcp://localhost:61616
JmsUsernameUsername to connect
JmsPasswordPassword to connect (can be encrypted using GenesisKey)
JmsClientIdA template pattern for the client ID, which identifies the process's durable subscriptions on the broker. You can use {{PROCESS_NAME}}, {{HOST_NAME}}, any system definition item and any of the process's environment variables, by name. See Stable client IDs.{{PROCESS_NAME}}@{{HOST_NAME}}
JmsTopicSubscriptionModeEnum value (TRANSIENT, PERSISTENT)TRANSIENT
JmsMaxConnectionRetryOnStartupHas no effect. The process keeps trying to connect to the broker, as set by JmsReconnectDelayMs20
JmsReconnectDelayMsThe amount of time in milliseconds (exponentially) for a connection reattempt to be made, in case of connectivity problems or other faults1000
JmsRetryToSendDelayMsThe amount of time in milliseconds before the first retry of a failed send; each later retry waits twice as long as the previous one, up to one minute (or up to this value, if it is longer)1000
JmsRetryToSendActionWhat to do when sending an update fails: RESCHEDULE or RETRY retries the update; IGNORE drops it. See Publish failuresRESCHEDULE
JmsRetryToSendLimitThe number of times a failed send is retried before the process stops publishing and shuts down. Applies only to RESCHEDULE and RETRY. With 0, the process shuts down on the first failed send. See Publish failures5

Publish failures​

warning

From versions 8.15.45 and 10.0.1, the process shuts down when an update still fails after all its retries. In earlier versions, the update was dropped with a WARN log and the process kept running, and RESCHEDULE put the update back on the queue instead of retrying it in place.

If an update fails to send and JmsRetryToSendAction is RESCHEDULE or RETRY (they behave the same), the process retries that update in place before it sends any other update. The first retry waits JmsRetryToSendDelayMs; each retry after that waits twice as long as the previous one, up to one minute (or up to JmsRetryToSendDelayMs, if that is longer). No other updates are published while it retries.

If the update still fails after JmsRetryToSendLimit retries, the process:

  • Logs an ERROR, closes its connection to the broker and reports the update queue as disconnected.
  • Does not send any of the updates queued behind the failed one, and logs each of them at ERROR.
  • Shuts down with exit status 1.

The process is restarted only if its process definition sets scheduleRestart to true, or if your deployment restarts it. The updates that were not sent never reach the broker, so no consumer receives them, durable consumers included; processes that load their data at startup, such as Data Servers, pick up those changes when they restart.

Only sends that fail on an open connection count towards the limit. With the defaults, the first send and five retries failing on an open connection take about 31 seconds, not counting reconnect time. While the broker is unreachable, the process keeps trying to reconnect, as set by JmsReconnectDelayMs; those attempts do not count, so a broker outage on its own does not shut the process down.

With JmsRetryToSendAction set to IGNORE, a failed update is dropped and logged at ERROR, and later updates are still sent.

Durable consumers​

You can configure specific processes to receive messages that were sent when the process was offline. This offers a useful method for processes to recover from missing messages without the need to replay an entire data stream.

For example, assume you have an application named alpha and you are going to set up ALPHA_CONSOLIDATOR to be a durable consumer of the update queue.

  1. Create a configuration file for the ALPHA_CONSOLIDATOR process with the contents:
alpha-consolidator-process-config.kts
process {
systemDefinition {
item(name = "JmsTopicSubscriptionMode", value = "PERSISTENT")
}
}
  1. Add the details of the newly created configuration to your application's processes.xml file:
procesess.xml
<process name="ALPHA_CONSOLIDATOR">
<groupId>ALPHA</groupId>
<start>true</start>
<options>-Xmx256m -DRedirectStreamsToLog=true -DXSD_VALIDATE=false -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5106</options>
<module>genesis-pal-consolidator</module>
<package>global.genesis.pal.consolidator</package>
<script>alpha-consolidator.kts</script>
<config>alpha-consolidator-process-config.kts</config>
<language>pal</language>
<primaryOnly>true</primaryOnly>
</process>
  1. Perform genesisInstall to apply the configuration and start the processes normally.
danger

Do not define JmsTopicSubscriptionMode at Global level, as this will cause all messages to be stored and delivered once the process is back online.

Stable client IDs​

The broker identifies a durable subscription by the client ID of the process that created it. The default client ID includes the host name, so if a durable consumer restarts on a host with a different name (for example, a pod in a Kubernetes Deployment), it creates a new subscription. The old one is never consumed again and keeps accumulating messages on the broker.

If you use JmsTopicSubscriptionMode = PERSISTENT where host names change between restarts, set JmsClientId to a pattern that stays the same across restarts. For example:

alpha-consolidator-process-config.kts
process {
systemDefinition {
item(name = "JmsTopicSubscriptionMode", value = "PERSISTENT")
// one instance of the process
item(name = "JmsClientId", value = "{{PROCESS_NAME}}")
// or, with several instances, a per-instance value from an environment variable
// item(name = "JmsClientId", value = "{{PROCESS_NAME}}-{{POD_INDEX}}")
}
}

{{PROCESS_NAME}} and {{HOST_NAME}} take precedence over system definition items with the same name, and system definition items take precedence over environment variables. Environment variables here are the process's ordinary environment, referenced by their own name: {{POD_INDEX}} reads the POD_INDEX variable. A placeholder with no value resolves to an empty string.

warning

The client ID must be unique for each running instance of a process. The broker rejects a second connection that uses a client ID already in use.

If you change JmsClientId on an existing deployment, the subscriptions created under the old client ID are not removed automatically; delete them on the broker.

High availability​

Prerequisites​

The quickest way to set up High Availability with ArtemisMQ is:

This method is tested and supported by Genesis. There are many other ways of implementing High Availability, but if you implement a different solution, it is vital that you test it thoroughly.

How it works​

The diagram below represents using a two-node cluster to show how the Genesis processes behave in this scenario.

  1. All processes connect to the primary broker:

  1. If there is a failure on the primary broker, the back-up turn primary and all clients automatically re-establish a connection to it:

info

During the failover period, the processes will be reported as DOWN.

Troubleshooting​

Process reports DOWN​

Scenario: The mon command displays the following message for one or more Genesis processes: UpdateQueue: Update queue is not connected.

There are two possible causes for this:

  • The process could not connect in the first place.
  • The connection to the message broker has been lost.
caution

At initialisation, processes are terminated automatically after the retry attempts are exhausted. However, if the connection is lost after the initialisation occurs, the processes are not shut down automatically; manual intervention is required from application support.

Resolution: Ensure that the message broker is online and accepting connections. Make sure that the configuration in the genesis-system-definition.kts has the correct values.

Process no longer exists but there are obsolete queues in the message broker​

Scenario: You have set up a durable consumer, but this process no longer exists in your application; you can see Artemis Console queues with messages that are never going to be consumed.

Resolution: Remove the queue from the Artemis MQ management console or CLI.