<?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 Levon Tamrazov on Medium]]></title>
        <description><![CDATA[Stories by Levon Tamrazov on Medium]]></description>
        <link>https://medium.com/@levon_t?source=rss-7bcec4c903bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TRziq7gW2NDDQQpV.jpg</url>
            <title>Stories by Levon Tamrazov on Medium</title>
            <link>https://medium.com/@levon_t?source=rss-7bcec4c903bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:39:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@levon_t/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[Experiment Driven Refactoring]]></title>
            <link>https://medium.com/@levon_t/experiment-driven-refactoring-a054a43ff2c9?source=rss-7bcec4c903bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a054a43ff2c9</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Levon Tamrazov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 00:45:11 GMT</pubDate>
            <atom:updated>2019-09-25T00:45:11.776Z</atom:updated>
            <content:encoded><![CDATA[<p>Technical debt is the nemesis of every engineering organization. All organizations want to address it but most often encounter one of two barriers: time and knowledge. Time refers to being able to find cycles to prioritize this work. Knowledge is about understanding what should be done and having the confidence that it can be done successfully. This is often difficult since:</p><ul><li>By the time we get to a refactor, the code is tightly coupled with the rest of our application. Changes become sensitive because they risk breaking logic elsewhere.</li><li>Subject matter experts often don’t exist. This is especially true when we look at refactoring legacy systems that have not been touched for years on end. The people who wrote them and know the side effects are long gone.</li></ul><p>Yet the refactor needs doing (assume that we’ve ruled out all other options or work arounds). This leaves the engineers facing a difficult problem with little expertise and high business impact and thus risk. The rest of this post will discuss one such problem that we faced and how we used experimentation to do a safe, high impact refactor.</p><h3>Context</h3><p>One such problem that we faced was having to change out how service authorization worked in our distributed system. Without going into too much details, the context was like this:</p><ul><li>We had two types of authorization tokens: one to make calls against our API gateway (we’ll call this API Token), and another to make calls against our legacy services (we’ll call this Legacy Token)</li><li>Both our API gateway and our legacy auth server were capable of validating their respective tokens: the gateway would validate any API calls and the auth server would validate any legacy calls.</li><li>In addition to validating the token, the auth server would also fetch and return a ton of metadata about the user that was critical for downstream services. Only the auth server was capable of doing this.</li></ul><p>The goal was to deprecate the Legacy token so that we can better manage our users sessions. In theory, this seemed simple:</p><ul><li>Our API already did token validation on the API Token.</li><li>We had a middleware on all our systems responsible for authoring requests, it would currently call our auth server.</li><li>So all we had to do was modify the middleware to call our API gateway and validate the API Token instead of validating the Legacy Token.</li><li>Call our legacy server to fetch the required metadata</li></ul><p>#ez #shipit.</p><p>But how do we know that this actually works? This is our auth. This path would get hit on every single request and would bring down our whole app if we misstepped even a bit. Sure we had automated tests, and manual QA, but in a distributed system that takes you only so far, and you never know what curveballs prod can throw at you. We needed to know that what we did worked in prod without risking prod.</p><h3>Experiments To The Rescue</h3><p>The main piece that we worried about and wanted to obtain 100% confidence was that in the process of this refactor we did not deviate from the structure of the metadata returned by our legacy auth server. This was important because our downstream services used it in different ways and required some or all of it to work properly. We did not know all the ways that it was used. This is where we decided to create an experiment. The main flow is like this:</p><ol><li>Introduce a feature flag that allows you to run your new code for some percentage of requests</li><li>When the flag is on, keep running and executing the old logic, then ALSO run the the new logic but keep your program path relying on the old logic.</li><li>Compare the obtained from the old and new path and log the outcomes in a way that you can measure.</li></ol><p>So in our case we kept executing the old authorization logic, but for a portion of requests we would also execute the new way.</p><blockquote>The key to this is a dry execution: it would perform all the logic, but the code would not actually rely on it. However it would still produce results that we could then compare against the legacy path.</blockquote><ol><li>We would keep validating against the Legacy server, but for a portion of requests would make an additional call to the API Gateway to validate using the API Token, and compare results. We use a portion of requests because we didn’t want to pay the extra network hop required by the experiment on each request. It’s also safer in case we blew something up.</li><li>For the same portion, we would also make a call to fetch the metadata using a new API, and again compare the results against what we got using the legacy mechanism.</li><li>We would then record a counter with the results: match, nomatch, error and log detailed messages.</li></ol><p>This was completely safe to release to prod because the new mechanism while active was not actually controlling any logic. After a few weeks of running this we collected lots of data that helped us identify a few edge cases that we promptly addressed. At this point we were fully confident in our solution because we had prod data that proved its accuracy, and as such we proudly shipped it!</p><h3>Conclusion</h3><p>Experimentation is a great way to test your code in production without incurring the risk of doing so. This is extremely valuable in large refactors that have high impact on the business due to the ambiguity and the unknown factors that often accompany legacy code. This is especially true in systems where the subject matter experts are not available and the knowledge is scattered. There are however a few caveats that you should consider:</p><ol><li>Be mindful of the cost of running the experiment. In our case running this experiment incurred a cost of two extra network hops on every single request. It was not insignificant since it blocks our services, but in this case was manageable and worth it. This might not always be so.</li><li>Make sure the experiments can’t cause exceptions by wrapping and catching all possible failures. We want to be aware of these failures, but we don’t want them to prevent our main path from executing. In our case we abstracted the entire experiment and wrapped it into a “catch-all” block to ensure no exception gets through.</li><li>Experimentation works best when the code is stateless. This means that it has no side effects on your data or other persisted functionality. Without this you cannot derisk running it. In our case, no data was modified. We simply compared results of pure functions.</li></ol><p>Refactor with confidence!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a054a43ff2c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Vert.x Starter Guide: Part 3 — Integrating Guice]]></title>
            <link>https://medium.com/@levon_t/java-vert-x-starter-guide-part-3-integrating-guice-8ab1c52cf10?source=rss-7bcec4c903bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ab1c52cf10</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[vertx]]></category>
            <dc:creator><![CDATA[Levon Tamrazov]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 00:21:06 GMT</pubDate>
            <atom:updated>2017-02-17T00:21:06.522Z</atom:updated>
            <content:encoded><![CDATA[<p>Vert.x is a reactive framework for developing highly scalable non-blocking applications. This is the third post in a three part series. The previous two posts included:</p><ol><li><a href="https://medium.com/@levon_t/java-vert-x-starter-guide-part-1-30cb050d68aa">Introduction to Vert.x</a></li><li><a href="https://medium.com/@levon_t/java-vert-x-starter-guide-part-2-worker-verticles-c49866df44ab">Worker Verticles</a></li></ol><p>This post will have much less to do with Vert.x, and will instead focus on how to integrate it with Guice dependency injection. This is <a href="https://github.com/ltamrazov/vertx-starter-guide/tree/part-2">the repo</a> to the code where we left of last time. The code in this post, can be found <a href="https://github.com/ltamrazov/vertx-starter-guide/tree/part-3">here</a>. Lets start.</p><h3>Vert.x Guice</h3><p>Vert.x does not yet have built-in dependency injection. Since you can’t hope to develop a maintainable and testable application without it, we need a solution and since we are using Java, that solution is Guice. Guice is a great <a href="https://github.com/google/guice">dependency injection library</a> developed by Google. A Vert.x plugin for Guice has already been build by ef-labs, <a href="https://github.com/ef-labs/vertx-guice">find it here</a>. All the credit for the awesome work on Guice integration goes to them. This post will simply demonstrate how to incorporate it into your application. Add this dependency to your project:</p><pre><em>build.gradle:</em></pre><pre>compile &#39;com.englishtown.vertx:vertx-guice:2.3.1&#39;</pre><h3>Service Binder</h3><p>The first thing we need to do is create a binder that will configure Guice to provide all our classes. To do that, we need to create a class that extends AbstractModule. The binder’s job is to tell Guice how to construct all the classes that we need and to bind implementations that we want to use for particular interfaces we specified in our constructors. It looks like this:</p><pre><em>ServiceBinder.java:</em></pre><pre>public class ServiceBinder extends AbstractModule{<br><br>    <em>@Provides @Singleton<br>    </em>public HelloController provideController(Vertx vertx, <br>        HelloWorld service)<br>    {<br>        return new HelloController(vertx, service);<br>    }<br><br>    <em>@Provides @Singleton<br>    </em>public HelloWorld provideService(){<br>        return new HelloWorld();<br>    }<br><br>    <em>@Provides @Singleton<br>    </em>public AppConfig provideAppConfig(){<br>        return new AppConfig(30, 30);<br>    }<br><br>    <em>@Override<br>    </em>protected void configure() {<br><br>    }<br>}</pre><p>The @Provides annotation marks the method as a provider, and @Singleton lets Guice know that we want it to use a single instance of whatever it provides throughout application (Singleton).</p><p>The second thing we have to do is override the configure method. This method gets called when the module is instantiated, and it can include any additional configurations. We can actually just put all our configurations that we did as methods, inside the configure method, but I find it more readable and neater to implement the methods, so our configure is empty.</p><h3>Main Class</h3><p>Before we used theServiceLauncher class to deploy our verticle. This relied on our build configuring the Vert.x Launcher class and pointing it to our ServiceLauncher. This works great, but if we want to manually deploy our verticle, we need a main class. This class will create a Vert.x instance, and use a helper method to deploy our verticles using Guice. This is our Main:</p><pre><em>Main.java:</em></pre><pre>public class Main {<br><br><br>    public static void main(String[] args){<br>        Vertx vertx = Vertx.vertx();<br>        deploy(vertx, ServiceLauncher.class,<br>                                  new DeploymentOptions());<br>    }<br></pre><pre>    private static Future&lt;Void&gt; deploy(Vertx vertx, Class verticle,<br>        DeploymentOptions opts)<br>    {<br>        Future&lt;Void&gt; done = Future.future();<br>        String deploymentName = &quot;java-guice:&quot; + verticle.getName();<br>        JsonObject config = new JsonObject()<br>                .put(&quot;guice_binder&quot;, ServiceBinder.class.getName());<br><br>        opts.setConfig(config);<br><br>        vertx.deployVerticle(deploymentName, opts, r -&gt; {<br>              // handle success/failure<br>        });<br><br>        return done;<br>    }</pre><pre><br>    private static class ServiceLauncher extends AbstractVerticle{<br>        private AppConfig appConfig;</pre><pre>        <em>@Inject<br>        </em>public ServiceLauncher(AppConfig appConfig) {<br>            this.appConfig = appConfig;<br>        }<br><br>        /**<br>         * Start method uses CompositeFuture to deploy all required <br>         * verticles<br>         *<br>         * <em>@param </em>done<br>         */<br>        <em>@Override<br>        </em>public void start(Future&lt;Void&gt; done) {<br>            // start your verticle here<br>        }<br>    }<br>}</pre><ol><li>The main method simply creates a Vert.x instance, and uses a helper method to deploy our static verticle launcher class. Vertx.vertx() can also take options that specify different things like number of instances.</li><li>Next is our helper method, this is the important part that integrates the Guice library. The first thing we do there, is amend the name of the verticle by pre-pendingjava-guice. Vert.x allows us to create and register verticle factories that are responsible for instantiating verticles before deployment. The library we are using, provides a factory that integrates Guice with the verticle if its name starts with java-guice. Second, we specify our ServiceBinder in the deployment options, thus letting Guice know where to find it.</li><li>Last is our ServiceLauncher . It is identical to what it was, with the exception of a constructor. We added the constructor with the @Inject Guice annotation. This makes it possible for the verticle factory to instantiate this verticle, and lets Guice know to inject the dependencies we need. In this case, it is simply a dummy AppConfig dependency. Its important to note that the ServiceLauncher, also needs to use our helper method to deploy our verticles. This is because <strong>you need to specify the ServiceBinder and amend the verticle name for each verticle where you want to use Guice</strong>.</li></ol><p>Thats it. Now anywhere inside our verticles we can use Guice dependency injection. We’ve modified all code to reflect this, injecting the dependencies into verticles, controllers, and our service class. For example, the HelloController constructor looks like this:</p><pre><em>@Inject<br></em>public HelloController(Vertx vertx, HelloWorld service){<br>    this.vertx = vertx;<br>    this.service = service;<br>}</pre><p><strong>Note: </strong>We don’t need to create a Vertx provider inside the ServiceBinder because the Vert.x Guice library already has the Vert.x provider that provides the Vert.x instance you use to deploy the verticle.</p><h3>Conclusion</h3><p>This series explored application architecture using Vert.x. We discussed high throughput single verticle structure, multi-verticle structure for independent scalability, and Guice integration for dependency injection. I will continue to explore Vert.x, and definitely encourage you to check it out as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ab1c52cf10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Vert.x Starter Guide — Part 2: Worker Verticles]]></title>
            <link>https://medium.com/@levon_t/java-vert-x-starter-guide-part-2-worker-verticles-c49866df44ab?source=rss-7bcec4c903bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49866df44ab</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[vertx]]></category>
            <dc:creator><![CDATA[Levon Tamrazov]]></dc:creator>
            <pubDate>Fri, 03 Feb 2017 14:49:48 GMT</pubDate>
            <atom:updated>2017-02-03T14:49:48.428Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second post in a 3 part series on Vert.x in Java. Vert.x is a reactive framework for developing asynchronous applications. For a more thorough introduction checkout <a href="https://medium.com/@levon_t/java-vert-x-starter-guide-part-1-30cb050d68aa#.9i5hxrzag">Part 1 of this series</a>. This post will expand on our HelloWorld application by adding worker verticles and introducing the Vert.x event bus.</p><p><a href="https://github.com/ltamrazov/vertx-starter-guide/tree/part-1">This repo</a> contains the code we wrote so far, feel free to clone it to follow along. You can also find the full <a href="https://github.com/ltamrazov/vertx-starter-guide/tree/part-2">code for Part 2</a> here.</p><h3>So Far…</h3><p>In the first part of this series, we deployed our service on a single server verticle. This was an event loop verticle that did all of its processing using executeBlocking. Behind the scenes, this method launches a worker thread to execute the code you give it. This thread is grabbed from a worker pool that every event loop verticle has. We can configure this pool when we deploy the verticle by using setWorkerPoolSize option in DeploymentOptions.</p><p>This technique allows us to nicely process our requests asynchronously. However, it couples our business logic with our server and limits our scaling and deployment options. Enter worker verticles.</p><h3>Hello Worker</h3><p>Workers are another type of verticle in Vert.x that are designed to execute blocking code. Unlike the regular verticles that run on the <em>event loop thread,</em> workers run on <em>worker threads</em> from a preconfigured pool. Because they are not part of the event loop, they can block while doing their processing. They can communicate with other verticles using the Vert.x event bus.</p><p>Now the cool part is since they are verticles, we can deploy them completely independently from other verticles. In fact we can deploy more instances written in a completely different language running on a different, beefier machine. It encapsulates all our business logic and completely segregates it from our server.</p><h3>Event Bus Producer</h3><p>First we add a new end point in our router that will send a message over the event bus to whoever might be listening. The event bus has two ways of communication:</p><ol><li>send — This is two way communication that allows us to set a reply handler that will process the response from our consumer.</li><li>publish — This is a send-and-forget type of communication that can be used when you don’t care about a response. You are simply publishing an event that you need other processes to be aware of.</li></ol><p>Our new handler looks like this:</p><pre><em>.../web/HelloController.java</em></pre><pre>private void getGreetingW(RoutingContext ctx){<br>    String data = new JsonObject()<br>            .put(&quot;name&quot;, ctx.request().getParam(&quot;name&quot;))<br>            .encode();</pre><pre>    vertx.eventbus().send(Events.GREET, data, res -&gt; {<br>        handleEventBusResponse(res, ctx);<br>    });<br>}</pre><p>All messages are sent as buffers, and by default Vert.x allows sending String and Buffer types. For any other type, Vert.x looks up a MessageCodec that specifies serialization into / from a buffer:</p><pre>vertx.eventBus().send(<em>event, SomeObject</em>, handler)</pre><p>The code above, would require us creating a MessageCodecfor SomeObject. Since Vert.x is multi-tenant in terms of languages, it is encourages to use JSON as your message format since it can be easily parsed by any language.</p><p>We created another response handler to process our event bus responses and modified our <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-2/src/main/java/com/ltamrazov/vertxstarterguide/web/GlobalHandlers.java">global error handler</a> to catch ReplyException which is the exception that is produced from our message consumers when they fail the response (see below). That code is self explanatory so is omitted from here, but I encourage you to check it out <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-2/src/main/java/com/ltamrazov/vertxstarterguide/web/HelloController.java">in the repo</a>.</p><h3>Setting Up the Worker Verticle</h3><p>Worker is structured just like any other verticle, except it will use the event bus consumer to listen for messages and reply to them. Here is what the start method looks like:</p><pre><em>.../service/HelloWorker.java</em></pre><pre><em>@Override<br></em>public void start(Future&lt;Void&gt; done){<br>    MessageConsumer&lt;String&gt; consumer = <br>                    vertx.eventBus().consumer(Events.<strong><em>GREET</em></strong>);<br><br>    consumer.handler(m -&gt; {<br>        JsonObject data = new JsonObject(m.body());<br>        Greeting retval = service.greet(data.getString(&quot;name&quot;));</pre><pre>        try{<br>            m.reply(Json.encode(retval));<br>        }catch (EncodeException e){<br>            m.fail(HttpResponseStatus.<strong><em>INTERNAL_SERVER_ERROR</em></strong>.code(), <br>                     &quot;Failed to encode data.&quot;);<br>        }<br>    });<br><br>    done.complete();<br>}</pre><p>This is a verticle, so it must extend the AbstractVerticle and override the start method. The interesting part is in the event bus:</p><pre>MessageConsumer&lt;String&gt; consumer = <br>                    vertx.eventBus().consumer(Events.<strong><em>GREET</em></strong>);</pre><p>This code creates a consumer on the event bus that listens on the Greet event. The type of consumer specifies that we are expecting a String message. The next part, sets a handler for this event:</p><pre>consumer.handler(m -&gt; { ... });</pre><p>The body of the message can be accessed via m.body(). This will be of the type specified for this consumer. Here you can do any blocking processing, and once you are done, call m.reply() to send the response back over the event bus. Should it fail, you can use m.fail() to indicate an error with a specified code and message. Because the error occurs in another verticle, <strong>it is important to catch all exceptions and fail over</strong> to make sure our server gets a reply.</p><h3>Deploying Our Verticle</h3><p>Finally we modify our ServiceLauncher to deploy all verticles:</p><pre><em>.../ServiceLauncher.java:</em></pre><pre><em>@Override<br></em>public void start(Future&lt;Void&gt; done){<br>    int WORKER_POOL_SIZE = 20;<br><br>    DeploymentOptions serverOpts = new DeploymentOptions()<br>            .setWorkerPoolSize(WORKER_POOL_SIZE);<br><br>    DeploymentOptions workerOpts = new DeploymentOptions()<br>            .setWorker(true)<br>            .setInstances(WORKER_POOL_SIZE)<br>            .setWorkerPoolSize(WORKER_POOL_SIZE);<br><br>    CompositeFuture.all(<br>            deploy(ServerVerticle.class.getName(), serverOpts),<br>            deploy(HelloWorker.class.getName(), workerOpts)<br>    ).setHandler(r -&gt; {<br>        if(r.succeeded()){<br>            done.complete();<br>        }<br>        else {<br>            done.fail(r.cause());<br>        }<br>    });<br>}</pre><p>A few things to note here:</p><ol><li>We use setWorker(true) in the workerOpts to indicate that this verticle should be deployed as a worker. By default <strong>worker verticle instance will only be executed by one thread at any one time (it is not concurrent).</strong> This means that you will not be processing more requests that the number of verticle instances no matter how large your thread pool is, so make sure those are equal. Alternatively you can use setMultiThreaded(true) to make this a <strong>multi threaded worker</strong>. This will allow several threads to run on the same instance concurrently, <strong>but then make sure your workers are thread safe</strong>.</li><li>We use CompositeFutureto deploy our verticles at once. This will insure that our deployment succeeds only if all verticles get deployed successfully.</li><li>deploy is a helper method that simply wraps the vertx.deployVerticle method call. You can see the implementation <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-2/src/main/java/com/ltamrazov/vertxstarterguide/ServiceLauncher.java">here</a>.</li></ol><h3>Conclusion</h3><p>We now have a worker verticle that can be used to offload any heavy processing from our server. In our case we deploy it together with our main verticle, but it can be deployed completely independently on another machine, with a different number of instances, and even a different language.</p><p>Thats it for this post. Stay tuned for Part 3 that will talk about using Guice to setup dependency injection in our code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49866df44ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Vert.x Starter Guide — Part 1]]></title>
            <link>https://medium.com/@levon_t/java-vert-x-starter-guide-part-1-30cb050d68aa?source=rss-7bcec4c903bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/30cb050d68aa</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[vertx]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Levon Tamrazov]]></dc:creator>
            <pubDate>Sat, 28 Jan 2017 22:26:34 GMT</pubDate>
            <atom:updated>2017-01-29T13:29:55.384Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Vert.x</h3><p>Vert.x is an asynchronous toolkit for writing applications running on the JVM. At its heart are two concepts:</p><ol><li><strong>Event Loop</strong> — This is the heart of Vert.x and allows clients to write 100% non-blocking, reactive code through handlers (or callbacks). For those familiar with NodeJs this will feel very similar.</li><li><strong>Verticles</strong> — These are encapsulated parts of your application that can be run completely independently of each other and communicate through an event bus. They can be used to either segregate code into logical sections, or be deployed as a pool of workers to handle computation intensive tasks. More on these later.</li></ol><p>This asynchronous architecture allows Vert.x applications to easily scale and handle large amounts of throughput. As an example, we measured a mock service that simply hits Redis, does some light processing and returns the results. Service running Spring, was able to handle at most around 1K requests/sec. The Vert.x service was able to process up to 5K requests/second (this was on a very light weight machine, but still).</p><p>Since Vert.x runs on the JVM, it is multi-threaded. Each Vert.x instance has a pool of worker threads that it uses to either execute non-blocking code on the event loop, or deploy worker verticles that each run on their own worker threads.</p><p>This guide is for beginners and won’t include an in-depth technical explanation of Vert.x architecture. Vert.x has <a href="http://vertx.io/docs/vertx-core/java/">excellent documentation</a> that you can explore on your own for an in-depth API description. Further more, Tim Fox published a <a href="https://github.com/vietj/vertx-materials/blob/master/src/main/asciidoc/Demystifying_the_event_loop.adoc">great guide</a> focusing on the event loop in particular.</p><p>Lastly, Vert.x is a <em>toolkit</em>, meaning it’s very lightweight and can be used either alone or in conjunction with any other framework of your choice (we’ve combined it with Spring and were able to take advantage of both the incredible throughput of Vert.x and all the infrastructure of Spring).</p><h3>Quick Start — Blown Out HelloWorld</h3><p>This section will go through basic application structure using a single vertical. Later sections will cover a worker-vertical structure.</p><p>Repository to this code can be found here: <a href="https://github.com/ltamrazov/vertx-starter-guide/tree/part-1">https://github.com/ltamrazov/vertx-quickstart-part1</a></p><p>Vertx is very explicit about borrowing heavily from NodeJs. Therefore the application structure will also reflect that and contain the following main components:</p><ol><li><strong>Server Verticle</strong> — will configure the HTTP server and setup the router</li><li><strong>Controller </strong>— handler methods that map routes to the service layer</li><li><strong>Services </strong>— contain all business logic and “actual work”.</li><li><strong>Service Launcher </strong>— will be responsible for configuring and deploying all verticles</li></ol><h3>Gradle Dependencies</h3><p>Add the following to your dependencies and you’re good to go:</p><pre>build.gradle:</pre><pre>compile &#39;io.vertx:vertx-core:3.3.3<br>compile &#39;io.vertx:vertx-web:3.3.3</pre><h3>Overview</h3><p>The golden rule of Vert.x is:</p><blockquote>Don’t block the event loop</blockquote><p>Our main verticle will be the event loop verticle and will be the entry point to our API. Any code that we implement on it, must be non-blocking to keep the event loop running.</p><p>We will do this by wrapping our handlers in a method called executeBlocking . It takes blocking code and a handler, then fires off a worker thread to complete the work in the background and call the handler when its done. This makes our app easy to structure / build, since we can safely write blocking code inside our business logic knowing that our controllers will execute it asynchronously.</p><h3>Services</h3><p>Our main service will have nothing to do with Vert.x. This way, we can decouple Vert.x from our business logic. Of course if you’d like you can incorporate Vert.x non-blocking libraries here as well (such as their Redis client), but it is unnecessary since we know all our handlers will be asynchronous.</p><pre>src/main/java/service/HelloWorld.java:</pre><pre>package com.ltamrazov.vertxstarterguide.service;</pre><pre>import com.ltamrazov.vertxstarterguide.domain.Greeting;<br><br>public class HelloWorld {<br><br>    public HelloWorld(){<br>        // initiate your class in any way you like<br>    }<br><br>    public Greeting greet(String name){<br>        try{<br>            Thread.sleep(1500);<br>            return new Greeting(name);<br>        }catch (InterruptedException e){<br>            throw new CustomException(&quot;This is a safe message&quot;);<br>        }<br>    }<br>}</pre><p>The only thing to note here is that we are catching the general exception, and throwing our own custom exception. We are doing this so that the global error handler will be aware that the exception is our own and that the message is safe to display. Here is the <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-1/src/main/java/com/ltamrazov/vertxstarterguide/domain/Greeting.java">Greeting domain model</a> and our <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-1/src/main/java/com/ltamrazov/vertxstarterguide/exceptions/CustomException.java">CustomException</a> that are used.</p><h3>Controller</h3><p>Our controller is where we start using Vert.x to implement asynchronous handlers. You can find the <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-1/src/main/java/com/ltamrazov/vertxstarterguide/web/HelloController.java">full code here</a>, below I’ve outlined the main parts.</p><pre>src/main/java/com.ltamrazov.vertxstarterguide/web<br>/HelloController.java</pre><pre>/*<br> * We inject Vertx and HelloWorld service. We need Vertx to <br> * construct our router and do async calls.<br>*/<br>public HelloController(Vertx vertx, HelloWorld service){<br>    this.vertx = vertx;<br>    this.service = service;<br>}</pre><pre>/* <br> * Get router method will allow our HTTP server to get a router<br> * that includes all the APIs for this controller. It will make<br> * our server nice and neat and not have to worry about end points<br>*/<br>public Router getRouter(){<br>    if(router == null){<br>        router = Router.router(vertx);<br>        router.get(API.GREETING).handler(this::getGreeting);<br>    }</pre><pre>    return router;<br>}</pre><pre>/*<br> * This is our main handler, it makes use of executeBlocking to make<br> * the call to our service asyncronous.<br>*/<br>private void getGreeting(RoutingContext ctx){<br>    String name = ctx.request().getParam(&quot;name&quot;);</pre><pre>    vertx.executeBlocking(<br>        fut -&gt; { fut.complete(service.greet(name)); },<br>        false,<br>        res -&gt; { handleAsyncResponse(res, ctx); }<br>    );<br>}</pre><pre>/*<br> * This is our helper method for handling responses.<br>*/<br>private void handleAsyncResponse(AsyncResult&lt;Object&gt; res, <br>    RoutingContext ctx)<br>{<br>    if(res.succeeded()){<br>        try { ctx.response().end(Json.encode(res.result())); }<br>        catch(EncodeException e){<br>            ctx.fail(new RuntimeException(&quot;Failed to encode&quot;);<br>        }<br>    } else {<br>        ctx.fail(res.cause());<br>    }<br>}</pre><p>The interesting part here is the actual handler. All handlers take RoutingContext which contains all the request / response information. But the real work happens inexecuteBlocking. It takes 3 arguments:</p><ol><li>Lambda that takes a future and contains blocking code. This code will be executed on a worker thread in the background. You have to resolve the future to trigger the handler. Any exceptions that happen in this first block, will automatically trigger future.fail() which is why we are not catching them.</li><li>Boolean that indicates if the operations are to be executed in order. <strong>By default it is set to </strong><strong>true meaning that blocking code will be executed in sequence, one at at time</strong>. Setting it false makes it execute code <em>unordered</em>. One catch, is <strong>you must make sure your code is thread safe and can be executed in this manner</strong>.</li><li>Handler that gets called when the future in the first argument is resolved. At this point we are back in the event loop thread<strong>, so make sure not to have any blocking code here</strong>. <strong>Lastly exceptions that happen here will not be failed over to a failure handler, so make sure to trigger fail when necessary.</strong></li></ol><p>Our common response handler, simply sends the response in case of success, or does a failover using RoutingContext.fail() in case of failure. The failover will trigger our <a href="https://github.com/ltamrazov/vertx-starter-guide/blob/part-1/src/main/java/com/ltamrazov/vertxstarterguide/web/GlobalHandlers.java">global error handler</a> .</p><h3>Server Verticle</h3><p>We will use an event loop verticle to create and start our server. It looks like this:</p><pre>public class ServerVerticle extends AbstractVerticle{</pre><pre>    <em>@Override<br>    </em>public void start(Future&lt;Void&gt; future) throws Exception{<br>        int PORT = 8181;<br>        HelloWorld service = new HelloWorld();<br>        HelloController controller = <br>               new HelloController(vertx, service);<br>        <br>        Router helloRouter = controller.getRouter();<br>        <br>        Router mainRouter = Router.router(vertx);<br>        mainRouter.route().consumes(&quot;application/json&quot;);<br>        mainRouter.route().produces(&quot;application/json&quot;);<br><br>        Set&lt;String&gt; allowHeaders = getAllowedHeaders();<br>        Set&lt;HttpMethod&gt; allowMethods = getAllowedMethods();</pre><pre>        mainRouter.route().handler(BodyHandler.create());<br>        mainRouter.route().handler(CorsHandler.create(&quot;*&quot;)<br>                .allowedHeaders(allowHeaders)<br>                .allowedMethods(allowMethods));<br><br>        mainRouter.mountSubRouter(API.<strong><em>HELLO_API</em></strong>, helloRouter);<br>        mainRouter.get(API.<strong><em>LB_CHECK</em></strong>)<br>                  .handler(GlobalHandlers::lbCheck);</pre><pre>        mainRouter.route().failureHandler(GlobalHandlers::error);<br><br>        // Create the http server and pass it the router<br>        vertx.createHttpServer()<br>            .requestHandler(mainRouter::accept)<br>            .listen(PORT, res -&gt; {<br>                if(res.succeeded()){<br>                    System.<strong><em>out</em></strong>.println(&quot;Server up. Port: &quot; + PORT);<br>                    future.complete();<br>                }<br>                else{<br>                    System.<strong><em>out</em></strong>.println(&quot;Failed to launch server&quot;);<br>                    future.fail(res.cause());<br>                }<br>            });<br>    }</pre><p>Points:</p><ol><li>All verticles must extend the AbstractVerticle class and override a single method start. This method can take a future to take advantage of the callback pattern when deploying this verticle.</li><li>In the top part we simply initiate our controller and get the router.</li><li>We then create another router to be our main. This is the one we use to set global configurations and apply the body parser and CORS handlers that both come with Vert.x.</li><li>We mount our HelloRouter on a specific endpoint on the main router. We then set all the global routes on our main router. These include a health check and our error handler.</li><li>We deploy our server, and resolve the future on completion / failure.</li></ol><p>An important point here is that <strong>Vert.x will attempt to match routes in the order they were added</strong>. If we had any middleware that we wanted applied to all routes, we would set it before we mounted our sub router. The same route can have multiple handlers, and you can call the next handler using the RoutingContext.next method.</p><p>Failure handler, is just another handler, but gets added using a special method failureHandler that lets Vert.x know to use it in case of failover.</p><h3>Service Launcher</h3><p>Lastly our ServiceLauncher will be responsible for launching all our verticles (in this case just one). It looks like this:</p><pre>public class ServiceLauncher extends AbstractVerticle{</pre><pre>    <em>@Override<br>    </em>public void start(Future&lt;Void&gt; done){<br>        int WORKER_POOL_SIZE = 100;<br>        <br>        DeploymentOptions opts = <br>            new DeploymentOptions()<br>                    .setWorkerPoolSize(WORKER_POOL_SIZE);<br>        <br>        String verticle = ServerVerticle.class.getName();<br>        <br>        vertx.deployVerticle(verticle, opts, res -&gt; {<br>            if(res.failed()){<br>                System.<strong><em>out</em></strong>.println(&quot;Failed to deploy verticle&quot;);<br>                done.fail(res.cause());<br>            }<br>            else {<br>                System.<strong><em>out</em></strong>.println(&quot;Deployed: &quot; + verticle);<br>                done.complete();<br>            }<br>        });<br>    }<br>}</pre><ol><li>ServiceLauncher is just another verticle, so like others it must extend the AbstractVerticle and override start.</li><li>DeploymentOptions is what contains all the configurations for a verticle. Here you can mark verticles as workers, set number of instances, control worker pool size, etc… By default all verticles are event loop verticles, so we don’t need to change that. We set the worker pool size to 100. This is the thread pool that our executeBlocking will use to run blocking code. If we wanted, we could deploy multiple instances of this verticle by setting the instances parameter. We could, for example, deploy an instance per core.</li><li>Finally we call deployVerticle with the options and the verticle name to launch it. Because we implemented the async start in our server verticle, we can make sure it launched successfully here. This becomes especially neat when we deploy multiple verticles, then we can use CompositeFuture to make sure all of them launch successfully.</li></ol><h3>Conclusion</h3><p>Thats it! This is a basic setup to run a reactive application in Vert.x. To compile it, make sure to specify Vert.x Launcher as the main class, and our ServiceLauncher as the main verticle:</p><pre>build.gradle:</pre><pre>jar {<br>    // by default fat jar<br>    archiveName = &#39;vertx-starter-guide-fat.jar&#39;<br>    from { configurations<br>               .compile<br>               .collect { it.isDirectory() ? it : zipTree(it) }<br>    }</pre><pre>    manifest {<br>        attributes &#39;Main-Class&#39;: &#39;io.vertx.core.Launcher&#39;<br>        attributes &#39;Main-Verticle&#39;:         <br>                   &#39;com.ltamrazov.vertxstarterguide.ServiceLauncher&#39;<br>    }<br>}</pre><p>If you are using IntelliJ, you can also configure a runner:</p><ol><li>Run &gt; Edit Configurations &gt; + &gt; Application</li><li>Give a name to your runner</li><li>Under main class, type : <em>io.vertx.core.Launcher</em></li><li>Under Program Arguments type the package path to your Service Launcher: <em>Run com.ltamrazov.vertxstarterguide.ServiceLauncher</em></li><li>Click save</li></ol><p>Thats it, now run it using the ‘Run’ button.</p><p>As I mentioned, this was meant to be a very beginner friendly introduction to Vert.x and an example of how to setup a single verticle app. Hopefully it got you interested enough to further explore on your own.</p><p>Stay tuned for a follow up article on how to setup an app using worker verticles and the Vert.x event bus.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30cb050d68aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>