<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan McCauley on Medium]]></title>
        <description><![CDATA[Stories by Ryan McCauley on Medium]]></description>
        <link>https://medium.com/@ryan.mccauley_15203?source=rss-61f22c0e45f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x5of1I8R92JkwGiM3chgyw.jpeg</url>
            <title>Stories by Ryan McCauley on Medium</title>
            <link>https://medium.com/@ryan.mccauley_15203?source=rss-61f22c0e45f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:26:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryan.mccauley_15203/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Aeron Archive in Practice: Recording and Replaying Streams in Java]]></title>
            <link>https://medium.com/version-1/aeron-archive-in-practice-recording-and-replaying-streams-in-java-ed798434645f?source=rss-61f22c0e45f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed798434645f</guid>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[archive]]></category>
            <category><![CDATA[aeron]]></category>
            <dc:creator><![CDATA[Ryan McCauley]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 11:25:17 GMT</pubDate>
            <atom:updated>2026-02-02T11:25:17.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpiHPB_JgX7U-aij" /><figcaption>Photo by <a href="https://unsplash.com/@robinpierre?utm_source=medium&amp;utm_medium=referral">Robin Pierre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Aeron Archive</strong> is one of the most powerful components in the Aeron ecosystem. It allows you to record message streams and replay them later, enabling features such as durable messaging, time-based replays, and recovery for late-joining subscribers.</p><p>This article assumes you are already familiar with the basics of Aeron, including configuring the Media Driver and setting up publications and subscriptions. If you’d like a refresher, you can start with the previous article: <a href="https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4">https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4</a></p><p>We’ll begin by exploring the core components of Aeron Archive, examine relevant code from the demo project, and then get hands-on by running the demo to see how recording and replay work in practice.</p><blockquote><a href="https://www.version1.com/data-strategy-platforms-and-governance/">Data strategy, platforms and governance — Version 1</a></blockquote><h3>Aeron Archive Components</h3><p>The <strong>Aeron Archive</strong> is split into two main components: the <strong>Archive service</strong> and the <strong>Archive client</strong>.</p><p>For clarity, this article uses the term <strong>Archive service</strong> to distinguish it from the client. In Aeron’s own terminology, this component is simply referred to as the <strong>Aeron Archive</strong>.</p><p>The Archive service is responsible for persisting stream data, executing replays, and emitting events related to recording and replay progress. Like other Aeron components, it connects to a Media Driver.</p><p>The Archive does not intercept traffic inside the Media Driver. Instead, it records streams by subscribing to them in the same way as any other Aeron subscriber. From the Media Driver’s perspective, the Archive behaves just like a normal subscriber, consuming data from a channel and stream and writing it to persistent storage.</p><p>The Archive service itself is concerned with persisting stream data, while all interaction — such as starting and stopping recordings or initiating replays — is performed via the Archive client over a separate control channel.</p><p>The <strong>Archive client</strong> is responsible for issuing control requests to the Archive service, such as starting and stopping recordings and requesting replays.</p><p>In addition to sending requests, the Archive client listens for events emitted by the Archive service. These include notifications when recordings start or stop, along with metadata such as recording identifiers and the current recorded position.</p><p>The client sends requests to the Archive service to replay a recording and specify the channel and stream on which the replay should be published. While initiating a replay is done via the client, the replay itself is delivered as a normal Aeron publication from the Archive service to a subscription provided by the client. Replays are therefore indistinguishable from live publications from the perspective of the subscriber.</p><p>Now that we’ve covered the two main components of the <strong>Aeron Archive</strong>, we’ll move on to how to configure the Archive service and client.</p><h3>Archive Configuration</h3><p>One of the biggest hurdles when working with Aeron Archive is understanding how to configure both the <strong>Archive service</strong> and the <strong>Archive client</strong>. Compared to regular publications and subscriptions, there are additional channels and setup steps required.</p><p>In this section, we’ll walk through the configuration of both components. Later, in the code walkthrough, we’ll look at how these configurations are applied in practice.</p><h4>Archive Service Configuration</h4><p>The Archive service configuration introduces several additional channels beyond those used for regular publications and subscriptions. At a high level, the configuration breaks down as follows:</p><p><strong>control channel</strong> — Consists of a channel and stream ID. The Archive service opens a subscription on this channel and polls for requests from the Archive client. Archive clients must be configured to send control requests to this channel.</p><p><strong>recording events channel — </strong>Used by the Archive service to publish recording-related events to clients, such as when a recording starts or stops, along with associated metadata.</p><p><strong>replication channel — </strong>Used by the Archive for replicating recordings between archive instances. This is primarily used for archive-to-archive replication and is not required for basic recording and replay scenarios.</p><h4>Archive Client Configuration</h4><p>The Archive client introduces several additional configuration options in order to communicate with the Archive service.</p><p><strong>control request channel — </strong>Used by the client to send control requests to the Archive service, such as starting or stopping recordings and initiating replays.</p><p><strong>recording events channel — </strong>The channel on which the client receives recording-related events from the Archive service. This must match the Archive service’s configured recordingEventsChannel.</p><p><strong>control response channel — </strong>Used by the Archive service to send responses to control requests issued by the client. The client subscribes to this channel to receive control responses and status information.</p><h3>Code Walkthrough</h3><p>Two additional modules have been added to the demo to support archiving:</p><ul><li><strong>archive</strong> — runs the Archive service, which persists messages and receives control requests from the Archive client</li><li><strong>archive-client</strong> — runs the Archive client, which interacts with the Archive service to request recordings and initiate replays</li></ul><p>As with the previous demo, Aeron-specific logic is isolated within the aeron packages. Code outside these packages is primarily responsible for wiring and starting the services and does not require any Aeron-specific knowledge.</p><p>We’ll begin by looking at the Archive service.</p><h4>archive</h4><p>There is only one class of interest containing the aeron archive logic:</p><p>io.ryanjames.aeron.AeronArchive</p><pre>public synchronized void startArchive(String mediaDriverPath, String controlChannel, String recordingEventsChannel) {<br>    Archive.Context aeronContext = new Archive.Context()<br>            .aeronDirectoryName(mediaDriverPath)<br>            .controlChannel(controlChannel)<br>            .recordingEventsChannel(recordingEventsChannel)<br>            .replicationChannel(&quot;aeron:udp?endpoint=localhost:0&quot;)<br>            .recordingEventsEnabled(true);<br>...</pre><p><strong>Explanation:<br></strong>Here we see a familiar pattern: configuring a context, this time using Archive.Context.</p><p>Under the hood, the Archive service connects to the Media Driver and creates subscriptions based on this configuration. As a result, the first required setting is the aeronDirectoryName, which points the Archive at the local Media Driver instance.</p><p>Next are the channels discussed earlier. Enabling recordingEventsEnabled allows the Archive service to emit recording-related events—such as when a recording starts or stops—on the configured recordingEventsChannel. In this demo, the recordingEventsChannel uses an MDC channel, allowing Archive clients to dynamically subscribe and receive events. This also means multiple Archive clients can listen for recording events concurrently.</p><p>The remaining configuration is the replicationChannel. In this case, it is safe to hardcode the channel and use port 0, allowing Aeron to select an available port. This channel is only required on the Archive service side and is used for archive-to-archive replication; the replication destination does not need prior knowledge of this channel.</p><p>Once the context has been configured, the remaining work is simply to launch the Archive service.</p><pre>try {<br>    aeronArchive = Archive.launch(aeronContext);<br>    LOGGER.info(&quot;Aeron Archive started (aeronDir={}, controlChannel={}, recordingEventsChannel={})&quot;, mediaDriverPath,<br>            controlChannel, recordingEventsChannel);<br>} catch (Exception e) {<br>    LOGGER.error(&quot;Failed to launch Aeron Archive&quot;, e);<br>    throw new IllegalStateException(&quot;Unable to start Aeron Archive&quot;, e);<br>}</pre><p>Once the context has been configured, launching the Archive service is straightforward. Calling Archive.launch(...) starts the Archive and connects it to the configured Media Driver.</p><p>At this point, the Archive service is running and ready to receive control requests from Archive clients via the configured control channel.</p><h4>archive-client</h4><p>Next we will look at the archive client code. Again the interesting aeron code is isolated in a single class</p><p>io.ryanjames.aeron.AeronClient</p><pre>public synchronized void connect(String mediaDriverPath, String controlRequestChannel,<br>                                 String recordingEventsChannel,<br>                                 String controlResponseChannel) {<br>    AeronArchive.Context aeronContext = new AeronArchive.Context()<br>            .aeronDirectoryName(mediaDriverPath)<br>            .controlRequestChannel(controlRequestChannel)<br>            .recordingEventsChannel(recordingEventsChannel)<br>            .controlResponseChannel(controlResponseChannel)<br>            .recordingSignalConsumer(this);</pre><p><strong>Explanation:</strong><br>Following a similar pattern to the Archive service, the Archive client is configured using a context. Like other Aeron components, it requires access to the Media Driver, so the first step is to point it at the appropriate Aeron directory.</p><p>The controlRequestChannel is then configured to match the Archive service’s controlChannel. This allows the client to publish control requests—such as starting or stopping recordings and initiating replays—to the Archive service.</p><p>The recordingEventsChannel is used to receive recording-related events emitted by the Archive service. In addition to configuring the channel, we also supply a recordingSignalConsumer, which allows the client to handle these events programmatically. We’ll look at this in more detail shortly.</p><p>Finally, the controlResponseChannel is configured. The Archive client opens a subscription on this channel to receive responses to control requests issued to the Archive service.</p><p>Next, we’ll look at how the Archive client receives recording events via the RecordingSignalConsumer.</p><pre>public class AeronClient implements AutoCloseable, RecordingSignalConsumer<br>...<br>    public void poll() {<br>        if (isRunning()) {<br>            archiveClient.pollForRecordingSignals();<br>        }<br>    }<br>...<br>    @Override<br>    public void onSignal(long controlSessionId, long correlationId, long recordingId, long subscriptionId, long position, RecordingSignal signal) {<br>        LOGGER.info(&quot;Received recording signal: controlSessionId={}, correlationId={}, recordingId={}, subscriptionId={}, position={}, signal={}&quot;,<br>                controlSessionId, correlationId, recordingId, subscriptionId, position, signal);<br>    }</pre><p>The AeronClient implements the RecordingSignalConsumer interface, which allows it to receive recording-related signals emitted by the Archive service. These signals include notifications such as when a recording starts or stops, along with associated metadata like recording identifiers and positions.</p><p>In this example, the onSignal callback simply logs the received information. In a real production system, however, these signals can be used for more meaningful purposes—for example, tracking available recordings, updating application state, or persisting metadata for later replay.</p><p>Implementing the RecordingSignalConsumer alone is not sufficient. As with all Aeron interactions, recording signals are delivered via polling. This gives the application explicit control over when and how events are processed.</p><p>To handle this, the client polls for recording signals on a background thread:</p><pre>executor.submit(() -&gt; {<br>    while (!Thread.currentThread().isInterrupted()) {<br>        int work = archiveClient.pollForRecordingSignals();<br>        idle.idle(work);<br>    }<br>});</pre><p>Starting a recording is straightforward:</p><pre>public long startRecording(String channel, int streamId) {<br>    long subscriptionId = archiveClient.startRecording(channel, streamId, SourceLocation.LOCAL);<br>    LOGGER.info(&quot;Started recording subscriptionId={} channel=&#39;{}&#39; streamId={}&quot;, subscriptionId, channel, streamId);<br>    return subscriptionId;<br>}</pre><p>Calling startRecording sends a control request to the Archive service via the control request channel, instructing it to begin recording the specified channel and stream.</p><p>The Archive service responds to this request over the client’s control response channel, allowing the call to complete. Separately, the Archive service emits recording signals — such as a recording start notification — on the recording events channel. These signals are delivered asynchronously and can be processed by polling via the RecordingSignalConsumer.</p><p>Once a stream has been recorded, the next step is to replay it:</p><pre>public void replay(long recordingId, String channel, int streamId) {<br>    long replaySessionId = archiveClient.startReplay(recordingId, channel, streamId, new ReplayParams());<br>    LOGGER.info(&quot;Started replay of recordingId={} to channel=&#39;{}&#39; streamId={} and replaySessionId: {}&quot;, recordingId, channel, streamId,<br>            replaySessionId);<br>}</pre><p>It’s important to note that the channel and streamId provided here are <strong>not</strong> the original channel and stream that were recorded. Instead, they define where the replayed data will be published.</p><p>The recordingId uniquely identifies the recorded stream and tells the Archive service what data should be replayed. The Archive service publishes the replay as a normal Aeron publication on the specified channel and stream, and the Archive client creates a subscription to receive the replayed data.</p><h3>Demo Walkthrough</h3><p>Now that we have a good understanding of the <strong>Aeron Archive</strong> we will jump into a short demo to see it in action. To begin clone the project <a href="https://github.com/k4pran/Aeron-Demo">https://github.com/k4pran/Aeron-Demo</a>.</p><p>We first need to run the non-archive services as we will want to record a publication. Starting these next three services will be mostly a condensed form of the previous article, but for more detail on these components read the demo at <a href="https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4">https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4</a></p><p><strong>Starting the </strong>client-mediadriver</p><p>1. Run ./gradlew client-mediadriver:run <br>2. Check the logs</p><pre>17:18:54.002 [main] INFO  io.javalin.Javalin - Javalin started in 283ms \o/<br>17:18:54.002 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7000/<br>17:18:54.009 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025. Your Javalin version is 211 days old. Consider checking for a newer version.).<br>17:18:54.009 [main] INFO  io.ryanjames.MediaDriverService - Redoc docs served at http://localhost:7000/redoc<br>17:18:54.009 [main] INFO  io.ryanjames.MediaDriverService - Swagger UI served at http://localhost:7000/swagger</pre><p>3. Navigate to url <a href="http://localhost:7000/swagger">http://localhost:7000/swagger</a><br>4. Start the MediaDriver with the directory path <strong>../aeron</strong>. Aeron will then create a directory at the project level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdRgMsTy0kLisOUogd-FsQ.png" /><figcaption>Start the mediadriver with REST request at <a href="http://localhost:7000/mediadriver/start"><strong>http://localhost:7000/mediadriver/start</strong></a></figcaption></figure><p><strong>Preparing the order-entry-client</strong></p><p>1. Run ./gradlew order-entry-client:run <br>2. Check the logs</p><pre>17:19:31.063 [main] INFO  io.javalin.Javalin - Javalin started in 276ms \o/<br>17:19:31.063 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7001/<br>17:19:31.078 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025. Your Javalin version is 211 days old. Consider checking for a newer version.).<br>17:19:31.078 [main] INFO  io.ryanjames.OrderEntryService - Redoc docs served at http://localhost:7001/redoc<br>17:19:31.078 [main] INFO  io.ryanjames.OrderEntryService - Swagger UI served at http://localhost:7001/swagger</pre><p>3. Navigate to <a href="http://localhost:7001/swagger">http://localhost:7001/swagger</a><br>4. Connect to the MediaDriver using the same directory we started the MediaDriver with — <strong>../aeron</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kz0Ar-TFNd3goM9I-ztghQ.png" /><figcaption>Connect the client with REST request at <a href="http://localhost:7001/client/connect"><strong>http://localhost:7001/client/connect</strong></a></figcaption></figure><p>Create a UDP publication with the /client/addPublication endpoint with the following parameters:</p><ul><li>channel = aeron:udp?endpoint=localhost:40000</li><li>streamId = 10</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0Az6E0XIOdgA-sUYe0ghw.png" /><figcaption>Add publication with REST endpoint — <a href="http://localhost:7001/client/addPublication"><strong>http://localhost:7001/client/addPublication</strong></a></figcaption></figure><p><strong>Preparing the order-gateway-server</strong></p><p>Next we follow similar steps to initialize the order entry client. Remember we use an <strong>embedded MediaDriver </strong>for this service that will start automatically, that gives us one less step.</p><p>1. Run ./gradlew order-gateway-server:run <br>2. Check the logs</p><pre>17:22:29.054 [main] INFO  io.javalin.Javalin - Javalin started in 191ms \o/<br>17:22:29.057 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7002/<br>17:22:29.068 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025. Your Javalin version is 211 days old. Consider checking for a newer version.).<br>17:22:29.068 [main] INFO  io.ryanjames.OrderGatewayService - Redoc docs served at http://localhost:7002/redoc<br>17:22:29.068 [main] INFO  io.ryanjames.OrderGatewayService - Swagger UI served at http://localhost:7002/swagger</pre><p>3. Navigate to <a href="http://localhost:7002/swagger">http://localhost:7002/swagger</a><br>4. Create a subscription</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5mCBej4stp27fiQa4GpzA.png" /><figcaption>Create a subscription listening on the same channel and stream as the publication with REST endpoint <a href="http://localhost:7002/gateway/addSubscriber"><strong>http://localhost:7002/gateway/addSubscriber</strong></a></figcaption></figure><p>Now that we have the three original services running we can next prepare the two components involved in archiving</p><p><strong>Preparing the archive service</strong></p><p>1. Run ./gradlew archive:run <br>2. Check the logs</p><pre>17:24:24.000 [main] INFO  io.javalin.Javalin - Javalin started in 251ms \o/<br>17:24:24.003 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7003/<br>17:24:24.013 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025. Your Javalin version is 211 days old. Consider checking for a newer version.).<br>17:24:24.013 [main] INFO  io.ryanjames.ArchiveApplication - Redoc docs served at http://localhost:7003/redoc<br>17:24:24.013 [main] INFO  io.ryanjames.ArchiveApplication - Swagger UI served at http://localhost:7003/swagger</pre><p>3. Navigate to <a href="http://localhost:7003/swagger">http://localhost:7003/swagger</a><br>4. Start the archive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8D6BWwEUx_e8ymu9A5KAQ.png" /><figcaption>Start the archive with REST endpoint <a href="http://localhost:7003/archive/start"><strong>http://localhost:7003/archive/start</strong></a></figcaption></figure><p>The parameters we are using are:</p><ul><li><strong>aeron directory path — </strong>../aeron</li><li><strong>archive control channel — </strong>aeron:udp?endpoint=0.0.0.0:4400</li><li><strong>archive recording events channel — </strong>aeron:udp?control-mode=dynamic|control=localhost:4401</li></ul><p>The recording events channel can look a little daunting so let’s break it down.</p><p>This channel uses <strong>Aeron’s Multi-Destination Cast (MDC)</strong> in dynamic control mode. Rather than publishing to a single fixed endpoint, the Archive service publishes recording events to a logical channel, and interested clients dynamically register themselves as destinations.</p><p>The control=localhost:4401 endpoint acts as the MDC control address. Archive clients send control messages to this address to join the channel, after which the Archive service begins sending recording events to them. This allows multiple Archive clients to subscribe to recording events without requiring the Archive service to be reconfigured for each client and the archive doesn’t need to know the client recording channels in order to publish to them.</p><p><strong>Preparing the archive client</strong></p><p>1. Run ./gradlew archive-client:run <br>2. Check the logs</p><pre>17:32:08.714 [main] INFO  io.javalin.Javalin - Javalin started in 258ms \o/<br>17:32:08.717 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7004/<br>17:32:08.731 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025. Your Javalin version is 211 days old. Consider checking for a newer version.).<br>17:32:08.731 [main] INFO  i.ryanjames.ArchiveClientApplication - Redoc docs served at http://localhost:7004/redoc<br>17:32:08.731 [main] INFO  i.ryanjames.ArchiveClientApplication - Swagger UI served at http://localhost:7004/swagger</pre><p>3. Navigate to <a href="http://localhost:7004/swagger">http://localhost:7004/swagger</a><br>4. Start the archive client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3px3hDjGj2NyALvUvBcCvw.png" /><figcaption>Start the archive client with REST endpoint <a href="http://localhost:7004/archive/client/connect"><strong>http://localhost:7004/archive/client/connect</strong></a></figcaption></figure><p>The parameters we are using here are:</p><ul><li><strong>aeron directory path — </strong>../aeron</li><li><strong>control request channel — </strong>aeron:udp?endpoint=localhost:4400</li><li><strong>recording events channel — </strong>aeron:udp?control-mode=dynamic|control=localhost:4401</li><li><strong>control response channel</strong> — aeron:udp?endpoint=localhost:0</li></ul><p><strong>Recording and Replaying</strong></p><p>Now that we have all our pieces set up, our next steps are:</p><ol><li>Start a recording on the publication we started earlier</li><li>Publish a few messages</li><li>Replay the messages to a new channel</li></ol><p>First we want to begin recording the publication channel.</p><p><strong>Start a recording</strong></p><ol><li>Navigate to the archive-client at <a href="http://localhost:7004/swagger">http://localhost:7004/swagger</a></li><li>Start a recording using the publication’s channel</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzGyR3B3R9zfW-mYSsuvtA.png" /><figcaption>Start a recording with REST endpoint <a href="http://localhost:7004/archive/client/record"><strong>http://localhost:7004/archive/client/record</strong></a></figcaption></figure><p>3. Check the archive-client logs</p><pre>17:41:04.334 [pool-1-thread-1] INFO  io.ryanjames.aeron.AeronClient - Received recording signal: controlSessionId=1707056815, correlationId=34, recordingId=11, subscriptionId=35, position=0, signal=START</pre><p><strong>Publish a few messages</strong></p><ol><li>Navigate to the order-entry-client at <a href="http://localhost:7001/swagger">http://localhost:7001/swagger</a></li><li>Publish a few messages, remember that we pass the registrationId which you can find in the order-entry-client logs.</li></ol><pre>17:21:58.091 [JettyServerThreadPool-20] INFO  io.ryanjames.aeron.AeronClient - Publication &#39;2&#39; created with channel &#39;aeron:udp?endpoint=localhost:40000&#39;, streamId &#39;10&#39;</pre><p>In my case my registrationId is <strong>2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnP5Zz5d-C7gdMBr9HEPPQ.png" /><figcaption>Publish message with REST endpoint <a href="http://localhost:7001/client/publishMessage"><strong>http://localhost:7001/client/publishMessage</strong></a></figcaption></figure><p>3. As a sanity check we can validate our messages have been received by the subscription we set up earlier in the order-gateway-server logs</p><pre>17:49:03.584 [aeron-subscriber-aeron:udp?endpoint=localhost:40000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 1<br>17:50:31.517 [aeron-subscriber-aeron:udp?endpoint=localhost:40000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 2<br>17:50:34.302 [aeron-subscriber-aeron:udp?endpoint=localhost:40000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 3</pre><p><strong>Create a subscription for the replayer</strong></p><ol><li>Create another subscriber in the order-gateway-service same as we did before, but this time we are creating a subscription that will receive the replayed data</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpTB9CHp2W9tIYnUzsv2Nw.png" /><figcaption>Create a subscription listening on the same channel and stream as we will replay to with REST endpoint <a href="http://localhost:7002/gateway/addSubscriber"><strong>http://localhost:7002/gateway/addSubscriber</strong></a></figcaption></figure><p><strong>Replay the stream</strong></p><ol><li>Navigate to the archive-client at <a href="http://localhost:7004/swagger">http://localhost:7004/swagger</a></li><li>Check the logs for the recordingId</li></ol><pre>17:41:04.334 [pool-1-thread-1] INFO  io.ryanjames.aeron.AeronClient - Received recording signal: controlSessionId=1707056815, correlationId=34, recordingId=11, subscriptionId=35, position=0, signal=START</pre><p>In my case the recordingId is <strong>11</strong></p><p>3. Start the replay</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZiCMKCi2uXv4f_zEAV7-g.png" /><figcaption>Replay a recording with REST endpoint <a href="http://localhost:7004/archive/client/replay"><strong>http://localhost:7004/archive/client/replay</strong></a></figcaption></figure><p>4. Check logs for the order-gateway-server to check the stream was replayed</p><pre>17:55:30.932 [JettyServerThreadPool-25] INFO  i.r.aeron.AeronSubscriberService - Subscriber created with channel &#39;aeron:udp?endpoint=localhost:5000&#39;, streamId &#39;10&#39; and registrationId &#39;4&#39;<br>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 1<br>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 2<br>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 3</pre><p>Notice too that it will be replayed in the order it was sent, we can replay again and it again will replay the recording from the beginning, or even replay to another subscriber</p><pre>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 1<br>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 2<br>17:55:59.010 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 3<br>18:01:53.939 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 1<br>18:01:53.939 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 2<br>18:01:53.939 [aeron-subscriber-aeron:udp?endpoint=localhost:5000-10] INFO  i.r.aeron.AeronSubscriberService - received: Test message 3</pre><h3>What’s Next?</h3><p>This article provides a practical introduction to the Aeron Archive and demonstrates the core record-and-replay workflow. However, it only scratches the surface of what the Archive is capable of.</p><p>Beyond the basics, the Aeron Archive supports a number of more advanced patterns and features, including:</p><ul><li><strong>Multiple concurrent clients</strong><br>Multiple Archive clients can interact with the same Archive service, allowing different applications or tools to start recordings, monitor recording progress, and initiate replays independently.</li><li><strong>Archive-to-archive replication</strong><br>Recordings can be replicated between Archive instances, enabling redundancy, migration, or disaster-recovery scenarios or syncing multiple hosts.</li><li><strong>Partial and position-based replays</strong><br>Replays are not limited to starting from the beginning of a recording. The Archive allows recordings to be replayed from specific positions, making it possible to resume processing and rebuild state and replay only what was missed.</li><li><strong>Remote replays</strong><br>Replays can be published to channels on remote hosts, allowing recorded data to be streamed across machines or environments just like regular aeron streams.</li></ul><p>These capabilities make the Aeron Archive a powerful building block for systems that require low-latency messaging while still supporting durability, recovery, and operational flexibility. If you’re interested in going beyond the basics, each of these areas is well worth exploring further.</p><h3>Conclusion</h3><p>In this article, we explored the Aeron Archive and how it extends Aeron’s low-latency messaging model with durable recording and replay capabilities. By walking through the core components, configuration, and a hands-on demo, we’ve seen how recordings and replays fit naturally into existing Aeron applications. While this only covers the fundamentals, it should provide a solid foundation for using the Archive in practice and for exploring its more advanced features going forward.</p><h3>About the author</h3><p>Ryan McCauley is a Senior Software Engineer here at <a href="https://www.version1.com/">Version 1</a>.</p><h3>Resources</h3><p><strong>Start here</strong></p><ul><li><a href="https://aeron.io/">https://aeron.io/ </a>— official site</li><li><a href="https://aeron.io/docs/aeron/overview/">https://aeron.io/docs/aeron/overview/ </a>— Aeron overview</li><li><a href="https://aeron.io/docs/aeron-archive/overview/">https://aeron.io/docs/aeron-archive/overview/</a> — Aeron archive overview</li></ul><p><strong>Previous article</strong></p><ul><li><a href="https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4">https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4</a></li></ul><p><strong>Demo Project</strong></p><ul><li><a href="https://github.com/k4pran/Aeron-Demo">https://github.com/k4pran/Aeron-Demo</a> — <strong>GitHub Demo Project</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed798434645f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/aeron-archive-in-practice-recording-and-replaying-streams-in-java-ed798434645f">Aeron Archive in Practice: Recording and Replaying Streams in Java</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Low-Latency Messaging with Aeron in Java]]></title>
            <link>https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4?source=rss-61f22c0e45f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfe1d841d5d4</guid>
            <category><![CDATA[aeron]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[udp]]></category>
            <category><![CDATA[low-latency]]></category>
            <dc:creator><![CDATA[Ryan McCauley]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 10:45:33 GMT</pubDate>
            <atom:updated>2025-09-22T10:45:33.667Z</atom:updated>
            <content:encoded><![CDATA[<p>Aeron is a <strong>high-performance, low-latency messaging system</strong> designed for applications where speed and reliability are critical. It’s widely used in areas like <strong>financial trading</strong>, where every microsecond counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yy8DqCibAqzti4t3" /><figcaption>Photo by <a href="https://unsplash.com/@coinhako_official?utm_source=medium&amp;utm_medium=referral">Coinhako</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of Aeron’s standout features is that it builds on top of <strong>UDP</strong>. Normally, UDP is fast but unreliable — packets can be dropped, duplicated, or arrive out of order. Aeron extends UDP with its own reliability layer: messages are delivered <strong>reliably, in order, and with minimal overhead</strong>, avoiding the extra baggage of TCP.</p><p>Unlike systems such as Kafka or Solace that rely on a central broker, Aeron is <strong>peer-to-peer</strong>. Applications send and receive messages directly over streams, without an intermediary in the middle. This makes Aeron both lean and predictable in terms of latency.</p><p>In this article, we’ll start with a <strong>high-level overview of Aeron</strong>, and then dive into a simple demo: a client that sends orders and a gateway that receives them. The aim isn’t to cover every feature in depth, but rather to give you a <strong>flavour of Aeron</strong> and show how easy it is to get started.</p><p>We’ll keep things simple — no multicast, no multi-destination-cast (MDC), and none of the advanced Aeron tooling (impressive as it is). Think of this as a <strong>gentle first step</strong> into Aeron, enough to get a working example running and spark your curiosity.</p><p><strong>Note:</strong> This is a <em>gentle</em> intro, not a short one. We’ll cover key Aeron fundamentals before getting hands-on. If you just want to see something working, skip to <strong>Installation &amp; Code Walkthrough</strong> and then <strong>A Simple Aeron Demo</strong> — but it’s worth understanding the basics first.</p><h3>The Core Building Blocks</h3><p>For our purposes, Aeron can be thought of in terms of <strong>two main components</strong>: the <strong>MediaDriver</strong> and the <strong>Client API</strong>. Let’s take a closer look at each.</p><h4>Aeron MediaDriver</h4><p>Let’s start with the <strong>MediaDriver</strong>. This was the first piece of Aeron that confused me — not because it’s difficult to use, but because it isn’t something you typically see in other messaging systems.</p><p>The diagram below shows the general flow of messages in Aeron. At first glance, the MediaDriver might look like a <strong>broker</strong>, similar to what you’d see in Kafka or Solace. But that’s not quite right. The MediaDriver is <strong>not a broker</strong> — there’s no central queue or store-and-forward model. In fact,<strong> </strong>each publication and subscription typically runs its own MediaDriver, rather than sharing a single broker process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBcQ7pwhrLVFvsArPM1t_A.png" /></figure><p>The MediaDriver is the component that <strong>sends and receives messages over the chosen media</strong> (UDP, IPC, etc.). It handles the transport mechanics, while your application code works with the Aeron API — managing publications, subscriptions, and streams. In other words, there’s a <strong>clean separation of concerns</strong>:</p><ul><li>Your app focuses on business logic.</li><li>The MediaDriver handles the details of moving bytes quickly and reliably.</li></ul><p>Another useful detail is that the MediaDriver can be run in <strong>different modes</strong>:</p><ul><li><strong>Embedded</strong> in your application (simplest to get started).</li><li>Or as a <strong>standalone process</strong> on the same machine (better isolation and stability).</li></ul><p>You can start embedded for ease of development, and later switch to a standalone driver if you need more robustness in production.</p><h4>Aeron Client API</h4><p>The <strong>Aeron Client API</strong> is where your application code actually interacts with Aeron. This is where you create <strong>publications</strong> (to send messages) and <strong>subscriptions</strong> (to receive messages). In other words, it’s the layer that lets your business logic talk to the transport.</p><p>The client doesn’t handle networking directly — instead, it connects to a <strong>MediaDriver</strong>, which does the heavy lifting of managing sockets, buffers, and flow control.</p><p><strong>In summary:</strong> Your application talks to the <strong>Client API</strong>, which manages <strong>Publications</strong> and <strong>Subscriptions</strong>. The <strong>MediaDriver</strong> handles sockets, buffers, and flow control. Messages travel over the chosen <strong>transport</strong> (UDP, multicast, or IPC). Together, these form Aeron’s foundation.</p><h3>Essential Aeron Concepts</h3><p>Now that we’ve covered the main components of Aeron, let’s look at a few concepts that are <strong>useful to understand before we dive into code</strong>.</p><h4>Channels / Streams / Sessions</h4><p>Aeron is <strong>peer-to-peer</strong>: for a publication and a subscription to communicate, they must both be using the <strong>same channel</strong> and <strong>stream ID</strong>.</p><ul><li>A <strong>channel</strong> defines the transport and endpoint — for example, a host and port over UDP. But it’s more abstract than that, because Aeron also supports other transports such as <strong>IPC</strong> (inter-process communication), where the “channel” is just shared memory within the same machine.</li><li>A <strong>stream</strong> is simply an integer identifier. A single channel can carry many different streams, allowing multiple logical message flows over the same transport.</li></ul><p>Together, <strong>channels and streams</strong> uniquely identify the flow of messages between a publication and a subscription.</p><p>There can also be <strong>multiple publications </strong>on the same channel and stream. In these cases, <strong>sessions</strong> become important: each publication is assigned a unique sessionId, which allows subscriptions to distinguish between different senders on the same logical stream.</p><p>Aeron channels are formatted as a URI String. Here are a couple of examples:</p><ul><li><strong>aeron:ipc</strong> — simplest form; an IPC protocol, that’s all the information IPC needs.</li><li><strong>aeron:udp?endpoint=localhost:7010</strong> — UDP needs an <strong>endpoint</strong> (host:port).</li></ul><p>For the full URI syntax (multicast, MDC, control endpoints), see the <a href="https://github.com/aeron-io/aeron/wiki/Channel-Configuration">Channel Configuration wiki</a></p><h4>Publications and Subscriptions</h4><p>These are probably the most intuitive concepts, since they appear in almost every messaging system. In Aeron, a <strong>publication</strong> sends messages as a stream across a channel, and a <strong>subscription</strong> receives those messages.</p><p>The beauty of Aeron is that <strong>publications and subscriptions work the same way regardless of the underlying protocol</strong> (UDP or IPC). This gives us a consistent API no matter which transport we choose.</p><p>Aeron also supports <strong>multi-destination cast (MDC)</strong>, which allows a single publication to be delivered to multiple destinations at once — useful for scenarios like fan-out messaging and in environments where multicast is not supported.</p><p>One thing to note is that publications and subscriptions are <strong>asynchronous</strong>. A publication writes messages into a log buffer, and subscriptions explicitly poll to read them. This design is key to Aeron’s performance.</p><h4>Log Buffers</h4><p>In Aeron, messages are stored in <strong>log buffers</strong>. These are memory-mapped files that the MediaDriver writes to and reads from.</p><p>As more messages are sent, multiple log buffers are created. Once a buffer reaches its configured size limit, Aeron <strong>rolls over to a new file</strong>. This design helps avoid problems (like page faults) that can occur if you try to use one very large file for everything.</p><p>Because the messages are persisted in files, it also becomes easier to <strong>archive, move, or replay</strong> them later.</p><p>For our demo, it’s enough to know that log buffers are <strong>where messages live</strong> while in flight. If you want the details, see the Aeron docs on <a href="https://aeron.io/docs/aeron/log-buffers-images/"><strong>Log Buffers &amp; Images</strong></a>.</p><h4>Polling</h4><p>One thing to note: Aeron uses a <strong>polling model</strong>. A Publication writes into a log buffer, and a Subscription explicitly calls poll() to read messages. This design is a big part of Aeron’s performance.</p><p>For example, when a subscription listens on a channel, you don’t just register a handler and wait for messages to arrive automatically. Instead, you explicitly <strong>poll</strong> for messages. This gives control to the receiving component over <em>when</em> and <em>how much</em> data it processes.</p><p>It’s worth keeping this in mind: if you’re not receiving something you expect, the first question to ask yourself is — <strong>am I polling?</strong></p><h3>Installation and Code Walkthrough</h3><p>Now that we’ve got a better understanding of Aeron, let’s clone the repo and skim the <strong>Aeron-specific code</strong> we’ll use in the demo.</p><h4>Requirements</h4><p>To follow along with this demo, you’ll need a few basics. I’m using IntelliJ with the Gradle wrapper, but you can use any IDE you like. At a minimum, make sure you have:</p><ul><li><strong>Java 17</strong> — Aeron requires a modern JVM, and Java 17 is the current LTS release.</li><li><strong>Gradle</strong> — to build and run the demo project (you can use the included Gradle wrapper).</li><li><strong>Git &amp; an internet connection</strong> — to clone the project repository.</li><li><strong>A web browser</strong> — the demo includes a Swagger UI, which we’ll use to send and receive orders.</li></ul><h4>Cloning and Project Structure</h4><p>You can clone the project with</p><pre>git clone https://github.com/k4pran/Aeron-Demo.git</pre><p>The project uses <strong>Gradle</strong> for builds, and <strong>Javalin</strong> to run the services with a <strong>Swagger UI</strong> for interacting with them. It’s divided into three modules, and in each module you’ll find an io.ryanjames.aeron package that contains the Aeron code. This separation is intentional: it keeps the Aeron logic isolated so you can focus entirely on the Aeron parts without needing to worry about Javalin, Swagger, or any other supporting code.</p><h4>Code walkthrough</h4><p>The project is split into three modules:</p><ul><li>client-mediadriver – runs the MediaDriver for the client.</li><li>order-entry-client – publishes orders to the gateway.</li><li>order-gateway-server – subscribes and listens for incoming orders.</li></ul><p>We will go through each of these only focusing on the Aeron code. All Aeron code we are interested in will be in the package io.ryanjames.aeron</p><p><strong>client-mediadriver</strong></p><p>io.ryanjames.aeron.MediaDriverRunner</p><pre><br>public void start(String mediaDriverDir) {<br>    if (mediaDriver != null) {<br>        throw new IllegalStateException(&quot;MediaDriver already running&quot;);<br>    }<br>    if (mediaDriverDir == null || mediaDriverDir.isBlank()) {<br>        throw new IllegalArgumentException(&quot;mediaDriverDir is required&quot;);<br>    }<br>    try {<br>        MediaDriver.Context ctx = new MediaDriver.Context()<br>                .aeronDirectoryName(mediaDriverDir)<br>                .driverTimeoutMs(DRIVER_TIMEOUT_MS);<br><br>        mediaDriver = MediaDriver.launch(ctx);<br>        LOGGER.info(&quot;MediaDriver launched.&quot;);<br>    } catch (Exception e) {<br>        throw new RuntimeException(&quot;Failed to start MediaDriver&quot;, e);<br>    }<br>}</pre><p><strong>Explanation:</strong><br>Here we create and launch the <strong>MediaDriver</strong>, the engine that owns Aeron’s transport. The MediaDriver.Context sets:</p><ul><li>the <strong>Aeron directory</strong> (aeronDirectoryName) — where Aeron writes its control and log-buffer files (e.g., cnc.dat, publications, images). Your client/server must point to this same directory to connect to this driver;</li><li>the <strong>driver timeout</strong> (driverTimeoutMs) — the liveness heartbeat window between the client and driver.</li></ul><p>Because we’re running the MediaDriver in its <strong>own JVM</strong> (standalone), it holds the sockets and memory-mapped files, while the client connects to it via shared memory using that directory.</p><p><strong>order-entry-client</strong></p><p>io.ryanjames.aeron.AeronClient</p><pre>public void connect(String mediaDriverPath) {<br>    if (aeron != null) {<br>        throw new IllegalStateException(&quot;Already connected to MediaDriver&quot;);<br>    }<br><br>    if (mediaDriverPath == null || mediaDriverPath.isBlank()) {<br>        throw new IllegalArgumentException(&quot;mediaDriverPath must be specified&quot;);<br>    }<br>    Aeron.Context ctx = new Aeron.Context()<br>            .aeronDirectoryName(mediaDriverPath)<br>            .driverTimeoutMs(CommonContext.DEFAULT_DRIVER_TIMEOUT_MS)<br>            .errorHandler(throwable -&gt; LOGGER.error(&quot;Unhandled aeron error&quot;, throwable));<br><br>    aeron = Aeron.connect(ctx);<br>    LOGGER.info(&quot;Connected to aeron MediaDriver at &#39;{}&#39;&quot;, mediaDriverPath);<br>}</pre><p><strong>Explanation:</strong></p><ul><li><strong>aeronDirectoryName(mediaDriverPath)</strong><br>Every MediaDriver creates a working directory where it exposes its buffers. Your client must connect to that exact directory.</li><li><strong>driverTimeoutMs</strong><br>Ensures the client times out if the MediaDriver isn’t alive. Default is usually fine, but you can tune it.</li><li><strong>errorHandler(...)</strong><br>Aeron runs background threads; uncaught exceptions go here. For production, you’ll probably want to escalate or retry instead of just logging.</li></ul><pre>public long addPublication(String channel, int streamId) {<br>    if (aeron == null) {<br>        throw new IllegalStateException(&quot;Aeron not initialized. Hint: ensure connect() has been called first&quot;);<br>    }<br>    ConcurrentPublication concurrentPublication = aeron.addPublication(channel, streamId);<br>    long registrationId = concurrentPublication.registrationId();<br>    publications.put(registrationId, concurrentPublication);<br><br>    LOGGER.info(&quot;Publication &#39;{}&#39; created with channel &#39;{}&#39;, streamId &#39;{}&#39;&quot;,<br>            registrationId, channel, streamId);<br>    return registrationId;<br>}</pre><p><strong>Explanation:</strong></p><p>This method creates a <strong>Publication</strong>, which is Aeron’s way of sending messages into the MediaDriver so they can be delivered to subscriptions.</p><ul><li>We first ensure connect() has been called. Aeron must be connected to a MediaDriver before publications or subscriptions can be created.</li><li><strong>aeron.addPublication(channel, streamId)</strong><br> Creates a publication on a specific channel and streamId. Together, these identify <em>where messages will be sent</em>.</li><li>channel is a URI formatted to <a href="https://github.com/aeron-io/aeron/wiki/Channel-Configuration">Aeron specification</a> (e.g. &quot;aeron:udp?endpoint=localhost:40123&quot;) describing the transport.</li><li>streamId is just an integer that lets you multiplex different message streams over the same channel.</li><li><strong>registrationId</strong><br>Aeron entities (publication, subscription etc.) has a unique registrationId. This acts like a handle so we can look up the publication later in our own publications map.</li><li><strong>State tracking<br></strong>We save the publication in a local Map&lt;Long, ConcurrentPublication&gt; so we can fetch it later when we need to send messages and remove publications.</li></ul><pre>public void sendMessage(long registrationId, String message) {<br>    ensureConnected();<br><br>    if (message == null) {<br>        message = &quot;&quot;;<br>    }<br><br>    ConcurrentPublication publication = publications.get(registrationId);<br>    if (publication == null) {<br>        throw new IllegalArgumentException(&quot;Publication not found: &quot; + registrationId);<br>    }<br><br>    int encodedLen = reusableSendBuffer.putStringAscii(0, message);<br>    long result = publication.offer(reusableSendBuffer, 0, encodedLen);<br><br>    if (result &lt; 0) {<br>        LOGGER.warn(&quot;Publication failed to offer with result &#39;{}&#39; for registration id &#39;{}&#39;: {}&quot;<br>                , result, registrationId, message);<br>        return;<br>    }<br>    LOGGER.info(&quot;Message sent from {}: {}&quot;, registrationId, message);<br>}</pre><p>This method <strong>publishes a message into Aeron’s MediaDriver</strong> using a previously created Publication.</p><ul><li>ensureConnected() ensures we’re attached to a MediaDriver. No publications work without it.</li><li>The registrationId from addPublication() is used to look up the right ConcurrentPublication. If it doesn’t exist, we throw.</li><li>reusableSendBuffer.putStringAscii(0, message) writes the string into a pre-allocated buffer.</li><li>The return value (encodedLen) tells us how many bytes were written.</li><li>publication.offer(buffer, offset, length) tries to enqueue the message for sending.</li><li>offer(...) returns a long: <strong>≥ 0</strong> means success; <strong>&lt; 0</strong> indicates back pressure / not connected / admin action / closed. The failure codes can be reviewed in Aeron’s <a href="https://javadoc.io/doc/io.aeron/aeron-all/latest/constant-values.html#io.aeron.Publication.ADMIN_ACTION">docs</a></li></ul><p><strong>order-gateway-server</strong></p><p>io.ryanjames.aeron.MediaDriverRunner</p><pre>public void startMediaDriver() {<br>    if (mediaDriver != null) {<br>        throw new IllegalStateException(&quot;MediaDriver already running&quot;);<br>    }<br>    mediaDriver = MediaDriver.launchEmbedded();<br>    LOGGER.info(&quot;MediaDriver launched at directory &#39;{}&#39;&quot;, mediaDriver.aeronDirectoryName());<br>    mediaDriver.aeronDirectoryName();<br>}</pre><p><strong>Explanation:</strong></p><p>This method starts a <strong>MediaDriver</strong> inside the same JVM as your client (an <em>embedded driver</em>).</p><p><strong>MediaDriver.launchEmbedded()</strong></p><p>This is distinct from how we previously launched a MediaDriver, in the previous case we launched a standalone MediaDriver in a separate JVM, in this case we embed it into our application.</p><p>io.ryanjames.aeron.AeronSubscriberService</p><pre>public long addSubscriber(String channel, int streamId) {<br>    ensureConnected();<br><br>    Subscription subscriber = aeron.addSubscription(channel, streamId);<br><br>    FragmentHandler handler = (buffer, offset, length, header) -&gt;<br>            LOGGER.info(&quot;received: {}&quot;, buffer.getStringAscii(offset));<br>    FragmentAssembler assembler = new FragmentAssembler(handler);<br><br>    AgentRunner runner = pollSubscriberAsAgent(subscriber, assembler, channel, streamId);<br>    long registrationId = subscriber.registrationId();<br><br>    subscriptions.put(registrationId, subscriber);<br>    runners.put(registrationId, runner);<br><br>    LOGGER.info(&quot;Subscriber created with channel &#39;{}&#39;, streamId &#39;{}&#39; and registrationId &#39;{}&#39;&quot;,<br>            channel, streamId, registrationId);<br>    return registrationId;<br>}<br><br>private AgentRunner pollSubscriberAsAgent(Subscription subscriber, FragmentHandler handler,<br>                                          String channel, int streamId) {<br>    Agent agent = new Agent() {<br>        @Override public int doWork() {<br>            return subscriber.poll(handler, 10);<br>        }<br>        @Override public String roleName() {<br>            return String.format(&quot;aeron-subscriber-%s-%s&quot;, channel, streamId);<br>        }<br>    };<br><br>    AgentRunner runner =<br>            new AgentRunner(idleStrategy, t -&gt; LOGGER.error(&quot;Subscriber agent error&quot;, t), null, agent);<br>    AgentRunner.startOnThread(runner);<br>    return runner;<br>}</pre><p>There may seem like there is quite a bit going on in here, but let’s break it down into the parts that matter:</p><ul><li><strong>Create subscription</strong>: aeron.addSubscription(channel, streamId) registers a receiving endpoint for the given channel/stream.</li><li><strong>Assemble fragmented messages</strong>: FragmentAssembler wraps the FragmentHandler so messages split across frames are reassembled before being delivered to your handler. Essentially Aeron will send messages in fragments, long messages will be broken into fragments and this simply assembles them for you into the original <em>whole message.</em></li><li><strong>Poll loop as an agent</strong>: pollSubscriberAsAgent(...) builds an Agrona Agent whose doWork() simply calls subscriber.poll(handler, 10) to process up to 10 fragments per run. Remember that in Aeron we are always polling, messages <strong>will not</strong> be pushed onto the subscription.<br>The agent is run via AgentRunner.startOnThread(...), giving you a dedicated polling thread using the provided idleStrategy.</li><li><strong>Track by id</strong>: The subscription’s registrationId is returned and used as the key to store both the Subscription and its AgentRunner for later access/cleanup.</li></ul><p>Simply put you subscribe to (channel, streamId), reassemble incoming fragmented messages, and continuously poll them on a background thread.</p><p>If you browse the code there are more methods in each of these classes, mostly removing entities, checking liveliness and handling cleanup but hopefully the above walkthrough give you a flavour by pointing out the most important parts.</p><h3>A Simple Aeron Demo</h3><p><strong>Goal:</strong> Build a minimal system with a client that sends orders and a gateway that receives them.</p><p>Let’s begin by running our three modules — client-mediadriver, order-entry-client and order-gateway-service</p><h4>Starting the client-mediadriver</h4><p>1. Run ./gradlew client-mediadriver:run <br>2. Check the logs</p><pre>19:20:35.417 [main] INFO  io.javalin.Javalin - Javalin started in 234ms \o/<br>19:20:35.420 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7000/<br>19:20:35.427 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025).<br>19:20:35.427 [main] INFO  io.ryanjames.MediaDriverService - Redoc docs served at http://localhost:7000/redoc<br>19:20:35.427 [main] INFO  io.ryanjames.MediaDriverService - Swagger UI served at http://localhost:7000/swagger</pre><p>3. Navigate to url <a href="http://localhost:7000/swagger">http://localhost:7000/swagger</a><br>4. Start the MediaDriver with the directory path <strong>../aeron</strong>. Aeron will then create a directory at the project level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdRgMsTy0kLisOUogd-FsQ.png" /><figcaption>Start the mediadriver with REST request at <a href="http://localhost:7000/mediadriver/start"><strong>http://localhost:7000/mediadriver/start</strong></a></figcaption></figure><p>You can check that it has started as expected by navigating to the <strong>aeron</strong> directory at the root of your project. You should see a file called <strong>cnc.dat</strong> which is a good indication that it has worked as expected.</p><p><strong>Preparing the order-entry-client</strong></p><p>1. Run ./gradlew order-entry-client:run <br>2. Check the logs</p><pre>10:01:18.376 [main] INFO  io.javalin.Javalin - Javalin started in 366ms \o/<br>10:01:18.380 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7001/<br>10:01:18.395 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025).<br>10:01:18.396 [main] INFO  io.ryanjames.OrderEntryService - Redoc docs served at http://localhost:7001/redoc<br>10:01:18.396 [main] INFO  io.ryanjames.OrderEntryService - Swagger UI served at http://localhost:7001/swagger</pre><p>3. Navigate to <a href="http://localhost:7001/swagger">http://localhost:7001/swagger</a><br>4. Connect to the MediaDriver using the same directory we started the MediaDriver with — <strong>../aeron</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kZ8Rdr8A8obd2L-zaxSKg.png" /><figcaption>Connect the client with REST request at <strong>http://localhost:7001/client/connect</strong></figcaption></figure><p>Now our Aeron client is connected for making order entries. Next we can create a publication with the /client/addPublication endpoint. We will create a UDP publication with the following parameters:</p><ul><li>channel = aeron:udp?endpoint=localhost:40000</li><li>streamId = 10</li></ul><p><strong>Note:</strong> IPC won’t work here because the client and gateway use <strong>different MediaDrivers</strong>. Use UDP.</p><p>Here is the swagger endpoint we want to execute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0Az6E0XIOdgA-sUYe0ghw.png" /><figcaption>Add publication with REST endpoint — <strong>http://localhost:7001/client/addPublication</strong></figcaption></figure><p>You will see a <strong>registrationId</strong> returns both in the HTTP response and the logs</p><pre>Publication &#39;2&#39; created with channel aeron:udp?endpoint=localhost:40000 and streamId 10</pre><p>Take a note of this <strong>registrationId</strong> (<strong>2</strong> in my case) as we will use this to publish from this publication later.</p><p><strong>Preparing the order-gateway-server</strong></p><p>Next we follow similar steps to initialize the order entry client. Remember we use an <strong>embedded MediaDriver </strong>for this service that will start automatically, that gives us one less step.</p><p>1. Run ./gradlew order-gateway-server:run <br>2. Check the logs</p><pre>10:27:19.916 [main] INFO  io.javalin.Javalin - Javalin started in 322ms \o/<br>10:27:19.922 [main] INFO  io.javalin.Javalin - Listening on http://localhost:7002/<br>10:27:19.936 [main] INFO  io.javalin.Javalin - You are running Javalin 6.7.0 (released June 22, 2025).<br>10:27:19.936 [main] INFO  io.ryanjames.OrderGatewayService - Redoc docs served at http://localhost:7002/redoc<br>10:27:19.937 [main] INFO  io.ryanjames.OrderGatewayService - Swagger UI served at http://localhost:7002/swagger</pre><p>3. Navigate to <a href="http://localhost:7002/swagger">http://localhost:7002/swagger</a><br>4. Create a subscription</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5mCBej4stp27fiQa4GpzA.png" /><figcaption>Create a subscription listening on the same channel and stream as the publication with REST endpoint <a href="http://localhost:7002/gateway/addSubscriber"><strong>http://localhost:7002/gateway/addSubscriber</strong></a></figcaption></figure><p><strong>IMPORTANT</strong>: Note that in order to receive messages from the publication we created in the previous steps the channel and streamId MUST match.</p><p>After creating the subscription you will receive a registrationId (in logs and HTTP response) used as a hook for managing the subscription and closing it once finished.</p><pre>Subscriber &#39;2&#39; created with channel aeron:udp?endpoint=localhost:40000 and streamId 10</pre><p><strong>Publishing a message</strong></p><p>Finally we get to the point that we can publish a message from the publication we just created, and expect to receive it on the client.</p><p>1. Navigate back to the <strong>order-entry-client </strong>swagger UI and to — <a href="http://localhost:7001/swagger#/default/post_client_publishMessage">http://localhost:7001/swagger#/default/post_client_publishMessage</a></p><p>2. Publish a message, passing in the registrationId and any message you like (no order validation in this demo). Remember the registrationId is the ID you received when adding the publication. You should also see this in the logs:</p><pre>10:19:15.909 [JettyServerThreadPool-28] INFO  io.ryanjames.aeron.AeronClient - Publication &#39;2&#39; created with channel &#39;aeron:udp?endpoint=localhost:40000&#39;, streamId &#39;10&#39;</pre><p>In my case I will publish a NewOrderSingle message using the <a href="https://www.fixtrading.org/what-is-fix/">FIX Protocol</a> to make it somewhat realistic. This is the message we will send:</p><pre>8=FIX.4.4|9=148|35=D|34=1080|49=TESTBUY1|52=20180920-18:14:19.508|56=TESTSELL1|11=636730640278898634|15=USD|21=2|38=7000|40=1|54=1|55=MSFT|60=20180920-18:14:19.492|10=092| </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4BpaQuQ31stTZKA5LgWTg.png" /><figcaption>Publish a message from the order-entry-client with REST endpoint — <strong>http://localhost:7001/client/publishMessage</strong></figcaption></figure><p>If we now view the logs from the <strong>order-entry-client </strong>we will see the message is sent</p><pre>10:43:30.640 [JettyServerThreadPool-28] INFO  io.ryanjames.aeron.AeronClient - Message sent from 2: 8=FIX.4.4|9=148|35=D|34=1080|49=TESTBUY1|52=20180920-18:14:19.508|56=TESTSELL1|11=636730640278898634|15=USD|21=2|38=7000|40=1|54=1|55=MSFT|60=20180920-18:14:19.492|10=092|</pre><p>And then if we check the <strong>order-gateway-service </strong>logs we will see the order has been received</p><pre>10:43:30.648 [aeron-subscriber-aeron:udp?endpoint=localhost:40000-10] INFO  i.r.aeron.AeronSubscriberService - received: 8=FIX.4.4|9=148|35=D|34=1080|49=TESTBUY1|52=20180920-18:14:19.508|56=TESTSELL1|11=636730640278898634|15=USD|21=2|38=7000|40=1|54=1|55=MSFT|60=20180920-18:14:19.492|10=092|</pre><p>We proved end-to-end Aeron messaging:</p><ul><li><strong>Client → sent</strong><br>AeronClient.offer(...) wrote the FIX message into the publication’s log buffer and the MediaDriver pushed it over your chosen media (UDP).</li><li><strong>Gateway → received</strong><br>The gateway’s MediaDriver appended it to the subscription’s image buffer. Your subscription <strong>polled</strong>, the FragmentAssembler reassembled (if needed), and the handler logged received:...</li></ul><p>We discussed <strong>Log Buffers </strong>earlier, check out the ../aeron/publications directory and you should see a log buffer created (or multiple depending on how many bytes has been sent)</p><h3>Key Takeaways</h3><ul><li><strong>MediaDriver ≠ broker</strong> — each side runs its own driver (client standalone, gateway embedded).</li><li><strong>Match channel + stream</strong> — both ends must use the same channel URI and streamId.</li><li><strong>Polling mindset</strong> — nothing is “pushed”; your code drives poll().</li><li><strong>Simple URIs</strong> — aeron:udp?endpoint=... or aeron:ipc keep the API consistent across transports.</li></ul><h3>Quick Troubleshooting (if your logs don’t match)</h3><ul><li>Channel/stream mismatch? (e.g., aeron:udp?... vs aeron:ipc, wrong streamId)</li><li>Not polling? Ensure the subscription agent is running.</li><li>Is the MediaDriver running?</li><li>Wrong driver directory? Client/gateway must point at the <strong>correct</strong> MediaDriver or network is reachable (for UDP).</li><li>Publication closed/back pressured? Check the offer() return code in logs.</li></ul><h3>What’s Next?</h3><p>This was a very simple demo of Aeron’s core workings. Now that you’ve seen messages flow end-to-end, try a few quick experiments:</p><ul><li><strong>Play with streams:</strong> create multiple publications/subscriptions on the <strong>same channel</strong> but different streamIds. Then try multiple publications on the <strong>same stream</strong> to see distinct sessionIds in action.</li><li><strong>Multiple hosts: </strong>try deploying this demo on multiple hosts. Can you send messages remotely with UDP?</li><li><strong>Probe back pressure:</strong> slow the subscription (or pause its agent) and watch offer() return codes in the client logs.</li><li><strong>Extend the demo: </strong>The demo project offers a skeleton of a client -&gt; gateway relationship. Try to make build it into something more useful, and even try making it bidirectional to allow the gateway to ACK orders.</li></ul><p>Aeron also has many more features that we haven’t touched here. If you are curious here are some other topics worth looking into. Resources will be at the end to help you explore these.</p><ul><li><a href="https://aeron.io/docs/aeron/aeron-tooling/#aeron-stat"><strong>Aeron Stats</strong></a><strong> — </strong>use counters to view stats and metrics</li><li><a href="https://aeron.io/docs/aeron-archive/overview/"><strong>Archiving </strong></a><strong>— </strong>allow recording and replaying of streams</li><li><a href="https://aeron.io/docs/aeron/multi-destination-cast/"><strong>MDC (Multi-Destination-Cast)</strong></a><strong> — </strong>similar to multicast, allows publication to multiple destinations. <em>NOTE: not a lot of the demo code changes required for this, could be a good challenge and will help with understanding of channel configuration.</em></li></ul><h3>Conclusion</h3><p>Aeron can feel unfamiliar at first, but the core ideas are simple once you see them in motion: your app uses the <strong>Client API</strong> (publications/subscriptions), the <strong>MediaDriver</strong> is the engine that moves bytes over <strong>UDP or IPC</strong>, and you control throughput with a <strong>polling</strong> model rather than callbacks. Pair that with <strong>channels + stream IDs</strong> (and optional <strong>sessions</strong>) to define where messages flow, and you’ve got a lean, predictable messaging stack.</p><p>In the demo we kept things gentle: one driver embedded, one driver standalone, a single publication and subscription, and a REST layer to control them. That was enough to prove end-to-end delivery, peek at <strong>log buffers</strong>, and get a feel for Aeron.</p><p>From here, you can explore a bit deeper — try <strong>remote hosts</strong>, add <strong>multiple streams</strong>, extend the demo, project, play with <strong>MDC</strong> for fan-out, or glance at counters/stats for observability. When you’re ready, there’s a whole world beyond point-to-point: the <strong>Archiver</strong>, <strong>multicast</strong>, and eventually <strong>Aeron Cluster</strong>.</p><p>If you found this helpful (or ran into an issue), drop a comment. And if you played around with the code, I’d love to hear what you discovered!</p><h3>Resources</h3><p><strong>Start here</strong></p><ul><li><a href="https://aeron.io/">https://aeron.io/ </a>— official site</li><li><a href="https://aeron.io/docs/aeron/overview/">https://aeron.io/docs/aeron/overview/ </a>— Aeron overview</li></ul><p><strong>Docs you’ll use</strong></p><ul><li><a href="https://github.com/aeron-io/aeron/wiki/Channel-Configuration">https://github.com/aeron-io/aeron/wiki/Channel-Configuration</a> — <strong>Channel URI options (UDP, IPC, MDC, multicast)</strong></li><li><a href="https://aeron.io/docs/aeron/publications-subscriptions/">https://aeron.io/docs/aeron/publications-subscriptions/</a> — <strong>Publications &amp; Subscriptions (offer/poll model)</strong></li><li><a href="https://aeron.io/docs/aeron/log-buffers-images/">https://aeron.io/docs/aeron/log-buffers-images/</a> —<strong> Log Buffers &amp; Images</strong></li></ul><p><strong>Demo Project</strong></p><ul><li><a href="https://github.com/k4pran/Aeron-Demo">https://github.com/k4pran/Aeron-Demo</a> — <strong>GitHub Demo Project</strong></li></ul><p><strong>Talks</strong></p><ul><li><strong>“Aeron: Open-source high-performance messaging” — Martin Thompson</strong> (<a href="https://www.youtube.com/watch?v=tM4YskS94b0">YouTube</a>)</li></ul><h4>About the author</h4><p>Ryan McCauley is a Senior Software Engineer here at <a href="https://www.version1.com/">Version 1</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfe1d841d5d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/building-low-latency-messaging-with-aeron-in-java-cfe1d841d5d4">Building Low-Latency Messaging with Aeron in Java</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Sonar Pipelines with Inbound (JNLP) Jenkins Agents]]></title>
            <link>https://medium.com/@ryan.mccauley_15203/unity-sonar-pipelines-with-inbound-jnlp-jenkins-agents-2a50314a427c?source=rss-61f22c0e45f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a50314a427c</guid>
            <category><![CDATA[sonar]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Ryan McCauley]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 18:39:41 GMT</pubDate>
            <atom:updated>2025-09-11T18:39:41.795Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting this working was a journey of trial and error — I must have broken it a hundred different ways before landing on a solution that finally stuck. The goal sounded simple enough: run SonarQube analysis against my Unity project inside a Jenkins pipeline.</p><p>In practice, it turned out to be trickier than expected, thanks to the way Unity, Jenkins, and Sonar interact. In this post, I’ll walk through what I tried, what went wrong, and how I eventually got everything running smoothly with Jenkins inbound agents and Unity’s test runner.</p><p>This article will be documenting my own path to a solution, I am not an expert, much of this could be my unnecessary adventure and this problem is solved in a much simpler way, but I found it fun and wanted to talk about it. Let’s begin with what didn’t work.</p><h3>Failed Attempts</h3><h4># 1 — Running everything in a cloud Linux box</h4><p>My first idea was to run Unity directly in the cloud. I already had Jenkins and SonarQube running on a Fedora server in DigitalOcean, so I figured adding Unity to the mix would be straightforward.</p><p>Installing Unity wasn’t the problem — I got it downloaded and set up. The roadblock came with licensing. Unity requires license activation before it will run in batchmode, and on Linux that usually means either:</p><ul><li>validating through a graphical interface (not an option on a headless server), or</li><li>using a Pro/Plus license with floating activation.</li></ul><p>Since I only had a free license and no GUI available, I hit a dead end.</p><h4># 2 — Trying Unity Hub for license activation</h4><p>The next idea was to use <strong>Unity Hub</strong>. Unlike the standalone Unity editor, Hub can manage licenses, and there’s some documentation suggesting it can be run in headless mode. On paper, that sounded like a way to bypass the GUI requirement.</p><p>In practice, it turned into a rabbit hole. Even in headless mode, Unity Hub still expects some form of display environment. I experimented with virtual displays (Xvfb and similar setups), but every attempt uncovered new blockers. After spending too much time chasing errors, I had to abandon this approach.</p><h4># 3 — Trying Unity DevOps</h4><p>When I discovered <strong>Unity DevOps</strong>, it felt like the perfect solution. The freemium plan gives some build storage and enough runtime to handle a few builds per month. I set it up, and sure enough — Unity builds were running successfully in the cloud.</p><p>The catch came when I tried to hook those builds into <strong>SonarQube</strong>. Sonar has a very strict requirement: a C# solution must be compiled between two scanner commands:</p><p>BUT now how do we hook it into SonarQube? The issue here seems that unity can build, and output artifacts including debug info, but SonarQube has a strict requirement that a C# solution needs to be run between two sonar scanner commands like this</p><pre>SonarScanner.MSBuild.exe begin /k:&quot;project-key&quot; /d:sonar.login=&quot;myAuthenticationToken&quot;<br>MSBuild.exe &lt;path to solution.sln&gt; /t:Rebuild<br>SonarScanner.MSBuild.exe end /d:sonar.login=&quot;myAuthenticationToken&quot;</pre><p>Unity DevOps can output artifacts (including debug info), but SonarQube doesn’t accept just the artifacts. The solution has to be rebuilt inside the same pipeline where SonarScanner is running. That requirement broke this approach — Unity could build in the cloud, but I couldn’t get the results back into Sonar in a usable way.</p><h4># 4 — Cloud Windows Server</h4><p>This would have solved licensing, but it was too expensive and still required a GUI — not ideal for headless CI</p><h4>#5 — Considering GitHub Workflows</h4><p>This seemed like it could be an option but I never got around to trying it, seemed like without a GUI it would have ran into similar licensing issues. Without a reliable way to activate Unity, this approach would have just led to the same dead end as my cloud Linux attempts.</p><h4># 6 — Running it all locally</h4><p>As a last resort — and a bit of an <strong>admission of defeat</strong> — I fell back to running everything locally. That meant Jenkins, SonarQube, and the Unity project were all on the same machine.</p><p>And yes, it technically worked. I could run builds, run tests, and push results into Sonar. But the limitations were obvious:</p><ul><li>It was <strong>offline by default</strong>, so setting up GitHub webhooks or external triggers wasn’t straightforward.</li><li>It tied everything to a single machine, which meant switching laptops or collaborating with someone else was a huge headache.</li><li>Maintaining Jenkins and SonarQube across multiple machines just wasn’t realistic.</li></ul><p>This setup was fine for <strong>experimentation</strong>, but it was never going to become a long-term solution.</p><h3>Solution: Using Inbound Agents</h3><p>After all those failed attempts, I finally landed on a solution that worked. It wasn’t exactly what I had envisioned at the start, but for a solo developer it’s a solid compromise that balances flexibility and simplicity.</p><p>In this setup:</p><ul><li><strong>Jenkins</strong> and <strong>SonarQube</strong> run remotely on a server.</li><li><strong>Unity Editor</strong> and the <strong>.NET SonarScanner</strong> run locally on my development machine.</li><li>I connect my machine to Jenkins as an <strong>inbound agent</strong>, which allows the remote Jenkins controller to trigger Unity commands and Sonar scans directly on my laptop.</li><li>The results are then published back to the remote Jenkins and SonarQube dashboards.</li></ul><p>This flow avoids the licensing and headless issues I hit in the cloud, but still gives me the benefit of centralized dashboards and automation. It also scales just enough: with a bit of configuration (mainly setting environment variables for project paths and Unity executables), I can run the same pipeline on different local machines with minimal effort.</p><p>For a solo developer setup, this turned out to be the right balance — not completely in the cloud, but a reliable pipeline that runs Unity tests, gathers results, and feeds SonarQube analysis without fighting the tooling at every step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OV_lYN3emkpD_yhu.png" /></figure><p>This setup solves a lot of the headaches that come with trying to run Unity entirely in the cloud. By running the editor and scanner locally, I sidestep licensing hurdles, display issues, and awkward workarounds — while still getting centralized reporting through Jenkins and SonarQube.</p><p>Is it the ideal solution for a team? Probably not. A fully cloud-native build pipeline would scale better in a multi-developer environment. But for a solo developer, this approach strikes the right balance: I can keep using my development machine for Unity builds and tests, while Jenkins handles orchestration and SonarQube tracks code quality in one place.</p><h3>Webhooks and Version Control</h3><p>One nice advantage of this approach over running everything purely local is that Jenkins can still integrate with your version control system. That means you can trigger builds automatically on commits, pull request creation, or whatever event makes sense for your workflow.</p><p>So what happens if the agent (your local machine) is offline? In that case, Jenkins will simply queue the job until the agent comes back online. For me, this is perfect: I can raise a PR (yes, I review my own PRs), close my laptop for the night, and when I start working the next day, Jenkins picks up the queued pipeline and runs it.</p><p>This small detail makes the whole setup feel a lot more like a “real” CI system, even though the heavy lifting is still happening on my local development machine.</p><h3>The Bad and the Ugly</h3><p>I’ve called this setup a compromise for a reason — there are some rough edges worth pointing out:</p><ul><li><strong>Unity Editor can’t run multiple instances.</strong> If my pipeline is running tests in Unity, I can’t use the same Editor instance for development at the same time. A possible workaround is installing multiple copies of the same Unity version and dedicating one just for pipelines.</li><li><strong>Builds only run when the local agent is online.</strong> If my laptop is off, Jenkins can queue jobs, but nothing executes until I bring the agent back.</li><li><strong>Manual agent management.</strong> I need to start the Jenkins agent manually on my machine, and occasionally restart it if environment variables or certain configuration changes are made.</li><li><strong>Multiple machines drawback</strong> — I still need to have a compatible unity editor installed on each local machine I want to develop with.</li></ul><p>These drawbacks don’t make the solution unusable — but they are the trade-offs for avoiding the licensing and headless issues that come with cloud-based Unity builds.</p><h3>Walkthrough</h3><p>Now that we’ve covered the background and the trade-offs, let’s walk through how to set up this pipeline step by step.</p><h4>Prerequisites</h4><p>Before getting started, make sure you have the following in place:</p><ul><li><strong>Unity project</strong> stored in version control (e.g. Git)</li><li><strong>Jenkins</strong> running on a remote server</li><li><strong>SonarQube</strong> running on a remote server</li><li><strong>Jenkins Git plugin</strong> → <a href="https://plugins.jenkins.io/git/?utm_source=chatgpt.com">Git Plugin</a></li><li><strong>Jenkins GitHub plugin</strong> → <a href="https://plugins.jenkins.io/github/?utm_source=chatgpt.com">GitHub Plugin</a></li><li><strong>Unity editor </strong>installed locally</li></ul><p>With the prerequisites in place, the next step is configuring Jenkins to use a <strong>local inbound agent</strong> that can run Unity and Sonar scans.</p><p>Start by setting up the <strong>Git</strong> and <strong>GitHub</strong> plugins in Jenkins. Each plugin page has detailed setup instructions, and there are a few variations depending on how your Jenkins server is exposed.</p><p>Once the plugins are configured, verify that GitHub is correctly sending events to Jenkins:</p><p>You should see a webhook pointing to your Jenkins server, something like:</p><ol><li>Go to your repository in GitHub.</li><li>Navigate to <strong>Settings → Webhooks</strong>.</li><li>You should see a webhook pointing to your Jenkins server, something like — <a href="https://my.jenkins.url/github-webhook/">https://my.jenkins.url/github-webhook/</a></li></ol><p>This confirms that GitHub will trigger your Jenkins pipeline whenever you push code or open a pull request.</p><h4>Setting up the Inbound agent</h4><p>By default, Jenkins comes with a single built-in agent, but we need to create a dedicated <strong>inbound agent</strong> for Unity. Here’s how to set it up:</p><ol><li>On the Jenkins dashboard, click the <strong>Manage Jenkins</strong> (⚙️) icon.</li><li>Navigate to <strong>Nodes</strong>.</li><li>Click <strong>New Node</strong>.</li><li>Enter a name (e.g. local-machine) and select <strong>Permanent Agent</strong>.</li><li>Configure the following settings:</li><li>&gt; <strong>Remote root directory</strong> → This is where Jenkins will write files on your local machine. For example - C:\Jenkins<br>All project checkouts and pipeline working directories will live here.</li><li>&gt; <strong>Labels</strong> → Add descriptive labels to control where pipelines run. In this case - local-machine unity msbuild</li><li>&gt; <strong>Usage</strong> → Select <strong>Only build jobs with label expressions matching this node</strong>.<br>This ensures that jobs only run on this agent when explicitly requested.</li><li>&gt; <strong>Launch method</strong> → Choose <strong>Launch agent by connecting to the controller</strong>.<br>This uses WebSockets, and Jenkins will generate a token for securely launching the agent.</li><li>&gt;<strong> Availability</strong> → Set to <strong>Keep this agent online as much as possible</strong>.</li><li>Click <strong>Save</strong>.</li></ol><p>If everything went smoothly, you should now see the agent listed on the left-hand side of the Jenkins dashboard under <strong>Build Executor Status</strong>.</p><p>Next, we’ll look at how to actually run the new agent on your local machine.</p><h4>Running the Inbound Agent</h4><p>In the previous step, we created an inbound agent called <strong>local-machine</strong>. At this point, you’ll notice it shows as <strong>offline</strong> in Jenkins — that’s because your local machine hasn’t yet connected back to the Jenkins controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*kpXOQCUiQyAUiFoR.png" /></figure><p>Click on the <strong>local-machine</strong> agent in Jenkins, and you’ll see a page with connection instructions. Jenkins conveniently provides the exact command you need to run, tailored for different operating systems.</p><p>Since we’re running on <strong>Windows</strong>, open a <strong>Command Prompt</strong> and paste the command shown. It will look something like this (your URL and secret will differ):</p><pre>curl.exe -sO https://my.jenkins.url/jnlpJars/agent.jar &amp; java -jar agent.jar -url https://example.jenkins.com/ -secret 123456789 -name &quot;local-machine&quot; -webSocket -workDir &quot;C:\Jenkins&quot;</pre><p>This command does two things:</p><ol><li><strong>Downloads the agent JAR</strong> from the Jenkins controller.</li><li><strong>Runs it with Java</strong>, which establishes a WebSocket connection back to Jenkins using the secret token.</li></ol><p>Notice that it also includes the <strong>working directory</strong> (-workDir &quot;C:\Jenkins&quot;) we configured earlier. That’s where Jenkins will check out code and store any temporary files for this agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*ACD7_GU8WLUpM8hl.png" /></figure><p>After running the command, refresh your Jenkins dashboard — the <strong>local-machine</strong> agent should now show as <strong>online</strong>, ready to accept jobs.</p><h4>Matching Agents to Pipelines with Labels</h4><p>Now that the agent is running, click on it in the Jenkins dashboard. You’ll see the list of labels we configured earlier:</p><ul><li>local-machine</li><li>unity</li><li>msbuild</li></ul><p>These labels make it easy to control which jobs run on which agents. To target this agent in a pipeline, just reference one of its labels in your <strong>Jenkinsfile</strong>. For example:</p><pre>pipeline {<br>  agent { label &#39;local-machine&#39; }<br><br>  stages {<br>    stage(&#39;Build&#39;) {<br>      steps {<br>        echo &quot;Running on the local-machine agent&quot;<br>      }<br>    }<br>  }<br>}</pre><p>When this pipeline runs, Jenkins will search for an agent with the matching label. Since our inbound agent is labeled <strong>local-machine</strong>, it will pick up the job.</p><h4>Adding Agent Timeouts</h4><p>By default, if an agent is offline, Jenkins will queue the job and wait for it to come back online. That’s useful, but if the agent stays offline too long, the build may eventually time out.</p><p>Since this setup relies on a <strong>local machine</strong> (and in my case, a laptop that frequently changes WiFi networks), the WebSocket connection can drop. To avoid jobs failing too quickly, we can make Jenkins more patient by setting a longer timeout directly in the <strong>Jenkinsfile</strong>:</p><pre>pipeline {<br>  agent { label &#39;local-machine&#39; }<br><br>  options {<br>    timeout(time: 48, unit: &#39;HOURS&#39;)<br>  }<br><br>  stages {<br>    stage(&#39;Example&#39;) {<br>      steps {<br>        echo &quot;This job can wait up to 48 hours for the agent to come online.&quot;<br>      }<br>    }<br>  }<br>}</pre><p>In this example, Jenkins will wait up to <strong>48 hours</strong> for the agent to reconnect before giving up. That number might seem high, but it’s use-case dependent. For me, it works well — I rarely have my laptop offline longer than two days, and I want queued builds to resume as soon as the agent is available again.</p><h4>Generating Unity Project Files</h4><p>Unity manages the .sln and .csproj files automatically, and most teams leave them out of version control. That’s fine for day-to-day development, but it creates a problem for SonarQube: <strong>Sonar requires a valid Visual Studio solution and project files in order to run its MSBuild-based analysis</strong>.</p><p>To solve this, we need to regenerate the solution before running Sonar. Unfortunately, Unity doesn’t provide a one-click CLI option for this. Instead, we can take advantage of the <a href="https://docs.unity3d.com/Packages/com.unity.ide.rider@3.0/manual/using-the-jetbrains-rider-editor-package.html">JetBrains Rider Editor package</a> which exposes a method to force Unity to sync project files.</p><p>The key command looks like this:</p><pre>Unity -batchmode -quit -projectPath ProjectPath -executeMethod Packages.Rider.Editor.RiderScriptEditor.SyncSolution</pre><p>This ensures Unity regenerates the .sln and .csproj files inside the project. With that in place, we can build them in the pipeline and let Sonar do its analysis. Note that this comes with Rider, if using Visual Studio you will likely need to execute a different method.</p><p>Here’s how it fits into the Jenkins stages:</p><pre>stage(&#39;Checkout&#39;) {<br>        steps {<br>            cleanWs()<br>            checkout scm<br>        }<br>    }<br>    stage(&#39;Activate Unity License&#39;) {<br>      steps {<br>        withCredentials([<br>          usernamePassword(<br>            credentialsId: &#39;unity-login&#39;,<br>            usernameVariable: &#39;UNITY_USERNAME&#39;,<br>            passwordVariable: &#39;UNITY_PASSWORD&#39;<br>          )<br>        ]) {<br>          bat &quot;&quot;&quot;<br>            &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -projectPath ProjectPath -nographics -quit ^<br>              -logFile - ^<br>              -username &quot;%UNITY_USERNAME%&quot; ^<br>              -password &quot;%UNITY_PASSWORD%&quot;<br>          &quot;&quot;&quot;<br>        }<br>      }<br>    }<br>    stage(&#39;Generate Unity Project Files&#39;) {<br>      steps {<br>        bat &quot;&quot;&quot;<br>              &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -nographics -quit ^<br>                -projectPath &quot;%WORKSPACE%&quot; ^<br>                -executeMethod Packages.Rider.Editor.RiderScriptEditor.SyncSolution ^<br>                -logFile -<br>            &quot;&quot;&quot;<br>      }<br>    }<br>    stage(&#39;Run Unity Non-Playmode Tests&#39;) {<br>      steps {<br>        script {<br>            bat &quot;&quot;&quot;<br>                  &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -nographics ^<br>                    -projectPath &quot;%WORKSPACE%&quot; ^<br>                    -runTests -testPlatform editmode ^<br>                    -testResults &quot;%WORKSPACE%\\${UNITY_UNIT_TEST_RESULTS_FILE}&quot; ^<br>                    -enableCodeCoverage ^<br>                    -coverageResultsPath &quot;%WORKSPACE%\\Coverage&quot; ^<br>                    -coverageOptions &quot;generateAdditionalMetrics;generateHtmlReport&quot; ^<br>                    -burst-disable-compilation ^<br>                    -logFile &quot;%WORKSPACE%\\unityTestLog.txt&quot;<br>                &quot;&quot;&quot;<br>        }<br>      }<br>      post {<br>        always {<br>          script {<br>            if (fileExists(&quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;)) {<br>              nunit testResultsPattern: &quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;<br>              archiveArtifacts artifacts: &quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;, fingerprint: true<br>            }<br>            archiveArtifacts artifacts: &quot;Coverage/**&quot;, allowEmptyArchive: true<br>          }<br>        }<br>      }<br>    }</pre><p>At this point we’ve:</p><ol><li>Checked out the project.</li><li>Validated the Unity license.</li><li>Regenerated the .sln/.csproj files.</li><li>Run editmode unit tests with code coverage enabled.</li></ol><p>With these pieces in place, the project is now ready for the <strong>SonarQube analysis stage</strong>.</p><h4>Running the SonarScanner</h4><p>With the Unity setup complete (project files generated, tests executed, coverage produced), running SonarQube is the final step. Fortunately, this part is relatively straightforward.</p><p>SonarQube’s MSBuild integration always follows the same three-step pattern:</p><ol><li><strong>Begin analysis</strong> — start the scanner and configure project keys, exclusions, and coverage paths.</li><li><strong>Build the solution</strong> — run MSBuild so Sonar can analyze the compiled C# code.</li><li><strong>End analysis</strong> — finalize and push the results to the SonarQube server.</li></ol><p>Here’s what that looks like in the Jenkinsfile:</p><pre>stage(&#39;SonarQube Analysis&#39;) {<br>      steps {<br>        script {<br>          def scannerHome = tool &#39;SonarScanner_NET&#39;<br>          withSonarQubeEnv(&#39;SonarQube&#39;) {<br>            bat &quot;\&quot;${scannerHome}\\SonarScanner.MSBuild.exe\&quot; begin &quot; +<br>                &quot;/k:\&quot;MyProject\&quot; &quot; +<br>                &quot;/d:sonar.sourceEncoding=UTF-8 &quot; +<br>                &quot;/d:sonar.exclusions=\&quot;**/Plugins/**/*,**/Libraries/**/*,**/Vendor/**/*,**/Samples/**,**/XR/**,**/Packages/**/*,**/ThirdParty/**/*\&quot; &quot; +<br>                &quot;/d:sonar.cs.opencover.reportsPaths=\&quot;%WORKSPACE%\\Coverage\\**\\*.xml\&quot;&quot;<br>                <br>            bat &quot;MSBuild.exe MyProject.sln /t:Rebuild /p:Configuration=Debug&quot;<br>            bat &quot;\&quot;${scannerHome}\\SonarScanner.MSBuild.exe\&quot; end&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>A few details to note:</p><ul><li><strong>Exclusions</strong>: Unity projects contain thousands of auto-generated or third-party files under Plugins/, Packages/, etc. Excluding them keeps the analysis focused on your actual code.</li><li><strong>Coverage reports</strong>: The /d:sonar.cs.opencover.reportsPaths property points Sonar to the XML reports generated by Unity’s test runner in the previous stage. This lets you see test coverage metrics directly inside the SonarQube dashboard.</li><li><strong>Project key</strong>: /k:&quot;MyProject&quot; is the unique identifier for this project in SonarQube. Make sure it matches the key you configured in the SonarQube UI.</li></ul><p>With this stage complete, Jenkins pushes a full analysis — including code quality issues and coverage — into SonarQube, where you can track it over time and enforce quality gates.</p><h4>Creating the Jenkins Pipeline</h4><p>With everything set up, the final step is to create the actual Jenkins pipeline.</p><ol><li><strong>Create the pipeline job<br>- </strong>From the Jenkins dashboard, click <strong>New Item</strong>.<br>- Enter a name (e.g. Unity-Sonar-Pipeline).<br>- Select <strong>Pipeline</strong> and click <strong>OK</strong>.</li><li><strong>Configure the job</strong> — Most of the configuration depends on your project, but here are a few key points:<br>- <strong>Triggers</strong> → Select <strong>GitHub hook trigger for GITScm polling</strong>.<br>This lets the GitHub and Git plugins work together to trigger builds automatically when a push or pull request event is received from GitHub.<br>- <strong>Pipeline Definition</strong> → Set this to <strong>Pipeline script from SCM</strong>.<br>This ensures Jenkins uses the Jenkinsfile stored in your repository, keeping pipeline logic version-controlled alongside your code.<br>- <strong>Branches to build</strong> → Adjust this to fit your workflow.<br>In my case, I added two branch specifiers: origin/FeaturePrefix-* (feature branches) and origin/master (main branch)</li><li><strong>Kick off the first build</strong><br>I found that webhooks didn’t trigger until after the first manual build. So run one build manually to “prime” Jenkins, and after that GitHub webhooks should trigger new builds automatically.</li></ol><h4>Triggering the pipeline</h4><p>With everything in place, we’re finally ready to trigger our first build.</p><p>Below is the complete Jenkinsfile for reference. This pulls together all the steps we’ve covered so far — checking out the code, activating the Unity license, generating project files, running tests with coverage, and finally running SonarQube analysis.</p><pre>pipeline {<br>  agent { label &#39;local-machine&#39; }<br>  <br>  options {<br>    timeout(time: 48, unit: &#39;HOURS&#39;)<br>  } <br> <br>  environment {<br>    PROJECT_NAME = &#39;MyProject&#39;<br>    UNITY_UNIT_TEST_RESULTS_FILE = &#39;UnityTestResults.xml&#39;<br>  }<br>  <br>  tools { msbuild &#39;ms22&#39; }<br><br>  stages {<br>    stage(&#39;Checkout&#39;) {<br>        steps {<br>            cleanWs()<br>            checkout scm<br>        }<br>    }<br>    stage(&#39;Activate Unity License&#39;) {<br>      steps {<br>        withCredentials([<br>          usernamePassword(<br>            credentialsId: &#39;unity-login&#39;,<br>            usernameVariable: &#39;UNITY_USERNAME&#39;,<br>            passwordVariable: &#39;UNITY_PASSWORD&#39;<br>          )<br>        ]) {<br>          bat &quot;&quot;&quot;<br>            &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -nographics -quit ^<br>              -logFile - ^<br>              -username &quot;%UNITY_USERNAME%&quot; ^<br>              -password &quot;%UNITY_PASSWORD%&quot;<br>          &quot;&quot;&quot;<br>        }<br>      }<br>    }<br>    stage(&#39;Generate Unity Project Files&#39;) {<br>      steps {<br>        bat &quot;&quot;&quot;<br>              &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -nographics -quit ^<br>                -projectPath &quot;%WORKSPACE%&quot; ^<br>                -executeMethod Packages.Rider.Editor.RiderScriptEditor.SyncSolution ^<br>                -logFile -<br>            &quot;&quot;&quot;<br>      }<br>    }<br>    stage(&#39;Run Unity Non-Playmode Tests&#39;) {<br>      steps {<br>        script {<br>            bat &quot;&quot;&quot;<br>                  &quot;%UNITY_EDITOR_PATH%&quot; -batchmode -nographics ^<br>                    -projectPath &quot;%WORKSPACE%&quot; ^<br>                    -runTests -testPlatform editmode ^<br>                    -testResults &quot;%WORKSPACE%\\${UNITY_UNIT_TEST_RESULTS_FILE}&quot; ^<br>                    -enableCodeCoverage ^<br>                    -coverageResultsPath &quot;%WORKSPACE%\\Coverage&quot; ^<br>                    -coverageOptions &quot;generateAdditionalMetrics;generateHtmlReport&quot; ^<br>                    -burst-disable-compilation ^<br>                    -logFile &quot;%WORKSPACE%\\unityTestLog.txt&quot;<br>                &quot;&quot;&quot;<br>        }<br>      }<br>      post {<br>        always {<br>          script {<br>            if (fileExists(&quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;)) {<br>              nunit testResultsPattern: &quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;<br>              archiveArtifacts artifacts: &quot;${env.UNITY_UNIT_TEST_RESULTS_FILE}&quot;, fingerprint: true<br>            }<br>            archiveArtifacts artifacts: &quot;Coverage/**&quot;, allowEmptyArchive: true<br>          }<br>        }<br>      }<br>    }<br>    stage(&#39;SonarQube Analysis&#39;) {<br>      steps {<br>        script {<br>          def scannerHome = tool &#39;SonarScanner_NET&#39;<br>          withSonarQubeEnv(&#39;MyProjectQube&#39;) {<br>            bat &quot;\&quot;${scannerHome}\\SonarScanner.MSBuild.exe\&quot; begin &quot; +<br>                &quot;/k:\&quot;MyProject\&quot; &quot; +<br>                &quot;/d:sonar.sourceEncoding=UTF-8 &quot; +<br>                &quot;/d:sonar.exclusions=\&quot;**/Plugins/**/*,**/Libraries/**/*,**/Vendor/**/*,**/Samples/**,**/XR/**,**/Packages/**/*,**/ThirdParty/**/*\&quot; &quot; +<br>                &quot;/d:sonar.cs.opencover.reportsPaths=\&quot;%WORKSPACE%\\Coverage\\**\\*.xml\&quot;&quot;<br>                <br>            bat &quot;MSBuild.exe MyProject.sln /t:Rebuild /p:Configuration=Debug&quot;<br>            bat &quot;\&quot;${scannerHome}\\SonarScanner.MSBuild.exe\&quot; end&quot;<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>First Run</strong></p><p>Before GitHub webhooks will trigger jobs automatically, you’ll likely need to <strong>manually run the first build</strong> in Jenkins. This primes the pipeline and makes sure everything is wired up correctly.</p><p>After that:</p><ol><li>Make a change in your branch.</li><li>Push the commit.</li><li>Check the <strong>GitHub Hook Log</strong> in Jenkins</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*P-yfrj2Yv5b7xbrP.png" /></figure><p>You should see entries like this:</p><pre>Seen 73 remote branches<br> &gt; git show-ref --tags -d # timeout=10<br> &gt; git log --full-history --no-abbrev --format=raw -M -m f73c03bf3ea8b7ae03471ff97ccd458c0b6bd971..b8ac068982f4238bf8d0823d1c18bb431cfe3e44 # timeout=10<br>Done. Took 12 sec<br>Changes found</pre><p>This means Jenkins detected the commit and started a new build.</p><p>If all went well you should finally see the results on your SonarQube server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hx7eBeOCUZ3UDwuX.png" /></figure><p><strong>Results</strong></p><p>If everything went smoothly, the pipeline will:</p><ul><li>Run Unity in batchmode to generate project files.</li><li>Execute editmode tests with code coverage enabled.</li><li>Send results to Jenkins (via NUnit and archived artifacts).</li><li>Rebuild the solution with SonarScanner hooks.</li><li>Publish code quality and coverage metrics to <strong>SonarQube</strong>.</li></ul><p>Finally, you’ll be able to view your results in SonarQube’s dashboard:</p><ul><li>Test coverage</li><li>Code smells</li><li>Duplications</li><li>Bugs and vulnerabilities</li><li>Quality gate status</li></ul><p>This is where all the effort pays off — automated Unity testing and SonarQube analysis running cleanly inside Jenkins. 🎉</p><h3>Wrapping It Up</h3><p>Setting up a Unity pipeline with Jenkins and SonarQube isn’t as straightforward as it is with more traditional .NET or Java projects. Between Unity’s licensing quirks, the lack of a true headless mode, and SonarQube’s strict requirements around building from solution files, it’s easy to get stuck chasing dead ends.</p><p>I am also aware there could be solutions out there and I would be surprised if wasn’t missing a few tricks in setting up Unity pipelines, so I guess this is my own journey and hopefully I can learn about other solutions out there.</p><p>Inbound agents turned out to be the key that unlocked everything. By letting Jenkins orchestrate builds on my local development machine, I was able to:</p><ul><li>Run Unity in batchmode for test execution and code coverage.</li><li>Generate solution files on demand (via Rider integration).</li><li>Execute SonarScanner in the correct order to capture results.</li><li>Keep Jenkins and SonarQube hosted remotely for centralized dashboards.</li></ul><p>Is this the perfect, cloud-native pipeline? Not quite. For a large team, scaling across multiple agents or moving to Unity DevOps with an enterprise license would probably be a better long-term play. But for a solo developer (or a small team experimenting with CI), this approach strikes a great balance — it’s reliable, flexible, and avoids most of the pain points that derail other setups.</p><p>At the end of the day, the pipeline now does exactly what I need: run Unity tests, measure coverage, feed results into SonarQube, and keep my quality gates green. And just as importantly — it does it automatically whenever I push code.</p><p>If you’ve been struggling to get Unity working cleanly with Jenkins and SonarQube, I hope this walkthrough saves you a few of the headaches I had along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a50314a427c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Curb Your Copy-Paste: Templating with Apache Velocity]]></title>
            <link>https://medium.com/version-1/curb-your-copy-paste-templating-with-apache-velocity-816c1e72f46a?source=rss-61f22c0e45f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/816c1e72f46a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[templating-engine]]></category>
            <dc:creator><![CDATA[Ryan McCauley]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 09:59:09 GMT</pubDate>
            <atom:updated>2025-07-21T09:59:09.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*80N1a1WODSdWzt2K" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When most of us think of ‘templating,’ we think of writing HTML, where placeholders get swapped out for dynamic data. But templating is not limited to web views, and can be used to generate configuration files, automate reports and produce documentation. We’ll show you how you can use templating to generate java code and cut down on repetitive coding.</p><p><strong>Assumptions</strong>: You know your way around Java — nothing more.</p><p>Whenever you find yourself writing the same code over and over, and your are writing from some reference data source. Pause and ask yourself: can this be automated? If your project meets the following criteria it may be a good fit for automation.</p><ol><li><strong>You have one authoritative data source</strong> (your schema, config, or spec).</li><li><strong>Your code follows a clear, repeatable pattern</strong> (same class structure, conversions, etc.).</li></ol><p>If both apply, a template engine can eliminate boilerplate, save you hours of work, and let you focus on more interesting problems. Invest time once in a solid template, then let the regenerate the code every time your data changes.</p><p>There are many template engines out there — FreeMarker, Thymeleaf, and Apache Velocity, to name a few. In this article, we’ll use Apache Velocity (<a href="https://velocity.apache.org/">https://velocity.apache.org/</a>) as our running example. We will touch on some impressive features of velocity, but the goal isn’t a deep dive into velocity, rather it is to show how you can streamline your workflow with templating.</p><p>Say we have an XML data source like so</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;exampleData&gt;<br>    &lt;packageName&gt;com.financial.trading&lt;/packageName&gt;<br><br>    &lt;messages&gt;<br>        &lt;message&gt;<br>            &lt;name&gt;Trade&lt;/name&gt;<br>            &lt;fields&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;tradeId&lt;/name&gt;<br>                    &lt;type&gt;string&lt;/type&gt;<br>                &lt;/field&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;securityId&lt;/name&gt;<br>                    &lt;type&gt;string&lt;/type&gt;<br>                &lt;/field&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;quantity&lt;/name&gt;<br>                    &lt;type&gt;decimal&lt;/type&gt;<br>                &lt;/field&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;price&lt;/name&gt;<br>                    &lt;type&gt;decimal&lt;/type&gt;<br>                &lt;/field&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;currency&lt;/name&gt;<br>                    &lt;type&gt;string&lt;/type&gt;<br>                &lt;/field&gt;<br>                &lt;field&gt;<br>                    &lt;name&gt;counterparty&lt;/name&gt;<br>                    &lt;type&gt;string&lt;/type&gt;<br>                &lt;/field&gt;<br>            &lt;/fields&gt;<br>        &lt;/message&gt;<br>    &lt;/messages&gt;<br>&lt;/exampleData&gt;</pre><p>We are going to use this data source to sketch out a template that can generate <strong>POJO</strong>s (<strong>P</strong>lain <strong>O</strong>ld <strong>J</strong>ava <strong>O</strong>bjects). The full demo can be found and clone from GitHub: — <a href="https://github.com/k4pran/Apache-Velocity-Demo">https://github.com/k4pran/Apache-Velocity-Demo</a></p><h4><strong>Step 1: Outline the package and class</strong></h4><p>First, point Velocity at your “golden source” (we’re using an XML message schema, but you could use JSON, YAML, etc.). In our example, each &lt;message&gt; element carries a list of fields (each with a name and type). For now we’ll focus on a single message to keep things simple.</p><p>With a template engine, you’re essentially sketching the file’s skeleton and telling it where to fill in variables. Let’s start by generating just the package declaration and an empty class:</p><pre>package $packageName<br><br>public class $className {<br><br>}</pre><p>In the snippet above, you see a bare‑bones Java class template. Velocity uses <strong>references </strong>marked by a dollar sign ($). These are the placeholders that are swapped out for the variables from your data source. For example, $packageName and ${className} tell Velocity, “Overwrite these placeholders with the packageName and className values from the context.” (We’ll dig into how to set up that context in the next section.)</p><p>Even at this early stage we can see how this template represents <em>any</em> class in <em>any</em> package.</p><h4><strong>Step 2: Generate a field</strong></h4><p>Next we want to generate the fields for our class, the java will look something like this:</p><pre>private String currency;<br>private double minQty;</pre><p>When you turn that into a template, ask yourself:</p><ol><li><strong>What stays the same?</strong><br> The private modifier.</li><li><strong>What changes?</strong><br> The type (String, double) and the field name (currency, minQty).</li></ol><p>In our template we sketch out the fixed and variable parts like so:</p><pre>private $resolvedType $resolvedName;</pre><ul><li>$resolvedType will resolve to the Java type (via theTypeResolver).</li><li>$resolvedName will resolve to the field name.</li></ul><h4><strong>Step 3: Loop over your fields</strong></h4><p>As each class can have any number of fields, you can’t hard‑code one line per field. Instead, Velocity’s #foreach directive lets you iterate over your $fields list:</p><pre>#foreach($field in $fields)<br>   #set($resolvedType = ${TypeResolver.resolveType($field)})<br>   #set($resolvedName = ${TypeResolver.resolveName($field)})<br>   private $resolvedType $resolvedName;<br>#end</pre><ul><li>#foreach($field in $fields) – steps through each field object in your data source.</li><li>Inside the loop, we call theTypeResolver helper to map the field’s metadata into a Java type ($resolvedType) and a valid Java identifier ($resolvedName).</li><li>Finally, we emit the private $resolvedType $resolvedName; line for each field.</li></ul><p>With this simple loop, your template now adapts to any<strong> </strong>number of fields.</p><p><strong>Side note:</strong> You’ll notice calls to TypeResolver in the template—that’s actually invoking your own Java code from within Velocity. This is where Velocity really shines: it can defer complex logic back to your application rather than trying to squeeze everything into the template. We’ll cover how to inject helpers like TypeResolver into your Velocity context later.</p><p>Velocity’s #macro directive lets you encapsulate reusable template logic into named blocks, cleaning up your code and to make the template easier to read:</p><pre>#macro(generateField $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    private $resolvedType $resolvedName;<br>#end</pre><p>You can now invoke that snippet anywhere in your template with:</p><pre>#generateField($field)</pre><p>Macros can even call other macros, or themselves recursively, making them perfect for handling nested structures.</p><h4><strong>Step 4: Adding getters and setters</strong></h4><p>We will now create two macros, one for getters and one for setters, we use macros to keep our template clean and concise:</p><pre>#macro(generateGetter $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedMethodPrefix = $StringUtils.capitalize(${TypeResolver.resolveName($field)}))<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    public $resolvedType get$resolvedMethodPrefix() {<br>        return $resolvedName;<br>    }<br>#end<br>##<br>#macro(generateSetter $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedMethodPrefix = $StringUtils.capitalize(${TypeResolver.resolveName($field)}))<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    public void set$resolvedMethodPrefix($resolvedType $resolvedName) {<br>        this.$resolvedName = $resolvedName;<br>    }<br>#end</pre><ul><li><strong>#macro(generateGetter $field)</strong><br> Resolves the field’s type and name, then generates a standard Java getter.</li><li><strong>#macro(generateSetter $field)</strong><br> Does the same for a Java setter.</li><li>## This is a simple technique to tell Apache to not print any whitespace, this allows us to space out the macros without newlines being included in our template.</li></ul><p>This uses the same techniques we used before, but you can now see them being used for more complex blocks of code. With just references, loops, and macros, you can assemble entire classes or even whole layers of your application.</p><h4><strong>Step 5: Finishing our template</strong></h4><p>Below is our complete Velocity template. It pulls in three macros for fields, getters, and setters, giving us our POJO template:</p><pre>#macro(generateField $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    private $resolvedType $resolvedName;<br>#end<br>##<br>#macro(generateGetter $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedMethodPrefix = $StringUtils.capitalize(${TypeResolver.resolveName($field)}))<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    public $resolvedType get$resolvedMethodPrefix() {<br>        return $resolvedName;<br>    }<br>#end<br>##<br>#macro(generateSetter $field)<br>    #set($resolvedType = ${TypeResolver.resolveType($field)})<br>    #set($resolvedMethodPrefix = $StringUtils.capitalize(${TypeResolver.resolveName($field)}))<br>    #set($resolvedName = ${TypeResolver.resolveName($field)})<br>    public void set$resolvedMethodPrefix($resolvedType $resolvedName) {<br>        this.$resolvedName = $resolvedName;<br>    }<br>#end<br>##<br>package $packageName;<br><br>public class ${className} {<br><br>#foreach($field in $fields)<br>    #generateField($field)<br>#end<br><br>#foreach($field in $fields)<br>    #generateGetter($field)<br><br>    #generateSetter($field)<br><br>#end<br>}</pre><p>This is a very basic template that can create a POJO from some very basic information, information we can derive from our xml.</p><h4><strong>Step 6: Wiring up the Velocity Engine</strong></h4><p>With your template ready, the final step is to configure Velocity, feed it your data, and let it spit out Java files. Here’s a view of the main snippets; the full demo is on GitHub: — <a href="https://github.com/k4pran/Apache-Velocity-Demo">https://github.com/k4pran/Apache-Velocity-Demo</a>.</p><pre>// 1) Configure and initialize Velocity<br>Properties props = new Properties();<br>// Tell Velocity to load .vm files from the classpath<br>props.setProperty(&quot;resource.loader&quot;, &quot;classpath&quot;);<br>props.setProperty(&quot;classpath.resource.loader.class&quot;,<br>    &quot;org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader&quot;);<br><br>VelocityEngine ve = new VelocityEngine(props);<br>ve.init();<br><br>// 2) Create a context and loop over your messages<br>VelocityContext ctx = new VelocityContext();<br>for (Message message : data.getMessages()) {<br><br>    // 3) Populate the context with keys that match your template references<br>    ctx.put(&quot;packageName&quot;, data.getPackageName());<br>    ctx.put(&quot;className&quot;, message.getName());<br>    ctx.put(&quot;fields&quot;,    message.getFields());<br><br>    // 4) Inject helper classes for complex logic<br>    ctx.put(&quot;TypeResolver&quot;, new TypeResolver());<br>    ctx.put(&quot;StringUtils&quot;,  new StringUtils());<br><br>    // 5) Load the template by filename (found via the classpath loader)<br>    Template tpl = ve.getTemplate(&quot;pojo-template.vm&quot;);<br><br>    File outDir = new File(&quot;generated&quot;);<br>    if (!outDir.exists()) {<br>        outDir.mkdirs();<br>    }<br><br>    // 6) Merge template + context → Java source file<br>    File outFile = new File(outDir, message.getName() + &quot;.java&quot;);<br>    try (FileWriter writer = new FileWriter(outFile)) {<br>        tpl.merge(ctx, writer);<br>    }<br>}</pre><ol><li><strong>VelocityEngine ve = new VelocityEngine(props); ve.init();</strong><br> We configure Velocity to use the <strong>ClasspathResourceLoader</strong> so it can find your .vm files in src/main/resources.</li><li><strong>VelocityContext ctx = new VelocityContext();</strong><br> The context is simply a map of <strong>key → value</strong> pairs. Keys become your template references (e.g. $className), and values can be primitives, objects, lists, or even helper classes (like TypeResolver).</li><li><strong>Populating the context<br>Data values</strong>: packageName, className, and the list of fields come straight from your parsed XML.</li><li><strong>Helpers</strong>:<br>TypeResolver and StringUtils are passed here so your template can call their methods instead of embedding complex logic.</li><li><strong>Loading the template<br></strong>ve.getTemplate(&quot;pojo-template.vm&quot;) looks on the classpath (thanks to our props) for that file.</li><li><strong>Merging</strong><br><strong>tpl.merge(ctx, writer) </strong>runs the template, replacing references ($…) with your context values and emitting the final Java code.</li></ol><p>When you run this loop, Velocity generates one .java file per Message in your XML—and all you had to write was the template and the code to run velocity.</p><p>If we run the demo project we get our autogenerated java class!</p><pre>package com.financial.trading;<br><br>public class Trade {<br><br>    private String tradeId;<br>    private String securityId;<br>    private double quantity;<br>    private double price;<br>    private String currency;<br>    private String counterparty;<br><br>    public String getTradeId() {<br>        return tradeId;<br>    }<br><br>    public void setTradeId(String tradeId) {<br>        this.tradeId = tradeId;<br>    }<br><br>    public String getSecurityId() {<br>        return securityId;<br>    }<br><br>    public void setSecurityId(String securityId) {<br>        this.securityId = securityId;<br>    }<br><br>    public double getQuantity() {<br>        return quantity;<br>    }<br><br>    public void setQuantity(double quantity) {<br>        this.quantity = quantity;<br>    }<br><br>    public double getPrice() {<br>        return price;<br>    }<br><br>    public void setPrice(double price) {<br>        this.price = price;<br>    }<br><br>    public String getCurrency() {<br>        return currency;<br>    }<br><br>    public void setCurrency(String currency) {<br>        this.currency = currency;<br>    }<br><br>    public String getCounterparty() {<br>        return counterparty;<br>    }<br><br>    public void setCounterparty(String counterparty) {<br>        this.counterparty = counterparty;<br>    }<br><br>}</pre><h3>Additional Tips</h3><h4>Embrace Partial Code Generation</h4><p>Even if your schema doesn’t let you generate a class 100% deterministically, templating can still deliver big results:</p><ul><li><strong>Automate the predictable 80%</strong><br> Let Velocity spit out all of the boilerplate — fields, accessors, even basic constructors.</li><li><strong>Flag the remaining 20%</strong><br> Insert clear placeholders (e.g. // TODO: implement mappings here) so developers know exactly where manual work is required.</li><li><strong>Fail fast</strong><br> Structure your template so that it doesn’t compile until those “gaps” are filled. That way, missing bits get caught in your build, not in production.</li></ul><h4>Leverage Fuzzy Matching for Complex Transforms</h4><p>When you’re mapping between two disparate schemas (say, converting from one API model to another), build in “fuzzy” logic:</p><ul><li><strong>Automate close matches</strong><br> If field names map with high confidence, wire them up automatically in your template.</li><li><strong>Fallback to placeholders</strong><br> When the fuzzy‐match score drops below your threshold, emit a <br>// REVIEW: no automatic match for &lt;sourceField&gt; comment instead of guessing.</li></ul><p>This hybrid approach keeps most of the work automated while leaving ambiguous parts of the code for human review.</p><h3>Conclusion</h3><p>Template engines like Apache Velocity aren’t just for rendering HTML — they’re powerful tools for automating any text‑based output, from configuration files to full Java classes. By defining a handful of simple macros, references, and loops, you can:</p><ol><li><strong>Eliminate boilerplate</strong> so you spend time on business logic rather than repetitive code.</li><li><strong>Ensure consistency</strong> across your POJOs, configs, or reports by driving everything from a single “golden source.”</li><li><strong>Adapt quickly</strong> when your schema or requirements change — just tweak your data model or TypeResolver, and regenerate everywhere.</li></ol><p>Whether you’re generating 100% of a class or automating just parts of it, templating could have a place in your build pipeline. Give it a try on your next project: start small with a couple of fields, evolve your macros over time, and you may be surprised how much it speeds up development and reduces bugs.</p><p>Happy templating!</p><h4>About the author</h4><p>Ryan McCauley is a Senior Software Engineer here at <a href="https://www.version1.com/">Version 1</a>.</p><blockquote><a href="https://www.version1.com/blog/my-journey-begins-at-version-1-a-fresh-perspective/">Learn more about Version 1</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816c1e72f46a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/curb-your-copy-paste-templating-with-apache-velocity-816c1e72f46a">Curb Your Copy-Paste: Templating with Apache Velocity</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>