<?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 Hannes Moser on Medium]]></title>
        <description><![CDATA[Stories by Hannes Moser on Medium]]></description>
        <link>https://medium.com/@hannesmoser?source=rss-ec5bea6e253e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*DwqjG57wy-fcL1Wae0VGbg.jpeg</url>
            <title>Stories by Hannes Moser on Medium</title>
            <link>https://medium.com/@hannesmoser?source=rss-ec5bea6e253e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:12:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hannesmoser/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[Faster inter-service communication with streams]]></title>
            <link>https://medium.com/@hannesmoser/speedup-inter-service-communication-c144372038b1?source=rss-ec5bea6e253e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c144372038b1</guid>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[apm]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Hannes Moser]]></dc:creator>
            <pubDate>Sun, 04 Aug 2019 17:32:01 GMT</pubDate>
            <atom:updated>2019-08-12T02:09:19.194Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3Wuz9XBaIo8O7VHuWuCBw.png" /></figure><p>A system of distributed services can provide some benefits over monoliths and we embrace the idea of small services at <a href="https://www.spurtli.com/">Spurtli</a>. In this article I’d like to bring attention to a performance problem that we recently had in one of our projects and how we solved it. Inter-service communication is hard, and it was even before microservices were a thing. Lots of three-tier architectures suffer from the same problem as described below, so this applies to monoliths too.</p><p><strong>tl;dr</strong> Use streams to speedup inter-service data transfer.</p><h4>Change is in inevitable, so better embrace than fight it.</h4><p>Most of the applications I had luck to work on over the last decade did not follow any idiomatic design or architecture. Development of complex applications is first and foremost an evolutionary process, and over time you just adopt better patterns and you use better tools (as a developer and a team).</p><p>But first, we need to go back in history. About 10 years ago, on-premise content management systems were <em>the thing</em> and every company built some sort of media asset pipeline into their system. Those systems either used a library or command-line tool to fulfill transcoding tasks and most of the time those tools were not written in any of the popular high-level programming languages used to build the application (PHP, Ruby, Java …).</p><p>Whether you need to transcode an uploaded video file or resize an image to generate a thumbnail for your website, the tools are not designed to be used by web applications exclusively. They are usually maintained by another team or they are best case an Open Source project. It’s also likely that developing such library on your own, will never pay off, even if you are a big shop and have enough developers around.<br>Up until today many projects have been relying on libs such as <a href="https://www.php.net/manual/en/book.image.php">GD</a> for PHP which was supported by many pre-cloud era webhosting firms. If you need something more powerful and efficient, you have another choice with <a href="https://imagemagick.org/index.php">ImageMagick</a>, and <a href="https://ffmpeg.org/">ffmpeg</a> is the heart and soul of a lot of media asset pipelines that need to support video.</p><h4>Call a service by its command line interface</h4><p>The easiest way to use any of the above mentioned programs and libs is by just using their command line interface. but it is likely to cause problems once the files are getting bigger. Though some people don’t consider those tools a service, they do have some characteristics that clearly show that they are services:</p><ul><li>They have a defined contract</li><li>They are doing one particular thing</li><li>… and you know nothing about its internal processes</li></ul><pre>mogrify  -format gif -path thumbs -thumbnail 100x100 *.jpg</pre><p>The snippet above is an example from the ImageMagick website, but if you look through the source of a (legacy) system, you might find a ton of similar CLI instructions. It works perfectly fine, it transforms images and copies them into a new directory. Also, most high-level programming languages and runtimes define an API to handle (sub-)processes and process communication. For example, Ruby has at least <a href="https://stackoverflow.com/questions/6338908/ruby-difference-between-exec-system-and-x-or-backticks">5 different ways</a> to execute a system program.<br>However, this also highlights a potential problem. If you have several options, it’s hard to pick and use the right one. This might also be the reason why there are so many <em>thin wrappers</em>, to simplify the usage of those programs. Just see the list of <a href="https://rubygems.org/search?utf8=%E2%9C%93&amp;query=ffmpeg">ffmpeg Rubygems</a>.</p><p>I strongly believe there is indeed a good way to use system programs. As long as you rely on the foundations of the UNIX system, you likely use the program exactly the way it was designed. Learning how to use <em>STDIN </em>and<em> STDOUT</em> properly and find a good way (even a lib) to handle flags and arguments is nearly everything you need.<br>You might also want to take it one step further and think about using system programs in the context of the <em>request/response</em> loop. Whether you use a micro framework or a full-blown MVC framework, its likely that you have some sort of <em>parameters</em> that define the behaviour of the request flow (e.g. query parameters). It is considered a best practice to sanitize and validate input and passing its values around our system afterwards (e.g. insert a row in your relational database). The same pattern can be used to invoke a system program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5c4cb565c074ecf91bf1337ac3969dd/href">https://medium.com/media/d5c4cb565c074ecf91bf1337ac3969dd/href</a></iframe><p>Simple? Yes, and this contrived example might work for some cases, but it is likely to cause problems once the files are getting bigger. This call is going to capture the <em>STDOUT</em> from the ffmpeg program and stores it in-memory (the output variable).<br>It has another flaw, the process that handles the request of the app (in this case it’s a Rails app) cannot be used for anything else as long as the processing of the video file goes on. The commonly accepted best practice is to keep request/response cycles as short as possible and to offload heavy tasks to a worker queue. Though, in certain situations this is not an option, when you absolutely need to create something on the fly. So, how do we handle this, you might be wondering?</p><h4>Call another service over network</h4><p>This is another, very popular, way of handling some work outside of your (primary) application. In a complex system, different services fulfill different roles. You might have a database, a cache or a search engine running behind the scenes. Most of the time you communicate with those services over the network or a similar concept (socket). This is what we usually call a <a href="https://12factor.net/backing-services">backing service</a>. Nevertheless, the world of microservices also requires communication between high-level services or even between full apps.</p><p>At <a href="https://www.spurtli.com/">www.spurtli.com</a>, we do have a few of those services running. Most of them are just communicating with our public facing GraphQL API. The web client, our poster generator, the internal dashboard, all of our clients and apps use the same API. GraphQL allows us to define a clean contract and through introspection, every client knows how to interact with it. This is all pretty straightforward, but the actual workflows itself are not as trivial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*tqOELmbK47dr6IL7wtk54Q.png" /></figure><p>Our app offers users to configure poster designs. The visuals created for the poster are based on the individuals fitness data, which we sync from <a href="https://www.strava.com/">Strava</a> or uploaded <a href="https://www.thisisant.com/">FIT files</a>. Depending on the number of the current user’s activities, the amount of data can become huge. The reason why we do this on the server side is because we also offer <strong>printed versions</strong> of the generated posters..</p><p>We still wanted to use D3, and even if it’s possible to invoke a JavaScript runtime directly from Rails or Ruby, we decided to go for a more native solution and decided to write the poster generator in pure JavaScript. Therefore, instead of simply utilizing <a href="https://d3js.org/">D3.js</a> in our web app, we created a new <a href="https://nodejs.org/en/">Node.js</a> service, the <strong>poster generator</strong>. The requirements for the service itself were pretty simple:</p><ul><li>It should be capable of accepting a bunch of user data and configuration</li><li>It should be accessible through a single RESTful endpoint POST /posters</li><li>It should be able to return the rendered poster in the requested file format</li></ul><p>The most complex task was actually to implement nice designs for the posters itself. For development purposes, we also created a slightly different <em>sandbox</em> version of the generator, but the ideas for the production and the development variant are pretty much the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*leMYiFqYOFEyCD70_g8R2w.png" /><figcaption>One of the designs, rendered by the poster generator service</figcaption></figure><p>Nevertheless, after shipping this, we discovered that the poster editor does not necessarily feel responsive all the time and we were forced to think about potential improvements we can make. To help understand the problem, have a look at the swimlane diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQgB4B2UtrZNjU4gpIooqQ.png" /><figcaption>Flow of data through the system</figcaption></figure><p>The major problem here is, that every step needs to wait for its previous step to finish and also data needs to be transferred in-between steps. All of this adds some time to the total round-trip time and even though it was not very slow, there was still room for improvement.<br>For some of the steps we realised there was no potential to speed things up. The initial request to the API, for example, is very fast. The proxy call to the generator was also never a problem. And, this is really important, we do all of the data transfer within the local network.</p><p>Furthermore, some of the steps cannot be optimized from an architectural point of view. We somehow have to run the D3 program to create a vector representation of the poster and we also have to fetch the complete data upfront from the database. After the vector representation has been created, we still need to transform it into the desired output format (PNG or PDF). For this step, we use a system program called rsvg-convert. This program is blazingly fast and is capable of converting SVG files or strings into a binary representation.</p><h4>Solution</h4><p>The best feature though, is the ability of rsvg-convert to do the work in chunks and that it can provide an output stream instead of writing the result to a file. After we have figured this out, we immediately thought about streams as we knew that they are working great together with Node.js. Therefore we decided to pass the output stream of the rsvg-convert program directly to the response stream. Instead of waiting for the program to write the full output to a temp file first, we can just skip this step and pipe it through.</p><p>Nevertheless, if you take a look at the diagram above, this improvement is only half of the way to solve the full problem. In our API, we still had to wait for the response to be completely served, before we could start to send the file to the client.<br>Again, this problem can also be solved by using streams. Even though streams in Ruby are not the most common thing.<br>So far, we were using an HTTP client called Faraday for service-to-service communication. Besides being an awesome HTTP client, streams are not exactly its strength. After some research, we found <a href="https://github.com/httprb/http"><em>httrb</em></a> and besides supporting streams out of the box, it also comes with a nice explanation on how to use <a href="https://en.wikipedia.org/wiki/HTTP_persistent_connection">persistent connections</a>. We did not think about this at first, but after trying a few HTTP clients, we realised that creating a new connection (with TLS) for each and every call to the service is also quite expensive. We ended up using <em>httprb</em> in conjunction with <a href="https://github.com/mperham/connection_pool"><em>connection_pool</em></a> to create a pool of <a href="https://github.com/httprb/http/wiki/Thread-Safety">thread-safe</a> connections, which can be reused by all the requests we make to the poster generator service.<br>To complete the cycle, we use Rails LiveController to also start pushing chunks immediately to the client. As soon as the poster generator starts serving chunks, this data is passed immediately to the client through our API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*4KDF3OqLqSgqAOqwz7fYJg.png" /><figcaption>Screenshot from our APM (Application Performance Monitoring)</figcaption></figure><p>This screenshot contains a diagram from our APM tooling and it shows the data-flow during the development of this solution. The generator and the API were set to debug mode, which adds a 1 sec delay between chunks sent to the stream. The total round-trip in production is usually close to 100ms for a preview file. You can see on the diagram, the span which says <strong>stream file</strong> ends shortly before the API response itself is completed. Before <em>streams</em>, this looked a lot like the swimlane diagram above.</p><h4>Summary</h4><p>Our production system is now serving all posters as a stream of data. No matter if they are intended to be used as a preview in the web editor or if files are generated for printing. This is working great for us and we are really happy with the solution.</p><p>There is obviously still some work that needs to be done and a few minor issues pop up occasionally, but in general, shipping this to production was easy. Recently, we even started thinking of more ways to use streams and we already use streams to serve the React web app (Server-Side Rendering).</p><p>With streaming in place, the overall roundtrip time to create a poster file and serving it to the client was reduced by about 30%.</p><p>Thanks for reading this, and happy programming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c144372038b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing software]]></title>
            <link>https://medium.com/series/writing-software-3377ee109147?source=rss-ec5bea6e253e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3377ee109147</guid>
            <dc:creator><![CDATA[Hannes Moser]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 22:14:48 GMT</pubDate>
            <atom:updated>2019-08-03T22:14:48.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>I am a software developer with a faible for web platforms, services and API design. The last decade, I have worked on browser games, scalable websites, APIs and web application</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3377ee109147" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>