<?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 Maxim Molchanov on Medium]]></title>
        <description><![CDATA[Stories by Maxim Molchanov on Medium]]></description>
        <link>https://medium.com/@vonmo?source=rss-f5be4eb3fb07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VLq3z1gQOcRxCuJqG8Swxw.jpeg</url>
            <title>Stories by Maxim Molchanov on Medium</title>
            <link>https://medium.com/@vonmo?source=rss-f5be4eb3fb07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:25:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vonmo/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[5 things I wish I knew before writing an financial exchange]]></title>
            <link>https://medium.com/@vonmo/5-things-i-wish-i-knew-before-writing-an-financial-exchange-52f794631be5?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f794631be5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[personal-experience]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 10:08:35 GMT</pubDate>
            <atom:updated>2020-02-19T07:32:38.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 things I wish I knew before writing a financial exchange</h3><p>“Tell me, and I will forget. Show me, and I may remember. Involve me, and I will understand.”</p><p>When I and my cat set off to developing a financial exchange engine, this very quote of Confucius was ringing in my head. We were a dream team: motivated, solid, result-oriented. Our condition could be best described as interest and readiness to take on challenges on our way to MVP. All those challenges and discoveries, met during development, have adjusted the whole process and were well worth the time spent. Today I’d like to share some of them with you — and tell about the results of this experiment as well.</p><p>For the impatient, here is the link to the <a href="https://github.com/Vonmo/trade_demo"><strong>self-hosted demo</strong></a>. The rest, please, welcome to read further.</p><p>The main challenge of this project was the limited resources. If this limit hadn’t been that critical, the following list would, probably, look a bit different. My insights might seem banal, but each question can be treated differently. There is a huge divide between just ‘hearing about a problem’, ‘becoming aware of the problem’ and ‘understanding the problem’.</p><p>So, here is the list:</p><p><strong>It’s way harder to bring a project to MVP than just to start it</strong></p><p>When you are working on a project single-handedly and, what’s more, in your free time only, it’s very easy to shift the deadlines. I personally had to stop for half a year because of the main workload and family issues.</p><p>The project implementation was divided into two parts: March-April 2019 and November-December 2019. In November I wasn’t sure that I would come to MVP. However, all the internal interfaces were ready, as well as the storage system and order processing. All I had to do was create user interfaces. So, I decided to move on.</p><p>As a result, I realized that it’s better not to put projects on hold as the initial motivation is lost and the focus can be shifted. To keep going, I had to put a real effort in finding time for the project again.</p><p><strong>Marketing can be different</strong></p><p>This insight appeared after I’d been researching and choosing the frontend stack. Now there is a wide variety of libraries and frameworks whose APIs are changing so rapidly that it might make you stunned.</p><p>The hype around any of them is not an indication of quality. The size of the community around a project often doesn’t correlate to the quality of the solution. If a project/solution/technology position themselves as the best of the best and are described as ‘magical’ and ‘amazing’, it’s better to take it with a grain of salt or even avoid. It is likely to save you some time in future.</p><p><strong>You never know which problem of failure in third-party software you might encounter</strong></p><p>Even proven technologies can let you down. It happens so that an instrument you’ve been using for a long time starts acting not the way you want. To my surprise, it happened to me while I was working on this project too. There was Timescale and its time_bucket which didn’t support big intervals; Tarantool and replication issues and manual control of transactions; Rustler which started copying more data while calling functions…this list can be continued. What I realized here was that in the open source world you can always manage to fix the problem or find a way to avoid it by digging deeper into the source code of the app.</p><p>When resources are limited, you can’t but plan the amount of work carefully. If a problem turns up, you have do deal with it on your own, be it a small one or big one. You just have noone to delegate it to.</p><p>So, every technical difficulty — for instance, a mistake in a third-party library, or a limitation in a technology you are using, or sometimes an issue of architecture — can seriously shift the deadline.</p><p><strong>Your eyes might glaze over and affect decision making</strong> Usually, in case of commercial development, we communicate with other people. Any project involves people who are making it or using it. During development, we constantly get updates from other members of the process which add up to our perspective. Making any technically challenging decision is a complex process. When you are absorbed in a problem and spend hours or even days trying to find the ways of addressing it, you sometimes can’t keep your focus.</p><p>I’ve realized how important and valuable working in a team is. An opportunity to discuss a question with a colleague who isn’t working on the same task but is still in the know can be really useful. They will be able to assess your approach or solution critically, and it will save your time and reduce the likelihood of mistakes.</p><p><strong>Teaching programming to a cat is a tricky business</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*8xG0eOAzc9gD5EAL.jpg" /></figure><p>If you want to repeat my experiment, here is something to bear in mind. Despite the fact that my four-pawed buddy demonstrated genuine interest to the project, it didn’t stop him from getting lazy or distracted all the time. After a couple of weeks I realized that there is no way he’d become a programmer. However, his teamwork skills can’t be underestimated. He was in charge of maintaining the team spirit and, needless to say, he did his best.</p><h3>Project outcomes</h3><p>Before I started this experiment, I’d set 2 main goals:</p><ul><li>A deeper understanding of the subject and improvement of technical expertise;</li><li>Identifying strengths and weaknesses of functional languages and open source projects in trading systems development.</li></ul><p>During the experiment I definitely managed to deepen and systematize my knowledge and expertise and even tried to share the outcomes with the community — by the way, you will find the links to the previous boringly theoretical articles in my profile. So, this goal has been achieved successfully.</p><p>As to the functional programming…well, I’m looking from Erlang/OTP perspective now. Erlang as a language and OTP as a framework are suited to industrial programming and financial systems implementation. First, the ecosystem is quite mature. Second, minimum syntactic basis of the language, immutability, and approaches embodied in OTP enable for quick implementation of scalable, distributed and reliable systems. Unfortunately, I didn’t keep a time log, but the whole process took me about 4 months while working after having done my day job. Meanwhile, there are more than 200 integration tests in the project.</p><p>Sounds good and all, you will say. However, there still is a small fly in the ointment. Erlang is pretty similar to Python in terms of performance. Unlike Python, it lets us write highly concurrent systems with an adjustable level of parallelism. Also, such systems are easy to scale, and the components can be distributed within a cluster. The systems turn out to be of high capacity, but not superfast. Basing on the last conclusion, I realized that the most effective and productive approach would be not distributing market handlers and client accounts to different machines within a cluster, but processing all markets and accounts within a single machine with data replication for the sake of reliability.</p><p>Due to the limited performance of Erlang, market processing should be done with the help of lower-level languages without GC and fair schedulers. In current implementation I have already moved some part of the functional to NIF on Rust. This way, thanks to the optimized work with network and binary structures, Erlang perfectly solves the issues of organizing a reliable and fast platform. An issue of working with orders and accounts, though, is better to be solved with the help of Rust/C/C++ (to your taste).</p><p>Last but not least is the choice of the language for frontend. Old habits die hard — I opted for Vue + Js. However, if I were choosing the stack now, I would prefer Vue + Typescript. Stricter typing would make it possible to accelerate the development. All in all, thanks to everyone who was following the experiment. I hope it wasn’t too boring, or was it? Stay tuned — it’s not goodbye! :-)</p><p><em>Originally published at </em><a href="https://www.vonmo.com/en/blog/5-things-i-wish-i-knew-before-writing-an-financial-exchange/"><em>https://www.vonmo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f794631be5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vonmo Trade Experiment. Part 4: Stock charts]]></title>
            <link>https://medium.com/@vonmo/vonmo-trade-experiment-part-4-stock-charts-b1583a3060c6?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1583a3060c6</guid>
            <category><![CDATA[charts-and-graphs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[financial-software]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 13:33:36 GMT</pubDate>
            <atom:updated>2020-01-21T13:33:36.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*99DYaStSUS7MB__Z.jpg" /></figure><p>In the previous articles we dealt with order creating and processing. Today’s one will focus on processing and storage of the information which is essential for graphic instruments of market analysis — or just stock charts.</p><p>To assess the market condition properly, we can’t manage with just an order book and trade history. We need an instrument which will help to see the market price trend clearly and fast. Charts can be divided into two types:</p><h3>Line charts</h3><p>These are the easiest and the do not require any preparation to be understood. Line charts show the dependence of a financial instrument price on time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*nELs0GJgE4gH1RIP.png" /></figure><h3>Chart resolution</h3><p>If we start building a chart based on all the price changes, i.e. every closed deal gets to the chart, it will be really difficult to take. Also, the capacities used for this chart processing and delivery will be wasted. That’s why data should be decimated: the timeline is split into intervals, and the prices within these intervals are aggregated. Resolution is the size of a basic interval of timeline splitting: second, minute, hour, day etc.</p><h3>Bar chart</h3><p>They belong to interval graphs. To increase informativeness, we need to show the price information at the beginning and at the end of the interval for every single interval. We also need to show the maximum and the minimum price. The graphic representation of this set is called a bar. Let’s look at a bar scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*8emaEwke0qRpe-lW.png" /></figure><p>A sequence of bars makes a bar chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*JS5otfc8wVe6orWj.png" /></figure><h3>Candlestick chart</h3><p>Like bar charts, they belong to interval graphs. They are the most popular type of graph in technical analysis. A ‘candlestick’ consists of black or white body and shadows — higher one and lower one. Sometimes a shadow is called a wick. The highest and the lowest borders of a candlestick illustrate the highest and the lowest price during the time interval represented. The body borders show the opening price and the closing price. Let’s draw a candlestick:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/0*CBu7YrMdTwcM3HNk.png" /></figure><p>A sequence of candlesticks make a candlestick chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*vIX6aRZmU0RBXxUf.png" /></figure><h3>OHLCV notation</h3><p>In the previous article we dealt with the scheme of data storage for a graph in postgresql and built a table for data source which will store aggregated data:</p><p>These fields don’t need to be explained except, probably, the r field which is the row resolution. In postgresql there are enumerations which are great to use when we know the value set for a field in advance. Let&#39;s define a new type for permissible chart resolutions via listings. Let it be a row from 1 minute to 1 month:</p><p>It’s important to find a balance between IO performance, CPU performance, and final cost of ownership. At the moment, there are 16 resolutions defined in the system. Two obvious solutions present themselves:</p><ul><li>We can calculate and store all resolutions in the base. This option is convenient because, while selecting, we don’t spend capacity on interval aggregating and all data are ready for output straightaway. There will be slightly more than 72k records for one instrument per month. Looks easy and convenient, doesn’t it? However, such table will change too often because for each price update we need to create or update 16 records in the table and rebuild the index. There might be an issue in postgresql with garbage collecting too.</li><li>Another option is to store a single basic resolution. While selecting from basic resolution, it’s necessary to build the resolutions required. For example, if we store a minute resolution as the basic one, 43k records will be created for each instrument per month. This way, compared to the previous option, we are reducing the record volume and overhead costs by 40%. However, CPU load is increasing at the same time.</li></ul><p>As mentioned before, it’s really vital to strike a balance. That’s why a middle ground would be to store not just one basic resolutions, but several: 1 minute, 1 hour, 1 day. Under this scheme, there are 44,6k records created for each instrument per month. Optimization of record volume will be 36% and CPU load will be acceptable as well. For instance, to build week intervals we’ll need to read from the disc and aggregate the data of 7 day resolutions instead of reading and aggregating 10080 records with minute basic resolution.</p><h3>OHLCV storage</h3><p>OHLCV is a time series in its nature. As is known, relational database is not suitable for such data storage and processing. Our project deals with this problem with the help of <a href="https://timescale.com/">Timescale</a>. Timescale improves the performance of insert and update operations, and enables to configure partitioning, and provides the analytical functions which are specially optimized for working with time series.</p><p>To create and update the bars, we’ll need standard functions only:</p><ul><li>date_trunc(&#39;minute&#39; | &#39;hour&#39; | &#39;day&#39;, transaction_ts) - to find the beginning of the interval of a minute, hour, and day resolution respectively.</li><li>greatest и least - to define the maximum and minimum price.</li></ul><p>Thanks to upsert api, only one update request is performed per each transaction.<br> What I got in the end is the following SQL for fixing market changes in basic resolutions:</p><p>While selecting, the following functions will serve us for aggregating the intervals:</p><p>The only problem with Timescale is the limitation of time_bucket function. It enables to manipulate the intervals less than a month only. To build a month resolution, we should use the standard function date_trunc.</p><h3>API</h3><p>To display the graphs on the client, we’ll use <a href="https://github.com/tradingview/lightweight-charts">lightweight-charts</a> from Tradingview. This library enables to configure the appearance of the charts and is quite convenient to exploit. I’ve got the following charts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*t4ttN45vYxeW8QTT.png" /></figure><p>As the main part of the browser-platform interaction is carried out via websocket, there are no problems with interactivity.</p><h3>Data source</h3><p>The data source for charts (or data feed) must return the required part of the time series in needed resolution. To save the traffic and processing time on the client, the server must pack the points. API for data feed should be designed so that you can request multiple graphs in a single request and subscribe to their updates. This will reduce the number of commands and responses in a channel. Let’s consider a request of the last 50 minutes for USDGBP with automatic subscription to the graph updates:</p><p>For sure, we can request the date range (from, to), but as we know each bar interval, declarative API indicating the moment and the number of bars seems more convenient to me. Data feed will respond to this request in the following way:</p><p>bar_fields field contains the information about the position of the elements. Further optimization involves putting this field into the client configuration which it gets from the server during the client initialization. This way, the client gets a necessary part of historical data and builds the initial state of the graph. If the state changes, the clients gets an update on the last bar only.</p><h3>Interim conclusion</h3><p>Over the whole series of articles we went through the theory and practice of building an exchange. Now it’s time to put the system together. The following article will tell about the development of user graphic interfaces: service UI to operate the platform and UI for end users. Also, you’ll be able to take a look at the demo version of Vonmo Trade.</p><p>Thanks to Nadezda Popova for proofreading.</p><p><em>Originally published at </em><a href="https://www.vonmo.com/en/blog/vonmo-trade-experiment-stock-charts/"><em>https://www.vonmo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1583a3060c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vonmo Trade Experiment. Part 3: Order book. Processing and storing trade info]]></title>
            <link>https://medium.com/@vonmo/vonmo-trade-experiment-part-3-order-book-processing-and-storing-trade-info-e05d06d60906?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05d06d60906</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-analysis]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[financial-software]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Fri, 17 Jan 2020 12:46:03 GMT</pubDate>
            <atom:updated>2020-01-17T12:46:03.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*E43234tnclr6k48q.jpg" /></figure><p>In the previous article of the series we got familiar with order types. Today we’ll take a closer look at an order book, processing orders, and dealing with issues of trade information storage.</p><h3>Supply and demand</h3><p>I’m pretty sure you remember the law of supply and demand from economics. It shows the market mechanics in pricing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*_56_phuZUdIVnKf1.png" /></figure><p>The same mechanics works at exchanges.</p><p>An order book is a list where all limit orders of buyers and sellers go. This way, the current interest to a particular financial instrument is demonstrated.</p><p>If we transform the previous graph with regard to an order book, we’ll have something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Xzvs_BQ-4YpPks04.jpg" /></figure><p>We can see that the market price appears when the maximum bid price equals the minimum offer price. The difference between these prices is called spread. Spread is an important indicator as it is connected with an instrument liquidity. The less the spread is, the more liquidity the instrument has. To provide liquidity within exchange trading process, a limit on maximum spread is often imposed. If this limit is exceeded, bidding is stopped.</p><h3>Creating an order</h3><p>Let’s have a look at an order life cycle, from getting to the exchange to being executed or cancelled. For ease, we’ll focus on a foreign exchange market. A special process is responsible for order processing logic. Let’s call it a market controller.</p><p>So, a trader creates an order and it gets to the exchange. The controller must make sure that the trader has enough liquidity to create the requested type of order. As a source of information, an internal accounting server or any external APIs can be used.</p><p>To fulfil this order immediately, the market must have a counterbid, or a so-called matching order. If the counterbid exists, then a smaller order from the pair is executed fully, and the bigger one partially — of course, as long as partial order fulfillment is allowed by the order trade instructions. If the counterbid doesn’t exist, a new order gets into the order book and takes its place in the list of the orders of its type. Since only pending orders can get into the order book, we need to create special lists for other order types.</p><p>In all order lists the buy side should be sorted in descending order while the sell one — in ascending order. The first item of the limit orders list shapes the best ask and bid prices respectively.</p><p>One more important point is the order of execution. The controller must implement FIFO. That is why, if the prices of two orders are identical, the first one to fulfil is the one which has been created first.</p><p>In user interface the order book looks like a table with a set of price levels. It shows both buy limit orders and sell limit orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*OLKZ1sgfIvi__KZU.png" /></figure><p>Buy orders and sell orders are in different colours to be distinguished easier.</p><h3>Price levels aggregation</h3><p>The order book depth is a number of price levels. For active markets with lots of pending orders, which differ as little as they can, this depth can be too big to be shown in the trader’s terminal. We need a tool for grouping the levels to assess the whole book. By cutting off one decimal place at a time and grouping the levels, we can reduce the number of levels with each step.</p><h3>Fulfilling and cancelling orders</h3><p>After an order in the order book has been executed or cancelled, the controller must update the book and delete the order. It also notifies all interested parties of the changes in the book.</p><h3>Handlers architecture and scaling</h3><p>Taking into account required performance and reliability of the system, we need to define the approaches to scale applications and data storage layers.</p><p>Normally, vertical scalability is used for exchanges. The code of order processing and user accounts processing is run on one machine as a monolith process. Such approach demonstrate good performance but has certain limitations — in any case, vertical scalability has its limits in terms of CPU and storage capacity.</p><p>As part of the experiment, I decided that market processing should be scaled horizontally. Each individual instrument is handled by its own process. The processes are automatically distributed between cluster nodes. In case of failure, a market is moved to another node without loss of state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*U0TQpp0C3ZMnhsk3.png" /></figure><p>The system formula is quite simple: M handlers are distributed on K cluster nodes and use L data storages. This model lets us scale a system up to approximately 150k nodes, and each market controller can process about 30k RPS.</p><p>As the flow of orders is different at different markets and depends on users participation, we can divide all markets into several groups: big, medium, and small ones. Each node has the settings enabling us to specify the limits of the markets which it can process. The master is evenly and automatically distributing the markets of the same type between the cluster nodes. If the cluster composition has been changed, the markets are redistributed. This way we can achieve more or less equal distribution of the system load.</p><p>Nodes in management UI look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*HZslHy4Dvpp3n2NU.png" /></figure><h3>Data storage</h3><p>The order book is constantly changing and must be stored in memory. For MVP I’ve opted for Tarantool with WAL as an in-memory storage. All historical data will be stored in PostgreSQL.</p><p>The storage scheme for current and historical data must comply with the chosen scheme of code scalability of the handlers. Each market can use its own postgres and tarantool. To make it possible, let’s combine postgresql and tarantool into a single entity — market data storage. While setting the market, an administrator is able to manage the storages. To retain flexibility, we’ll be indicating the unique id of the connection pool instead of credentials to certain postgresql and tarantool instances. The pool interface is supported by the platform. So, the storage looks like this in admin UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RIcnEZu1vbgrM_2e.png" /></figure><p>While setting the market, the administrator must indicate at least one storage for each market. If several are indicated, we’ll have a market with logical replication of data. This function enables us to configure the reliability and performance of the data storage scheme.</p><h3>Order book data</h3><p>Tarantool uses spaces for stored data organisation. The declaration of spaces necessary for the order book looks like this:</p><p>As several markets can store their data on one tarantool instance, let’s add market id to all instances. Current book implementation is based on the so-called precalculated principle. When the book is being updated, the groups are automatically recalculated. For example, we add an order to the market with 6 digit precision for prices. We can have 6 possible groups of prices + one slice with the order raw data which need to be updated. There is a number of orders_mapping orders for getting the client’s active orders.</p><p>Thanks to tarantool’s indexes and iterators, lua-code for the order book storage consists of 600 lines only (together with initialization).</p><h3>Historical data</h3><p>Market data are stored in tables, separately for each market. Let’s take a look at the set of basic tables.</p><h3>Orders execution history</h3><p>To save the results of order processing, we have history table. All the orders that are completely fulfilled and the orders which are cancelled but partially fulfilled go there.</p><p>Reports for customers are computed based on their trade history which is stored in this table.</p><h3>Historical data feed</h3><p>For analytical purposes and historical data feed building, the market controller must save the information about the event after every transaction. The ticks table is used to commit all market changes:</p><p>It contains prices and market volume after a transaction has been made. The opts field contains service-based data, for example, the description of the orders involved in the transaction.</p><h3>Data feed for charts</h3><p>The ticks table is enough to be able to build stock charts. It contains the so-called raw data stream, but postgresql has powerful analytical functions and enables us to aggregate data on request. Troubles start when there is too much of data and lack of available computing resources. To solve it, let’s create a table with pre-calculated data:</p><p>In the next article we’ll talk about working with time series in Postgresql, preparing data for df table, and building charts.</p><h3>Conclusion</h3><p>This article has given us a better understanding of the main moments of order book organisation, as well as order processing mechanism. We have also had some practice of working with market data. The chosen storage scheme enables us to start with just one storage for all markets and, as the project grows, spread the markets to different storages and place them as close as possible to market handlers.</p><p><em>Originally published at </em><a href="https://www.vonmo.com/en/blog/vonmo-trade-experiment-order-book-processing-and-storing-trade-info/"><em>https://www.vonmo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05d06d60906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vonmo Trade Experiment. Part 2: Orders. Types and processing features]]></title>
            <link>https://medium.com/@vonmo/vonmo-trade-experiment-part-2-orders-types-and-processing-features-f96a169fed6f?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96a169fed6f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[financial-software]]></category>
            <category><![CDATA[system-analysis]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 15:33:33 GMT</pubDate>
            <atom:updated>2020-01-09T20:19:33.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*A5Xe4WhgRpGfCSU7.png" /></figure><p>To figure out how exchanges work, we need to look into exchange orders and the way broker processes them. This article deals with order types, the way they are executed at an exchange, and limitations imposed by trading system.<br> If you are curious to know what all those DAY, GTC, FOK, IOC, GTD, GAT, MOO, MOC, LOO, LOC, MIT, OCO, OSO, PEG mean, you are welcome.</p><h3>Orders</h3><p>All market players are interested in a good deal. To start bidding, we need to create a sell or a buy order for a required financial instrument. Consequently, a set of orders placed on the exchange creates current supply and demand. A market order is instructions from a client to their broker to buy or sell financial instruments at the exchange. A typical order contains the following information:</p><ul><li>Financial Instrument Identifier</li><li>Order type</li><li>Order side. Buy or sell.</li><li>Price</li><li>Quantity</li><li>Order duration type (optional)</li><li>Additional instructions (optional)</li></ul><p>We can break all the orders into three big groups:</p><ul><li><strong>Market orders</strong>. This order must be executed immediately at the current market price. If there is no necessary amount, then the order is executed as soon as possible.</li><li><strong>Pending orders</strong>. A request enables to control the limit prices for buying and selling. Sometimes such orders can not be executed straightaway or at all. The price is always better for limit orders.</li><li><strong>Conditional orders</strong>. These are all requests except limit ones that require extra conditions to be activated and executed.</li></ul><h3>Time in force</h3><p>You have, for sure, seen acronyms like DAY, GTC, FOK, IOC, GTD, GAT All of them indicate how long an order will remain active before it is executed or expires.</p><ul><li><strong>DAY</strong>. These orders expire at the end of the trading day.</li><li><strong>GTC</strong> (Good till canceled). This order is valid until it is cancelled. To make sure they don’t stay at the market indefinitely, a special limitation is imposed, which is usually from 30 to 90 days.</li><li><strong>FOK</strong> (Fill Or Kill). The order must be fully filled or immediately cancelled.</li><li><strong>IOC</strong> (Immediate Or Cancel). The order is immediately executed or cancelled by the exchange. Unlike FOK, this type allows for partial fulfillment.</li><li><strong>GTD</strong> (Good-til-Date/Time).</li><li><strong>GAT</strong> (Good-after-Time/Date).</li></ul><h3>Conditions of order execution</h3><p>By combining instructions on prices, time in force and extra limitations, we can get various types of order execution. To get a better idea, let’s get back to the order types structure which is presented at the beginning of this article.</p><h3>Market-on-open/close orders</h3><p>If we limit the duration of period when this market order is valid, we get the following:</p><ul><li><strong>MOO</strong> (Market-On-Open). A market order of such type can be executed only at the opening of the trading day. Its execution is guaranteed provided there is liquidity.</li><li><strong>LOO</strong> (Limit-On-Open). Like MOO, LOO can be executed at the opening of the trading day only. However, limit orders of this type enable for setting instructions for the price. The execution is not guaranteed.</li><li><strong>MOC</strong> (Market-On-Close). These orders are similar to MOO, but the market order can be executed at the closing of the trading day only. The execution is guaranteed provided there is liquidity.</li><li><strong>LOC</strong> (Limit-On-Close). These orders are similar to LOO, but the market order can be executed at the closing of the trading day only. The execution is not guaranteed.</li></ul><h3>Conditional orders</h3><p>When we want to tailor our orders for some trading strategy, we can do it with the help of conditional orders — the ones which are activated only after the condition has been satisfied. Thus, their main aim is to minimize the risk of significant financial losses.</p><h3>Stop order</h3><p>Stop order is a bid or an ask for a certain amount of a financial asset at a specified price or worse. As soon as the price equals or exceeds the specified stop price for a bid order, it automatically turns into a market order and is executed on general grounds. It works the same way with a stop order for selling. As soon as the price reaches the level set in the order and continues to fall, the order turns into a market one. This way, execution is guaranteed for active stop orders. Stop orders let us minimize potential losses, that’s why stop loss is the synonym for the stop order.</p><h3>Stop-limit order</h3><p>Unlike usual stop orders, where just the stop price is specified, stop-limit orders require also a limit price. As soon as the asset price is equal or worse than the stop price, a limit order with the specified limit price is automatically created. The execution of such order is not guaranteed.</p><h3>Trailing stop order</h3><p>Unlike usual stop orders, where the stop price is shown in absolute units, trailing orders use percentage. After activation, it turns into a usual market order. This way, the stop price is linked to the market price and grows with it. For example, we’ve placed an order for 10 dollars and set the stop price at 10% from the current one, i.g. the absolute stop price equals 9 dollars. Then, the asset grew to 15 dollars alongside with the stop price which grew to 13.5 dollars. This order type is used to minimize losses as well as maximize profit.</p><h3>Trailing stop-limit order</h3><p>Unlike trailing stop orders, this order turns into a limit one, not a market one, after activation.</p><h3>PEG order</h3><p>This is a kind of limit orders. It changes its price automatically after the change of bid or ask prices. In price instructions a shift for the worse from the current best bid/ask price is indicated.</p><h3>OCO order (one cancels other)</h3><p>This is a pair of orders. It usually consists of a stop order and a limit order. Both orders work with the same instrument. If one of them is executed, the second is automatically cancelled. A simple example: let’s imagine that we’ve bought an asset for ＄10. We aim at getting at least ＄3 of profit and limiting the losses to ＄2 at most. Then our stop price will be ＄8 and our limit price ＄13.</p><h3>OSO order (one sends other)</h3><p>This order consists of the main order and a group of linked orders. Orders can work with different instruments. If the main order is executed,all linked orders are then sent.</p><p>Now when we’ve briefly reviewed orders theory, let’s get down to practice.</p><h3>Practice</h3><p>From the system point view, it’s crucial to define the basic structure for all orders in a flexible, but precise way. Erlang enables us to do that with the help of records:</p><h3>Order identification</h3><p>After an order has been placed on the exchange, it gets an internal identifier — id field. To improve user&#39;s experience, when we are coordinating the exchange with external systems, we should enable an external system to set its own id to the order being created. It will give us a possibility to request orders both by id and by orig_id. Also, it will enable us not to use extra order mapping in the external system.</p><h3>Order ownership</h3><p>Let’s provide a possibility to create an agent (external broker) in our system. Orders can come directly from traders or from a broker that provides services to clients who don’t have direct access to the exchange. In case of a direct order owner and trader coincide.</p><h3>Instruction encoding</h3><p>Let’s look at the rest of the fields. There are two fields for encoding the instructions by price: price, which is the limit price for limit orders, and trigger_price, which is the trigger price for custom types. For instance, in case of stop orders this field will encode the stop price.</p><p>We use qty and qty_orig for encoding the volume. Qty_orig sets the initial order volume and qty - the order volume while being fulfilled. deals_history array will help to have precise information about partial fulfillments. With its help we can, for example, calculate the average price of the order after it&#39;s been fully filled. linked_orders field is necessary for encoding the information about linked orders for OCO and OSO.</p><p>To enlarge the system without changing exchange_order record, let&#39;s add opts field which is a dynamic dictionary.</p><h3>Interim conclusion</h3><p>To be honest, I thought that the second part of the series would be more compact. However, I had to be more detailed to elaborate on the topic. The theoretical part of the following article will shed the light on order book and the rules of order processing. The technical part will deal with the scheme of market data processing and issues of historical data storage.</p><p>Thanks to Nadezda Popova for proofreading.</p><p><em>Originally published at </em><a href="https://www.vonmo.com/en/blog/vonmo-trade-experiment-orders-types-and-processing-features/"><em>https://www.vonmo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96a169fed6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vonmo Trade Experiment. Part 1: Exchanges and modern technologies]]></title>
            <link>https://medium.com/@vonmo/vonmo-trade-experiment-part-1-exchanges-and-modern-technologies-f174ce298dbe?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/f174ce298dbe</guid>
            <category><![CDATA[financial-software]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[system-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 17:23:48 GMT</pubDate>
            <atom:updated>2020-01-05T20:35:32.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*jk7sx_BNWai58s1N.png" /></figure><p>This series of articles describes an attempt to create a reactive system performed by one person, with a minimum budget and in the shortest time possible.</p><p>The experiment aims at:</p><ul><li>A deeper understanding of the subject and improvement of technical expertise;</li><li>Identifying strengths and weaknesses of functional languages and open source projects in trading systems development.</li></ul><p>This article presents the motivational part and task decomposition.</p><p>I was planning to start this experiment in spring 2019, but then — life happened — and I had to reschedule. That is why here are my apologies to all those few followers of mine who have been waiting for the articles on this topic.</p><h3>What brought me here?</h3><p>When I realized that I’d got tired of day-to-day project routine, I wanted to create something unusual. I was thinking of various topics and directions which looked challenging enough for me. This way, the main requirements to the project-to-be appeared:</p><ul><li>Field of studies that I find interesting;</li><li>Distributed and high-availability nature of the app;</li><li>High information capacity and big volume of stored data, typical for data-intensive apps;</li><li>Maximum use of open source projects.</li></ul><p>As I’ve already had some experience in developing object storages, I came up with an idea. Why don’t I write a new implementation of s3-compatible storage using erasure coding and fast hash functions? But then I wanted something even more exciting. From a developer’s point of view, financial system are interesting due to their near real-time work, huge number of updates and volume of stored data. So, I set my mind on creating my own implementation of an exchange system.</p><h3>About exchanges</h3><p>A stock exchange is also known as bourse (from Latin “bursa” — “purse”). In a broad sense, this is a market where sellers and buyers conduct transactions. A traded asset defines the exchange type:</p><ul><li>commodities exchange, including labour exchange</li><li>stock exchange / market</li><li>currency exchange</li><li>futures exchange</li></ul><p>Historically, exchanges were literally a place which, at the appointed time, brought together sellers, buyers and brokers, or middlemen, who assisted with transactions.</p><p>The main functions of any exchange are the following:</p><ul><li>Organizing the exchange trade:</li><li>Defining trade rules under current legislation</li><li>Setting product standards</li><li>Staffing and material provision</li><li>Information activity. Providing information about stock instrument prices, markets and companies;</li><li>Drawing up standard contracts;</li><li>Settlement of disputes (arbitration);</li><li>Providing certain guarantees of order execution.</li></ul><p>Modern exchanges are well-organized trading platforms which work by certain rules and create supply and demand. Exchange economy is crystal clear: the more transactions there are on the exchange, the more fees and commissions it gets for its service.</p><p>Now when we have a general idea, let’s limit tasks to do for MVP realization.</p><h3>MVP</h3><p>Limited resources lead to limited functionality of the prototype.However, vital and fundamental things should be fully implemented.</p><h3>Task decomposition and architecture choice</h3><p>Technically speaking, an exchange is a public service system where its participants generate a flow of requests — or orders. The system, in its turn, operates and executes them by the rules defined in advance. Order service must be performed with minimum waste of time. The exchange must be fault-tolerant and highly available.</p><p>Let’s divide the project into a system part and a public part. The system part enables us to manage platform components and exchange trading process. The public part includes client interfaces: Web API, Trading API, notifications subsystem. Both parts will be based on distributed apps platform which is responsible for system scalability and reliability. As we are limited in budget, we’ll opt for tested open-source solutions for data storage organization. Tarantool is used for the system hot data, PostgreSQL for the cold data.</p><p>Let’s draw the system structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*c7OWdz9G6xvCr9VU.png" /></figure><p>It might seem that both the architecture and the project itself are no different from any usual system. Where is the challenge, you may ask. To answer, let’s take a look at the process of creating orders and filling orders for a currency exchange.</p><p><strong>Creating an order</strong></p><ol><li>Checking authorization</li><li>Making sure that a user can now afford to place an order</li><li>Creating an order</li><li>Informing the user on success of the operation or failure</li></ol><p><strong>Filling an order</strong></p><ol><li>Finding a match</li><li>Checking fund sufficiency for both parties of the deal</li><li>Making the deal: money transfer between accounts + exchange fee transfer to the exchange commission account</li><li>Saving the history of order execution</li><li>Updating the information data: raw data and aggregated data for graphs</li><li>Notifying all parties concerned about the deal.</li></ol><p>The trouble starts when we move from a monolith, working on a single machine, to a distributed fault-tolerant system deployed on a cluster. I think, the minimum performance level should make about 5–7k RPS completed transactions per market. This puts extra limitations on architecture and work with data.</p><p>Following the KISS principle, each app must perform only the functions which are necessary for processing the entity implemented in it: market, account, authorization etc.</p><p>VonmoTrade is based on horizontal scalability principle. Each application could have many instances to provide fault-tolerance and required performance level.</p><h3>Technology stack</h3><p>To avoid generating entropy, let’s limit the languages and approaches used. For server, this set will include:</p><ol><li>Erlang. To my mind, a perfect language to deal with infrastructure things.</li><li>Rust. Excellent for system-related things and optimization issues.</li><li>PostgreSQL. Serves as the main base for long-term data storage.</li><li>Tarantool. Serves as hot data storage (for MVP only)</li><li>Clickhouse. For logs analysis and deep analytics.</li><li>Linux. The system must support modern distributions.</li></ol><p>The client software is implemented with the help of Vue framework and Vuex.</p><p>As the project presupposes a big number of components, we will write a lot of property-based tests and integrative tests to ensure an adequate level of quality of the final solution.</p><h3>Plans</h3><p>In foreseeable future I’m planning to review the basics of the theory and delve into practice in the following directions:</p><ul><li>Orders. Types, processing features, aspects of trade information storing.</li><li>Order book. Visual representation of the market.</li><li>Bidding history. Prints, graphs, personal history.</li></ul><p>As they say… Like, Share, Subscribe :))</p><p>Thanks to Nadezda Popova for proofreading.</p><p><em>Originally published at </em><a href="https://www.vonmo.com/en/blog/vonmo-trade-experiment-exchanges-and-modern-technologies/"><em>https://www.vonmo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f174ce298dbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building distributed apps: second approximation]]></title>
            <link>https://medium.com/data-science/building-distributed-apps-second-approximation-f792b3fe893f?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/f792b3fe893f</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 19:03:31 GMT</pubDate>
            <atom:updated>2019-07-11T14:20:06.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JSRd7074-Wcp3pgKlNdQhg.jpeg" /></figure><p>This article is the final one of the series about distributed reactive apps in Erlang/Elixir. In the <a href="https://towardsdatascience.com/building-distributed-apps-zero-approximation-b0c4b16f92d3">first article</a> you will find the theoretical basis of reactive architecture. The <a href="https://towardsdatascience.com/building-distributed-apps-first-approximation-2bbab777f6b2">second one</a> illustrates the main templates and mechanisms of building such systems.<br>Today we will address the questions of code base development and projects development in general.</p><h3>Service organization</h3><p>When we deal with service development in real life, we often have to combine several interaction patterns in one controller. For example, service which performs managing the project users’ profiles must respond to req-resp requests and send notifications on profile update events using pub-sub. This case is quite simple: behind messaging, there is just one controller implementing the service logic and publishing the updates.</p><p>It’s getting more complicated when we have to create a fault-tolerant distributed service. Let’s imagine that the requirements for users service have changed:</p><ol><li>The service must now process requests at 5 nodes of the cluster,</li><li>It must be capable of carrying out background processing tasks,</li><li>It should be also able to dynamically manage the subscription lists</li></ol><p><strong>Note</strong>: In this article we are not addressing the question of consistent storing and replication of data. Let’s suppose that these issues have been solved before — the system already has a scalable and reliable storage layer and the handlers can interact with it.</p><p>Formal description of users service got more complicated. From a programmer’s point of view, the changes are minimal due to the use of messaging. To meet the first requirement, we have to define balancing algorithm on the req-resp.</p><p>The requirement of handling background processes comes up quite often. In users it can be checking users’ documents, processing of downloaded multimedia or synchronizing data with social networks. These tasks should be distributed within cluster, and their implementation must be controlled. That is why we have two options: either to use the pattern from the previous article or, if it doesn’t suit us, write a customized task scheduler which will be in control of handlers pool.</p><p>The third point requires pub-sub pattern extension. To implement it, we should first create a pub-sub exchange and, then, run the controller of this exchange within our service. This way we kind of move out managing subscribing events and lists of subscribers from the messaging layer to users implementation.</p><p>As a result, task decomposition has shown that to meet the requirements we should run 5 copies of the service on different nodes and create an extra entity — a pub-sub controller which is responsible for subscription.</p><p>To run 5 handlers, it’s not necessary to change the service code. There is just one additional action — setting the rules of balancing on the exchange. We will talk about this a bit later. Also, there is one more difficulty: pub-sub controller and customized scheduler must work as a singleton. The messaging service, being fundamental, must provide a mechanism for leader election.</p><h3>Leader election</h3><p>In distributed systems this is a procedure of nominating the only process which is responsible for scheduling and distributing tasks and load over the cluster.</p><p>In systems which don’t tend to be centralized some universal and consensus-based algorithms are used, for instance, paxos or raft.</p><p>As messaging is a broker and a central element at the same time, it knows about all service controllers — leadership candidates. Messaging can appoint the leader without voting.</p><p>After starting and connecting to an exchange, all services receive a system message:</p><blockquote>#’$leader’{exchange = ?EXCHANGE, pid = LeaderPid, servers = Servers}</blockquote><p>If LeaderPid matches current process pid, it is appointed as the leader. The Servers list includes all nodes and their parametres.</p><p>When a new cluster node appears and the currently working one is turned off, all service controllers get</p><blockquote>#’$slave_up’{exchange = ?EXCHANGE, pid = SlavePid, options = SlaveOpts}</blockquote><p>and</p><blockquote>#’$slave_down’{exchange = ?EXCHANGE, pid = SlavePid, options = SlaveOpts}</blockquote><p>respectively.</p><p>This way, all components are aware of all changes. What’s more, there is just one guaranteed leader in a cluster at any given moment.</p><h3>Middleware</h3><p>Middleware is convenient to use if we need to implement complex distributed processing or to optimize existing architecture.</p><p>If you don’t want to change service code and deal with the issues of additional processing, routing of message logging, you can turn on proxy handler which will do all the job.</p><p>A classic example of pub-sub optimisation is a distributed app with a business core which is generating update events like change of price at the market. Such an app also has an access layer — N servers which provide web clients with websocket API.</p><p>Client service, if deal with it outright, looks like this:</p><ul><li>Client establishes connection with platform. On the side of the server, terminating the traffic, the process is launched which serves this connection,.</li><li>Authorization and subscription to updates take place within service process. The process calls subscribe method for topics.</li><li>When an event has been generated in the core, it is delivered to the processes which serve the connection.</li></ul><p>Let’s imagine that we have 50000 subscribers to the topic ‘news’. The subscribers are evenly distributed across 5 servers. Eventually, every update, when it gets to the exchange, is replicated 50000 times: 10000 times per server, according to the number of subscribers. Doesn’t look like an effective scheme, right?</p><p>To improve it, let’s introduce a proxy which has the same name with the exchange. Global names registry must be able to resolve nearest process by name in a group as this is important.</p><p>Then, let’s run this proxy on access layer servers. All our processes which serve websocket api will subscribe to it, not to the initial pub-sub exchange in the core. Proxy subscribes to the core only in case of unique subscription and replicates the message which it gets to all its subscribers.</p><p>As a result, 5 messages instead of 50000 will be sent between the core and access servers.</p><h3>Routing and balancing</h3><h3>Req-Resp</h3><p>In current implementation of messaging there are 7 strategies of request distribution:</p><ul><li><em>default</em>. Request goes to all controllers.</li><li><em>round-robin</em>. Controllers are assigned for incoming request in a cyclic way.</li><li><em>consensus</em>. Controllers providing the service are divided into the leader and slaves. Requests go to the leader only.</li><li><em>consensus &amp; round-robin</em>. There is a leader in the group, but requests are distributed between all members.</li><li><em>sticky</em>. Hash function is calculated and reserved for a certain handler. All the following requests with this signature go to the same handler.</li><li><em>sticky-fun</em>. When an exchange is initialized, hash function for sticky balancing should be defined.</li><li><em>fun</em>. Equivalent to sticky-fun, but you can also redirect, decline or pre-process it.</li></ul><p>Distribution strategy is defined when an exchange is initialized.</p><p>Apart from balancing, messaging enables us to tag entities. Let’s look at tag types in a system:</p><ul><li>Connection tag. Allows us to understand the connection via which the events have arrived. It is used when controller process connects to the same exchange but with different routing keys.</li><li>Service tag. Allows us to unite handlers in groups within one service and expand routing and balancing opportunities. Routing is linear for req-resp pattern. We send a request to an exchange, the exchange passes it to the server. However, if we have to split handlers into logical groups, the splitting is done with the help of tags. If a tag is indicated, the request will be sent to a certain group of controllers.</li><li>Request tag. Allows us to distinguish responses. As our system is asynchronous, we need to have an opportunity to indicate RequestTag to process service responses. By this tag we will understand the response to which request we have received.</li></ul><h3>Pub-sub</h3><p>It gets a bit easier with pub-sub. We have an exchange which gets the messages published. The exchange distributes the messages among subscribers that have subscribed to the routing keys they need (you could say it’s the equivalent of topics).</p><h3>Scalability and fault-tolerance</h3><p>System scalability generally depends on the scalability of its layers and components:</p><ul><li>Services are scaled by adding extra nodes with the service handlers to the cluster. One can choose the optimal routing policy during the trial operation.</li><li>The messaging service itself within a certain cluster is generally scaled either by moving the most loaded exchanges to separate cluster nodes or by adding proxy processes to the most loaded cluster zones.</li><li>The whole system scalability depends on the flexibility of architecture and an opportunity to unite separate clusters into one logical entity.</li></ul><p>Project success often depends on simplicity, fast transformation and scalability. Messaging in current implementation is growing with the app. Even if the cluster of 50–60 machines is not enough for us, we can use a federation. Unfortunately, the issues of federation extend beyond this particular article.</p><h3>Reservation</h3><p>We have already discussed service controllers reservation while talking about load balancing. However, messaging should be reserved too. If a node or a machine fails, messaging must automatically recover as quickly as possible.</p><p>In my projects I use additional nodes which can take part of the load in case of a failure. Erlang has a standard realization of distributed mode for OTP apps. Distributed mode is responsible for recovery by running the fallen app on another node which has been started beforehand. The process is clear: after a failure, the app automatically moves to the failover node. You can get more details about this functionality <a href="http://erlang.org/doc/design_principles/distributed_applications.html">here</a>.</p><h3>Performance</h3><p>Let’s try, at least roughly, to compare rabbitmq performance with the one of our customized messaging.</p><p>I’ve come across the official test results of rabbitmq from openstack team:</p><p>(<a href="https://docs.openstack.org/developer/performance-docs/test_results/mq/rabbitmq/cmsm/index.html">https://docs.openstack.org/developer/performance-docs/test_results/mq/rabbitmq/cmsm/index.html</a>).</p><p>In point 6.14.1.2.1.2.2. of the document the following RPC CAST result is shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*nHnAhlnQjv-l8163" /></figure><p>Let’s not use any advanced settings of OS kernel or erlang VM.</p><p>Testing environment:</p><ul><li>erl opts: +A1 +sbtu.</li><li>Test within one node is run on a laptop with an old mobile version of Intel i7.</li><li>Cluster tests are run on the servers with 10G network.</li><li>Code works in docker containers. The network is in NAT mode.</li></ul><p>The code for the test:</p><pre>req_resp_bench(_) -&gt;</pre><pre>   W = perftest:comprehensive(10000,</pre><pre>        fun() -&gt;</pre><pre>           messaging:request(?EXCHANGE, default, ping, self()),</pre><pre>           receive</pre><pre>              #&#39;$msg&#39;{message = pong} -&gt; ok</pre><pre>           after 5000 -&gt;</pre><pre>             throw(timeout)</pre><pre>           end</pre><pre>        end</pre><pre>   ),</pre><pre>   true = lists:any(fun(E) -&gt; E &gt;= 30000 end, W),</pre><pre>   ok.</pre><p>Scenario 1: The test is run on a laptop with an old mobile version of Intel i7. The test, messaging and service are all implemented on the same node and in one docker-container:</p><p>Sequential 10000 cycles in ~0 seconds (26987 cycles/s)</p><p>Sequential 20000 cycles in ~1 seconds (26915 cycles/s)</p><p>Sequential 100000 cycles in ~4 seconds (26957 cycles/s)</p><p>Parallel 2 100000 cycles in ~2 seconds (44240 cycles/s)</p><p>Parallel 4 100000 cycles in ~2 seconds (53459 cycles/s)</p><p>Parallel 10 100000 cycles in ~2 seconds (52283 cycles/s)</p><p>Parallel 100 100000 cycles in ~3 seconds (49317 cycles/s)</p><p>Scenario 2: 3 nodes are run on various machines via docker (NAT).</p><p>Sequential 10000 cycles in ~1 seconds (8684 cycles/s)</p><p>Sequential 20000 cycles in ~2 seconds (8424 cycles/s)</p><p>Sequential 100000 cycles in ~12 seconds (8655 cycles/s)</p><p>Parallel 2 100000 cycles in ~7 seconds (15160 cycles/s)</p><p>Parallel 4 100000 cycles in ~5 seconds (19133 cycles/s)</p><p>Parallel 10 100000 cycles in ~4 seconds (24399 cycles/s)</p><p>Parallel 100 100000 cycles in ~3 seconds (34517 cycles/s)</p><p>In all cases CPU utilization hasn’t exceeded 250%.</p><h3>Results</h3><p>I hope this series doesn’t look like a brain dump and my experience will be of real use both for distributed systems researchers and for practitioners who are just starting out. I’m sure that some of them are looking at Erlang/Elixir with interest but have their doubts.</p><p><em>Announcement</em>.</p><p>In early autumn I am going to publish one more article series about queueing systems engineering: ‘<strong>VTrade experiment — an attempt to write a framework for trading systems</strong>’. In this series we will address theory and practice of building a trading exchange, an auction and a shop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f792b3fe893f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-distributed-apps-second-approximation-f792b3fe893f">Building distributed apps: second approximation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building distributed apps: first approximation]]></title>
            <link>https://medium.com/data-science/building-distributed-apps-first-approximation-2bbab777f6b2?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bbab777f6b2</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Mon, 08 Apr 2019 18:51:14 GMT</pubDate>
            <atom:updated>2019-04-09T13:18:42.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*u4If3GpMU-jXmKRH" /></figure><p>In the <a href="https://towardsdatascience.com/building-distributed-apps-zero-approximation-b0c4b16f92d3">previous article</a> we have addressed the theoretical basics or reactive architecture. Now it’s time to talk about data flows, ways of implementing reactive Erlang/Elixir systems, and message exchange patterns included in them:</p><ul><li>Request-response</li><li>Request-Chunked Response</li><li>Response with Request</li><li>Publish-subscribe</li><li>Inverted Publish-subscribe</li><li>Task distribution</li></ul><h3>SOA, MSA and messaging</h3><p>SOA and MSA are service architectures which define the rules of system development. Messaging, in its turn, provides us with primitives for their implementation.</p><p>I don’t want to advocate for any particular type of architecture. I’m all for using the practices which fully meet the needs of a certain project or business. Whatever paradigm we might choose, system components should be created with Unix-way in mind: components with minimal connectivity which are implementing different system entities. API methods perform basic actions on entities.</p><p>Messaging, as we can guess from the name, is a message broker. Its main aim is to receive and send messages. Also, it is responsible for message sending interfaces, creating of logical data communication channels, routing, balancing, and handling failures at the system level.</p><p>Messaging which is being developed does not try to compete with Rabbitmq or replace it. Among its main features are the following:</p><ul><li><em>Distributed nature</em>. Exchanges can be created at any node of the cluster, as close as possible to the code which is exploiting them.</li><li><em>Simplicity</em>. Orientation towards usability and minimization of boilerplate code.</li><li><em>Better performance</em>. We are not trying to reproduce Rabbitmq functionality. We are just highlighting architectural and transport layers and embedding them into OTP, reducing the costs at the same time.</li><li><em>Flexibility</em>. Every service can integrate a number of exchange patterns.</li><li><em>Fault tolerance</em> embodied in design.</li><li><em>Scalability</em>. Messaging is growing together with the app. As the load increases, we can put some exchange points to separate machines.</li></ul><p><em>Note.</em><strong> </strong>In terms of code organization, meta-projects aka umbrella projects are a good fit for complicated systems in Erlang/Elixir. All the project code is located in one repository — umbrella project. At the same time, microservices are isolated as much as possible and perform simple actions which are responsible for a separate entity. Under this approach, it’s easy to support the API of the whole system. You can also make changes and write unit or integrative tests effortlessly.</p><p>In service architectures components interact directly or via broker. From messaging point of view, every service has a number of life stages:</p><ul><li><em>Service initialization</em>. At this stage initialization and start of the process with all its dependencies takes place.</li><li><em>Creating an exchange</em>. Service can use a static exchange, given in node config, or create exchanges dynamically.</li><li><em>Service registration</em>. Service must be registered on an exchange to be able to handle the requests.</li><li><em>Normal working</em>. In this mode service is processing user’s requests.</li><li><em>Termination of the process</em>. There are two possible ways of termination: a normal one and a crash one. In the first case, the service disconnects from the exchange and stops. In case of a crash, however, messaging performs one of the scenarios of handling the failures.</li></ul><p>That might look a bit complicated, but actually it’s not that bad if you take a look at the code. Some code samples will be presented in this article a little later.</p><h3>Exchanges</h3><p>Exchange is an internal process of messaging service. It provides logic of interaction between different system components within defined message exchange pattern.</p><p>In all the examples below the components interact via exchanges whose combination creates messaging.</p><h3>Message exchange patterns (MEPs)</h3><p>Generally, all MEPs can be divided into two-way and one-way patterns. The former imply a response to the received message, the later do not. A classic case of a two-way MEP in client-server architecture is Request-response template. Let’s take a closer look at this one and its modifications.</p><h3>Request-response or RPC</h3><p>RPC is used when we need to get a response from another process. This process can be started at the same node or even be located on a different continent. Below you can see the diagram which demonstrates client-server interaction via messaging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*UKhmtY3EwYTqQPE5" /></figure><p>Since messaging is fully asynchronous, exchange for a client includes 2 stages:</p><ul><li>Sending a request.</li></ul><pre>messaging:request(Exchange, ResponseMatchingTag, RequestDefinition, HandlerProcess)</pre><p><em>Exchange</em> is a unique exchange name</p><p><em>ResponseMatchingTag</em> ‒ a local tag for processing the response. For instance, when several identical requests which belong to different users are being sent.</p><p><em>RequestDefinition </em>‒<em> </em>request body</p><p><em>HandlerProcess </em>‒ handler PID. This process will get a server response.</p><ul><li>Receiving a response</li></ul><pre>handle_info(#&#39;$msg&#39;{exchange = EXCHANGE, tag = ResponseMatchingTag,message = ResponsePayload}, State)</pre><p><em>ResponsePayload</em> is server response.</p><p>For a server, the process is carried out in two stages too:</p><ol><li>Exchange initialization</li><li>Processing of requests</li></ol><p>This pattern can be illustrated by the code. Let’s imagine that we have to create some simple service which provides one method for precise time.</p><p>First, let’s put API definition code into <strong>api.hrl</strong>:</p><pre>%% =====================================================</pre><pre>%%  entities</pre><pre>%% =====================================================</pre><pre>-record(time, {</pre><pre>   unixtime :: non_neg_integer(),</pre><pre>   datetime :: binary()</pre><pre>}).</pre><pre>-record(time_error, {</pre><pre>   code :: non_neg_integer(),</pre><pre>   error :: term()</pre><pre>}).</pre><pre>%% =====================================================</pre><pre>%%  methods</pre><pre>%% =====================================================</pre><pre>-record(time_req, {</pre><pre>   opts :: term()</pre><pre>}).</pre><pre>-record(time_resp, {</pre><pre>   result :: #time{} | #time_error{}</pre><pre>}).</pre><p>Let’s define service controller in <strong>time_controller.erl</strong></p><pre>%% The example shows the main code only. If you insert it into gen_server pattern, you will get a proper working service.</pre><pre>%% gen_server initialization</pre><pre>init(Args) -&gt;</pre><pre>   %% connection to exchange</pre><pre>   messaging:monitor_exchange(req_resp, ?EXCHANGE, default, self())</pre><pre>   {ok, #{}}.</pre><pre>%% processing of exchange disconnection events. The same happens if an exchange hasn’t been run yet.</pre><pre>handle_info(#exchange_die{exchange = ?EXCHANGE}, State) -&gt;</pre><pre>   erlang:send(self(), monitor_exchange),</pre><pre>   {noreply, State};</pre><pre>%% API processing</pre><pre>handle_info(#time_req{opts = _Opts}, State) -&gt;</pre><pre>   messaging:response_once(Client, #time_resp{</pre><pre>      result = #time{ unixtime = time_utils:unixtime(now()),       datetime = time_utils:iso8601_fmt(now())}</pre><pre>   });</pre><pre>   {noreply, State};</pre><pre>%% gen_server termination</pre><pre>terminate(_Reason, _State) -&gt;</pre><pre>   messaging:demonitor_exchange(req_resp, ?EXCHANGE, default, self()),</pre><pre>   ok.</pre><p>The client code is placed in <strong>client.erl. </strong>To send a request to the service, we can call messaging request API in any part of the client:</p><pre>case messaging:request(?EXCHANGE, tag, #time_req{opts = #{}}, self()) of</pre><pre>    ok -&gt; ok;</pre><pre>    _ -&gt; %% repeat or fail logic</pre><pre>end</pre><p>We don’t know state of the system because its depends on state of various of system components when request arrived. When a request comes, messaging can be not running yet, or service controller may be not ready to process the request. That’s why we have to check messaging response and process a failure.</p><p>If a request is delivered, the service can answer with a response or a failure. Let’s process both cases in <em>handle_info</em>:</p><pre>handle_info(#&#39;$msg&#39;{exchange = ?EXCHANGE, tag = tag, message = #time_resp{result = #time{unixtime = Utime}}}, State) -&gt;</pre><pre>    ?debugVal(Utime),</pre><pre>    {noreply, State};</pre><pre>handle_info(#&#39;$msg&#39;{exchange = ?EXCHANGE, tag = tag, message = #time_resp{result = #time_error{code = ErrorCode}}}, State) -&gt;</pre><pre>    ?debugVal({error, ErrorCode}),</pre><pre>    {noreply, State};</pre><h3>Request-Chunked Response</h3><p>It’s safer not to send huge messages as they might affect system responsiveness and performance in general. If a response takes up too much memory, splitting is crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*qqpR1DD8chGBvO30" /></figure><p>Here is a couple of examples:</p><ul><li>Components are exchanging binary data ‒ some files, for example. Splitting a response into small chunks helps us work with files of any size and prevent memory overflow.</li><li>Listings ‒ for instance, we need to select and transmit all the rows of huge table in database to another component.</li></ul><p>Such responses sometimes look like a train. Anyway, 1024 1-MB messages are better than a single 1-GB message.</p><p>Erlang cluster constitutes an additional benefit ‒ the load on the exchange and network is reduced as the responses go to the receiver directly, bypassing the exchange.</p><h3>Response with Request</h3><p>This one is quite a rare modification of RPC pattern for building dialogue systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*1EeRLq8ix3ok0mzW" /></figure><h3>Publish-subscribe (data distribution tree)</h3><p>Event-driven systems deliver data to users when it is ready. Systems are more inclined to a push-model than to pull or poll ones. This feature enables us not to waste resources while constantly requesting and waiting for data.</p><p>The illustration shows the process of message distribution to users subscribed to a certain topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*S92ZnrK1PDvxRRgP" /></figure><p>A classic case of this pattern usage is state distribution: it can be game world in computer games, market data on financial exchanges, or useful information in datafeeds.</p><p>Take a look at the subscriber code:</p><pre>init(_Args) -&gt;</pre><pre>   %% subscribe to exchange, routing key = key</pre><pre>   messaging:subscribe(?SUBSCRIPTION, key, tag, self()),</pre><pre>   {ok, #{}}.</pre><pre>handle_info(#exchange_die{exchange = ?SUBSCRIPTION}, State) -&gt;</pre><pre>    %% if an exchange is unavailable, we are trying to reconnect to it</pre><pre>    messaging:subscribe(?SUBSCRIPTION, key, tag, self()),</pre><pre>    {noreply, State};</pre><pre>%% process received messages</pre><pre>handle_info(#&#39;$msg&#39;{exchange = ?SUBSCRIPTION, message = Msg}, State) -&gt;</pre><pre>    ?debugVal(Msg),</pre><pre>    {noreply, State};</pre><pre>%% if a consumer stops, disconnect from exchange</pre><pre>terminate(_Reason, _State) -&gt;</pre><pre>    messaging:unsubscribe(?SUBSCRIPTION, key, tag, self()),</pre><pre>    ok.</pre><p>Publisher can publish the message in any suitable place by function call:</p><pre>messaging:publish_message(Exchange, Key, Message)</pre><p><em>Exchange</em> ‒ exchange name,</p><p><em>Key</em> ‒ routing key,</p><p><em>Message</em> ‒ payload.</p><h3>Inverted Publish-subscribe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*yaapxaXcTkMouDpz" /></figure><p>When we invert the pub-sub, we get a pattern which is good for logging. The set of producers and consumers can vary a great deal. The diagram shows a case with one consumer and a number of producers.</p><h3>Task distribution pattern</h3><p>Nearly every project challenges us with postponed processing tasks like generating reports, delivery of notifications, getting data from third-party systems. The system capacity is easily scaled by adding workers. All that remains now is to make up a cluster of workers and distribute tasks between them evenly.</p><p>Let’s consider an example with 3 workers. At the stage of distributing tasks we are faced with the question of the fairness of this distribution and workers overload. Round-robin will be responsible for providing fairness, while prefetch_limit will prevent workers overload. In transient modes prefetch_limit will not allow one worker to get all the tasks.</p><p>Messaging controls queues and processing priority. Workers get tasks as they come. Any task can be completed either successfully or with a failure.</p><ul><li><em>messaging:ack(Tack)</em> ‒ is called when a message is successfully processed</li><li><em>messaging:nack(Tack)</em> ‒ is called in all emergency situations. After having a task back, messaging will resend it to another worker.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*VZle1dGFgOLeUSsW" /></figure><p>Let’s suppose that a complex failure has happened in processing 3 tasks. Worker 1 crashes after getting the task and fails to inform the exchange. In this case, the exchange redirects the task to another worker on expiry of <em>ack</em> timeout. Worker 3, for some reason, rejects the task and sends <em>nack. </em>As a result, the task goes to another worker which manages to complete it.</p><h3>Preliminary conclusion</h3><p>In this article we have taken a closer look at the main building bricks of distributed systems. We have also gained basic understanding of their implementation in Erlang/Elixir.</p><p>By combining basic patterns, you can build complex paradigms to deal with emerging challenges.</p><p>The final part will focus on some general questions of managing services, routing, and balancing. We will also talk about the practical side of system scalability and fault tolerance.</p><p>The end of the second part.</p><p>Photo by <a href="https://unsplash.com/photos/UXfi8LyqGDk">Marius Christensen</a></p><p>Illustrations made with websequencediagrams.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bbab777f6b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-distributed-apps-first-approximation-2bbab777f6b2">Building distributed apps: first approximation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building distributed apps: zero approximation]]></title>
            <link>https://medium.com/data-science/building-distributed-apps-zero-approximation-b0c4b16f92d3?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c4b16f92d3</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 09:24:13 GMT</pubDate>
            <atom:updated>2019-04-02T13:22:48.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xwBA2_wxVkogia3oczKpEA.jpeg" /></figure><p>These days, the world is moving fast. Progress constantly creates new technological challenges. Information systems architecture should be flexible enough to respond to new requirements and evolve. In this article, we are going to talk about event-driven architecture, concurrency, parallelism, asynchrony, and how to live in peace with all that in Erlang.</p><h3>Introduction</h3><p>We, as developers, opt for this or that type of information exchange depending on the system size and requirements. In most cases, what you can use to coordinate services is a pattern with a broker, for example, based on RabbitMQ or kafka. Sometimes the event stream, SLA, and the level of control over the system are such that ready-made messaging doesn’t suit us. Of course, you can complicate the system a little bit and use ZeroMQ or nanomsg. By doing so, you will take responsibility for the transport layer and cluster formation. But if the system lacks throughput or standard Erlang cluster capacity, then the question of adding an extra entity requires examination and economic rationale.</p><p>The topic of reactive distributed applications is quite vast. In order to meet the format of the article, today we will focus on homogeneous environments built on Erlang/Elixir. Erlang/OTP ecosystem enables us to implement reactive architecture with the least time and effort. Anyway, we will need a messaging layer.</p><h3>Theoretical framework</h3><p>Engineering starts with defining the goals and limitations. The main aim doesn’t lie in the area of development for the sake of development. What we need is to get a safe and scalable tool which will let us create and develop modern applications of various levels. The apps may vary from single server applications that serve a small audience to 50–60 node clusters or cluster federations. Thus, our main aim is to maximize profit by reducing the system development and ownership costs.</p><p>Let’s emphasize 4 requirements for the target system:</p><ul><li><strong>S</strong>calability. Separate units can be scaled both vertically and horizontally. There should also be an opportunity to scale the whole system horizontally with no limits;</li><li><strong>E</strong>vent-driven nature. The system is always ready to deal with the events flow and process it;</li><li><strong>L</strong>atency which is guaranteed. Time is money, so the users shouldn’t wait for too long;</li><li><strong>F</strong>ault tolerance. All levels and services have to be restored automatically in case of a failure.</li></ul><p>The system can advance from the MVP stage and be progressive if its basis satisfies the minimum requirements of <strong>SELF</strong>. Messaging as an infrastructure tool and basis for all the services is characterized by its usability for programmers too.</p><h3>Event-driven nature</h3><p>So that an app could grow from one server to a cluster, its architecture should provide loose coupling. This requirement is met in an asynchronous model. Within such a model, both a sender and a receiver care about the information load of their message and do not worry about message passing or routing.</p><h3>Scalability</h3><p>Scalability and system performance often go hand in hand. App components must be able to utilize all resources available. The more effectively we can use capacities and the more optimal our processing methods are, the less money we spend on equipment. <br>Within a single machine, Erlang creates highly concurrent environment. The balance between parallelism and concurrency can be set via selection of the number of OS threads accessible for Erlang VM, as well as the number of schedulers which utilize these threads.</p><p>Erlang processes don’t have shared state and work in non-blocking mode. This provides relatively low latency and higher throughput than traditional blocking sync apps have. Erlang scheduler takes care of fair CPU and IO allocation. The absence of blockages enables the app to respond even in case of peak load or failures.</p><p>At a cluster level, the problem of utilization also exists. It’s important to distribute the load evenly between the machines in a cluster and not to overload the network. Imagine: user traffic is landing on load balancers (e.x. haproxy, nginx, etc). These balancers are distributing requests between available handlers in servers pool. Within app infrastructure, the service which implements the interface required is just the last mile. It has to request a number of other services to respond to the initial query. Internal requests require routing and balancing too. <br>To manage data flows properly, messaging should provide developers with an interface for controlling routing and load distribution. As a result of this, developers will be able to use microservice patterns and solve both routine tasks and non-standard ones.</p><p>From a business perspective, scalability is one of the tools for risk management. The key thing here is to meet the client’s needs and use the hardware efficiently:</p><ul><li>If you improve the performance of hardware through progress, the hardware won’t stand idle because of software imperfections. Erlang can be perfectly scaled vertically and is able to utilize all CPU kernels and the memory available;</li><li>Within cloud environments, we can manage the amount of hardware depending on current or predicted load and ensure SLA.</li></ul><h3>Fault tolerance</h3><p>Let’s consider two axioms: ‘Failures are unacceptable.’ and ‘There will always be failures.’ For any business, a software failure means lost money and, what’s much worse, loss of reputation. Even teetering between potential losses and the development cost for fault-tolerant software, it’s usually possible to reach a compromise.</p><p>In the short term, fault-tolerant architecture saves money on purchasing ready-made clustering solutions. They might cost you an arm and a leg, and contain errors.</p><p>In the long term, fault-tolerant architecture pays off its costs many times over at all stages of development.</p><p>Messaging inside the code base enables you to elaborate components relationships in a system at the development stage. This facilitates the task of managing the faults as all the responsible components process the faults, and the target system with automatic fail-over knows how to restore itself to a normal state after a fault by design.</p><h3>Responsiveness</h3><p>Regardless of faults, your app should respond to queries and comply with SLA. The reality is that people nowadays are not ready to wait. Consequently, business must adjust. More and more apps are expected to be highly responsive.</p><p>Responsive applications work in near real-time mode. Erlang VM operates in soft real-time mode. For some fields, however, like stock exchange, medicine, or industrial equipment the hard real-time mode is crucial. Responsive systems improve UX and help business.</p><h3>Preliminary conclusion</h3><p>When I was planning this article, I wanted to share my experience of creating a message broker with further building of complex systems based on it. However, the theoretical and motivational part turned out to be too extensive.</p><p>In the second part of the article we’ll talk about the nuances of exchange points implementation, and message exchange patterns.</p><p>The third part will be devoted to some general issues of arrangement of services, routing, and balancing. Also, we’ll talk about the practical side of scalability and fault tolerance.</p><p>The end of the first part.</p><p>Photo by <a href="https://unsplash.com/photos/SRjZtxsK3Os">Luca Bravo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c4b16f92d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-distributed-apps-zero-approximation-b0c4b16f92d3">Building distributed apps: zero approximation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erlang/Elixir solutions: struggle for quality]]></title>
            <link>https://medium.com/data-science/erlang-elixir-solutions-struggle-for-quality-2bd0a63de057?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd0a63de057</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 18:00:35 GMT</pubDate>
            <atom:updated>2019-03-06T14:31:40.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*C-gD5NmH1JcNPWQB" /><figcaption>@<a href="https://unsplash.com/@jcutrer">jcutrer</a></figcaption></figure><p>Today we are going to talk about logs, quantitative metrics, and how to observe them in order to increase the team reaction rate and reduce the system waiting time in case of an incident.</p><p>Erlang/OTP as a framework and ideology of developing distributed systems provides us with regulated approaches to development, proper tools, and implementation of standard components. Let’s assume that we have exploited OTP’s potential and have gone all the way from prototype to production. Our Erlang project feels perfectly fine on production servers. The code base is constantly developing, new requirements are emerging alongside with functionality, new people are joining the team. Everything is, like…fine? However, from time to time something might go wrong and any technical issues combined with human factor lead to crash.</p><p>As you just can’t have all the bases covered and foresee all the potential dangers of failures and problems, then you have to reduce the system waiting time via proper management and software solutions.</p><p>In any information system there is a risk of failures of a different nature, such as:</p><ul><li>hardware and power failures</li><li>network failures: configuration mistakes and broken or out of date firmware</li><li>logical mistakes: from algorithm coding problems to architecture-related issues which appear at the border of subsystems and systems</li><li>safety issues alongside with cyber attacks and hacks, including internal falsification</li></ul><p>First, let’s delineate the responsibilities. Infrastructure monitoring will deal with networking software and data transmission networks. Such monitoring might be organized with the help of zabbix. Much has been written about its setup, and we are not going to repeat it.</p><p>From developer’s point of view, the problem of access and quality is closely connected to early detection of errors and performance issues, as well as quick response to them. To do so, you need certain approaches and assessment tools. Well, let’s try to figure out quantitative metrics. By analyzing them on different stages of project development and operation, we can significantly improve its quality.</p><h3>Build systems</h3><p>Let us begin with recalling, once again, how vital engineering approach is in testing and developing software. Erlang/OTP offers not one, but two testing frameworks: eunit and common test.</p><p>We can use the number of successful or problematic tests, their run-time and test coverage as metrics for primary assessment of the code base and its dynamics. Both frameworks enable us to save test results in Junit. For instance, with rebar3 and ct you need to add the following into rebar.config:</p><blockquote>{cover_enabled, true}.<br>{cover_export_enabled, true}.<br>{ct_opts,[<br> {ct_hooks, [{cth_surefire, [{path, “report.xml”}]}]}<br>]}.</blockquote><p>The number of successful and failed tests makes it possible to build a trend chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYEAL5i_BmN19K9U" /></figure><p>By looking at it, you can assess team’s performance and tests regression. For example, you can get a graph like this in Jenkins, using Test Results Analyzer Plugin. Usage of metrics allows you to notice and prevent breaking or slowing down the project tests and fix problems before releasing</p><h3>Application metrics</h3><p>Apart from OS metrics, application metrics should also be included into monitoring. It might be page views per second, number of payments, and other crucial indicators.</p><p>In my own projects I use the code template <em>${application}.${metrics_type}.${name}</em> for naming the metrics. This naming helps to get metric lists like</p><blockquote><em>messaging.systime_subs.messages.delivered = 1654</em></blockquote><blockquote><em>messaging.systime_subs.messages.proxied = 0</em></blockquote><blockquote><em>messaging.systime_subs.messages.published = 1655</em></blockquote><blockquote><em>messaging.systime_subs.messages.skipped = 3</em></blockquote><p>The more metrics we have, the easier it is to get an idea of what’s going on within a complicated system.</p><h3>Erlang VM metrics</h3><p>Special attention should be given to Erlang VM monitoring. ‘Let it crash’ ideology is truly wonderful, and proper usage of OTP will definitely help you out in restoring applications and processes. But don’t forget about Erlang VM itself: although it’s difficult to crash it, but still possible. All potential cases are based on running out of resources. Let’s list the most popular ones:</p><p><strong>Atom table overflow.</strong></p><p>Atoms perform as identificators whose main aim is to improve code readability. Once created, they stay in Erlang VM memory forever because they are not cleaned away by the garbage collector. Why is that? Well, the garbage collector is working within each process just with this process data. Atoms, in their turn, might be distributed across data structures of a number of processes. 1,048,576 atoms can be created by default. In the articles on killing Erlang VM you will probably come across something like that:</p><blockquote>[list_to_atom(integer_to_list(I)) || I &lt;- lists:seq(erlang:system_info(atom_count), erlang:system_info(atom_limit))]</blockquote><p>as an illustration of the above-mentioned effect. This problem looks quite artificial and unlikely to happen in real systems. There have been cases, though… For instance, in an an external API handler in queries analysis <em>binary_to_atom/2</em> is used instead of <em>binary_to_existing_atom/2</em>, or <em>list_to_atom/1</em> instead of <em>list_to_existing_atom/1</em>.</p><p>To monitor atoms state, the following parameters are good to use:</p><ol><li><em>erlang:memory(atom_used) </em>— memory used by atoms</li><li><em>erlang:system_info(atom_count) </em>— number of atoms created in a system.</li></ol><p>Together with <em>erlang:system_info(atom_limit)</em> it’s possible to calculate atoms utilization.</p><p><strong>Processes leaking-out.</strong></p><p>It’s worth mentioning that with reaching process_limit (+P argument erl) erlang vm does not crash but falls into disrepair — even connecting to it seems impossible in such case. Eventually, running out of memory due to its allocation to leaking processes will result in erlang vm crash.</p><p>To monitor process state, let’s use the following parameters:</p><ol><li><em>erlang:system_info(process_count)</em> — the number of processes currently existing at the local node. Together with <em>erlang:system_info(process_limit)</em>, you can calculate the processes usage.</li><li><em>erlang:memory(processes) </em>— the total amount of memory currently allocated for the Erlang processes.</li><li><em>erlang:memory(processes_used)</em> — the total amount of memory currently used by the Erlang processes.</li></ol><p><strong>Mailbox overflow</strong>.</p><p>When a producer process is sending messages to a consumer process without confirmation pending is a great illustration of that. Meanwhile, <strong>receive</strong> in a consumer process is ignoring the messages because of a missing or wrong pattern. As a result, all the messages are being stored in the mailbox. Erlang has a mechanism of slowing down the sender if the processor can’t cope with the processing. However, vm crashes after available memory exhaustion anyway.</p><p>You can understand if you have any mailbox overflow issues with the help of etop.</p><blockquote>$ erl -name etop@host -hidden -s etop -s erlang halt -output text -node dest@host -setcookie some_cookie -tracing off -sort msg_q -interval 1 -lines 25</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*FlcJxdH_8EgSw2tk" /></figure><p>The number of problematic processes can be taken as metrics for constant monitoring. To identify those processes, the following function may be used:</p><blockquote>top_msq_q()-&gt;</blockquote><blockquote>[{P, RN, L, IC, ST} || P &lt;- processes(), { _, L } &lt;- [ process_info(P, message_queue_len) ], L &gt;= 1000, [{_, RN}, {_, IC}, {_, ST}] &lt;- [ process_info(P, [registered_name, initial_call, current_stacktrace]) ] ].</blockquote><p>This list can also be logged. In this case, the analysis of the problem is simplified after getting a notification from monitoring.</p><p><strong>Binary overflow.</strong></p><p>Memory for huge (more than 64 bytes) binaries is allocated on the heap. Allocated memory unit has a reference counter which shows the number of processes having access to it. After you reset the counter, clean up is performed. As easy, as that, right. However, there are some tiny little issues. For instance, there is a chance of appearing a process that will generate so much garbage that the system won’t have enough memory for clean-up.</p><p><em>erlang:memory(binary) </em>performs as metrics for monitoring. It shows the memory allocated for binaries.</p><p>All in all, we have mentioned all the cases which lead to vm crash. However, it seems rational to keep monitoring other equally important parameters which may directly or indirectly affect your apps proper functioning:</p><ul><li>ETS tables memory: <em>erlang:memory(ets)</em>.</li><li>Memory for compiled modules: <em>erlang:memory(code)</em>. If your solutions don’t use dynamic code compilation, this parameter can be excluded. <br>There should be a specific reference to erlydtl. If you compile templates dynamically, beam is created and gets loaded into vm memory. It can also lead to memory leaks.</li><li>System memory: <em>erlang:memory(system)</em>. Shows the memory used by runtime erlang.</li><li>Total memory utilization: <em>erlang:memory(total)</em>. The total amount of memory currently allocated for the Erlang processes.</li><li>Information on reductions: <em>erlang:statistics(reductions)</em></li><li>The count of all processes which are ready for execution: <em>erlang:statistics(run_queue)</em></li><li>Vm uptime: <em>erlang:statistics(runtime</em>) — enables you to understand without analysing the logs if there was a restart</li><li>Network activity: <em>erlang:statistics(io)</em></li></ul><h3>Sending metrics to zabbix</h3><p>Let’s create a file which contains app metrics and erlang vm metrics. We will update it once in N seconds. For each erlang node the metrics file must include all the apps metrics and erlang vm metrics. Eventually, we should have something like this:</p><blockquote>messaging.systime_subs.messages.delivered = 1654</blockquote><blockquote>messaging.systime_subs.messages.proxied = 0</blockquote><blockquote>messaging.systime_subs.messages.published = 1655</blockquote><blockquote>messaging.systime_subs.messages.skipped = 3</blockquote><blockquote>….</blockquote><blockquote>erlang.io.input = 2205723664</blockquote><blockquote>erlang.io.output = 1665529234</blockquote><blockquote>erlang.memory.binary = 1911136</blockquote><blockquote>erlang.memory.ets = 1642416</blockquote><blockquote>erlang.memory.processes = 23596432</blockquote><blockquote>erlang.memory.processes_used = 23598864</blockquote><blockquote>erlang.memory.system = 50883752</blockquote><blockquote>erlang.memory.total = 74446048</blockquote><blockquote>erlang.processes.count = 402</blockquote><blockquote>erlang.processes.run_queue = 0</blockquote><blockquote>erlang.reductions = 148412771</blockquote><blockquote>….</blockquote><p>With the help of <strong><em>zabbix_sender</em></strong> we’ll be sending this file to zabbix where the graphic representation will be available, alongside with the possibility to create automatization and notification triggers.</p><p>Now, as in our monitoring system there are metrics together with automatization and notification triggers, we have a chance to avoid failures and breakdowns. That’s because we are able to react to all dangerous deviations from fully functional mode in advance.</p><h3>Central log collection</h3><p>If there is just a couple of servers in a project, it’s possible to do without centralized log collecting. When a distributed system with a lot of servers, clusters and environments appears, however, it’s necessary to deal with log collecting and viewing.</p><p>To perform logging in my projects, I use lager. On the way from prototype to production, projects go through the following stages of log collecting:</p><ul><li>The simplest logging with downloading logs to a local file or even stdout (lager_file_backend)</li><li>Central log collecting with using, for instance, syslogd and sending all the logs to collector automatically. For such a scheme, <a href="https://github.com/basho/lager_syslog">lager_syslog</a> is optimal. The main disadvantage, though, is that you have to get to the log collector server, find the file with the logs required, and somehow filter the events searching for the ones you need for debugging.</li><li>Central log collecting with saving into repository with filter and search opportunities.</li></ul><p>Now, it’s time to talk about benefits, drawbacks, and quantitative metrics which you can apply using the later type of log collecting. We’ll do it by example of certain implementation — lager_clickhouse, which I use in most of my projects. There is a couple of things to say about lager_clickhouse. This is a lager backend for saving events to clickhouse. It’s an internal project so far, but there are plans to make it open. During lager_clickhouse developing, it was necessary to bypass some certain clickhouse features. For example, buffering of events was used in order not to query to clickhouse too often. The effort was paid off with steady work and good performance.</p><p>The main disadvantage of this approach with saving to repository is creating an additional entity — clickhouse. In such case, you have to write the code for saving events into it, as well as user interface for searching and analysing events. Also, for some projects using tcp for sending logs might be critical.</p><p>The advantages, as it seems to me, overweight all the possible drawbacks:</p><ol><li>Quick and easy search for events:</li></ol><ul><li>Filtering by date without having to search a file/files on the central server which contains the variety of events.</li><li>Filtering by environment. Logs from various subsystems and often from different clusters are written into the same storage. Currently, there is a division by tags. Every node can be marked by a tag or set of tags which are defined in config file of the node.</li><li>Filtering by node name.</li><li>Filtering by the name of the module which sent the message.</li><li>Filtering by event type</li><li>Text search</li></ul><p>The screenshot below demonstrates an example of log viewer interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-2XFdeN1feQRY2zk" /></figure><p>2. A possibility to fully automate the process. With implementing a log storage, it’s possible to get real-time data about the number of mistakes, critical issues, and system performance. Analysing this data in real time and imposing some limits, we can generate warnings for nonfunctional state of the system and handle it in automatic mode: execute scripts to manage the issue and send notifications:</p><ul><li>in case of a critical error</li><li>in case of an outbreak of errors</li><li>A certain metric is the event generation speed, as many new events appear in a log. You can almost always know an estimate of logs generated by project per unit of time. If it is exceeded, something is definitely going wrong.</li></ul><p>The further development of the topic of emergencies automation is the implementation of lua scripts. Any developer or administrator can write a script for processing logs and metrics. Scripts result in flexibility and enable you to create personal scenarios of automation and notification.</p><h3>Results</h3><p>Metrics and logs, alongside with proper tools to analyse them, are crucial for understanding processes within a system and investigating incidents. The more information about the system we have, the easier it is to analyse its behaviour and fix problems at an early stage. If our measures haven’t worked well, we always have graphs and detailed logs at our disposal.</p><p>How do you exploit Erlang/Elixir solutions? Ever met any interesting cases in production?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd0a63de057" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/erlang-elixir-solutions-struggle-for-quality-2bd0a63de057">Erlang/Elixir solutions: struggle for quality</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arbitrary-precision arithmetic in Erlang and Elixir]]></title>
            <link>https://medium.com/@vonmo/arbitrary-precision-arithmetic-in-erlang-and-elixir-4b3e7e95febb?source=rss-f5be4eb3fb07------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3e7e95febb</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Maxim Molchanov]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 11:18:37 GMT</pubDate>
            <atom:updated>2018-11-06T11:20:20.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*cEUSJNwuQoCJxrb2vgHTVA.jpeg" /><figcaption>Image by @rawpixel</figcaption></figure><p>Even school students know that there are different number systems. As well, they are aware of the fact that not every finite decimal fraction equals to its finite binary representation. However, not many of us realize that due to this fact all operations with floats and doubles are never precise enough.</p><p>Let’s take Erlang, for instance. As many other languages, it implements IEEE754 standard for floats while standard Integer is implemented via arbitrary-precision arithmetic. However, it would be great to have not just bigint, but also an opportunity to handle rational and complex numbers and floats with precision required.</p><p>This article provides an overview of number coding theory of floats, and the most vivid examples of possible results. It also presents the solution which ensures the necessary precision of operations through a fixed-point implementation. This solution is framed as a library EAPA (Erlang Arbitrary Precision Arithmetic) whose main aim is to meet the needs of Erlang/Elixir financial apps.</p><h3>Standards, standards, standards…</h3><p>For the time being IEEE754 is the main standard for floating-point binary arithmetic. It is widely adopted in technology and programming and has four formats of representation:</p><ul><li>single-precision 32 bit</li><li>double-precision 64 bit</li><li>single-extended precision &gt;=43 bit (rarely used)</li><li>double-extended precision &gt;= 79 bit (usually 80 bit)</li></ul><p>Also, there are four rounding modes:</p><ul><li>rounding to the nearest integer</li><li>rounding towards zero</li><li>rounding towards +∞</li><li>rounding towards -∞</li></ul><p>Most of modern microprocessors are made with a hardware implementation of real number representation in IEEE754. The number length is limited by the format, and rounding modes influence precision. Programmers are often unable to change the behaviour of equipment, or languages implementation. For example, the official implementation of Erlang stores float in 3 words on a 64-bit machine and in 4 words on a 32-bit one.</p><p>As we have said before, IEEE754 numbers are an infinite set represented as finite. That’s why every operand can be misrepresented in IEEE754.</p><p>Most numbers when represented as a finite set have stable minimal relative error. For instance, it is 11,920928955078125e-6% for a float and 2,2204460492503130808472633361816e-14% for a double. Most programmers can afford to neglect such an error, though it should be mentioned that you can be caught in the same trap because the rate of an absolute error might be up to 10³¹ and 10²⁹² for a float and a double respectively. It can be troublesome for your computing.</p><h3>Demonstration of effects</h3><p>So, let’s get back to business and try to reproduce the effects in Erlang. All the examples below are processed as ct-tests.</p><h3>Rounding and precision loss</h3><p>First things first — how about adding 0,1+0,2 = ?:</p><pre>t30000000000000004(_)-&gt;</pre><pre>  [&quot;0.30000000000000004&quot;] = io_lib:format(&quot;~w&quot;, [0.1 + 0.2]).</pre><p>The result of addition is a bit different from the one we’ve been expecting, and the test is run successfully. Let’s try to get the precise result now. To do so, we should re-write the test, using EAPA:</p><pre>t30000000000000004_eapa(_)-&gt;</pre><pre>  %% prec = 1 symbols after coma</pre><pre>  X = eapa_int:with_val(1, &lt;&lt;&quot;0.1&quot;&gt;&gt;),</pre><pre>  Y = eapa_int:with_val(1, &lt;&lt;&quot;0.2&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;0.3&quot;&gt;&gt; = eapa_int:to_float(1, eapa_int:add(X, Y)).</pre><p>This test is also successful and shows us that the problem has been solved. However, we keep on experimenting and add just a tiny value to 1.0:</p><pre>tiny(_)-&gt;</pre><pre>  X = 1.0,</pre><pre>  Y = 0.0000000000000000000000001,</pre><pre>  1.0 = X + Y.</pre><p>As we can see, our addition has been left unnoticed. Let’s try to fix it and, as well, show one of the library functions which is the autoscaling:</p><pre>tiny_eapa(_)-&gt;</pre><pre>  X1 = eapa_int:with_val(1, &lt;&lt;&quot;1.0&quot;&gt;&gt;),</pre><pre>  X2 = eapa_int:with_val(25, &lt;&lt;&quot;0.0000000000000000000000001&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;1.0000000000000000000000001&quot;&gt;&gt; = eapa_int:to_float(<br>                                         eapa_int:add(X1, X2)<br>                                      ).</pre><h3>Word size overflow</h3><p>Apart from the issues related to small numbers, one might overcome quite a significant problem of overflow.</p><pre>float_overflow(_) -&gt;</pre><pre>  1.0 = 9007199254740991.0 - 9007199254740990.0,</pre><pre>  1.0 = 9007199254740992.0 - 9007199254740991.0,</pre><pre>  0.0 = 9007199254740993.0 - 9007199254740992.0,</pre><pre>  2.0 = 9007199254740994.0 - 9007199254740993.0.</pre><p>As can be seen from the test, at some point the difference stops being equal to 1.0. EAPA helps solve this problem too:</p><pre>float_overflow_eapa(_)-&gt;</pre><pre>  X11 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740992.0&quot;&gt;&gt;),</pre><pre>  X21 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740991.0&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;1.0&quot;&gt;&gt; = eapa_int:to_float(1, eapa_int:sub(X11, X21)),</pre><pre>  X12 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740993.0&quot;&gt;&gt;),</pre><pre>  X22 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740992.0&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;1.0&quot;&gt;&gt; = eapa_int:to_float(1, eapa_int:sub(X12, X22)),</pre><pre>  X13 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740994.0&quot;&gt;&gt;),</pre><pre>  X23 = eapa_int:with_val(1, &lt;&lt;&quot;9007199254740993.0&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;1.0&quot;&gt;&gt; = eapa_int:to_float(1, eapa_int:sub(X13, X23)).</pre><h3>Dangerous reduction</h3><p>The following text is an example of how dangerous reduction might appear. It means that computing precision is reduced dramatically when we deal with operations with resulting value much smaller than input ones. In our case the result of subtraction is 1. You can see that this problem exists in Erlang:</p><pre>reduction(_)-&gt;</pre><pre>  X = float(87654321098765432),</pre><pre>  Y = float(87654321098765431),</pre><pre>  16.0 = X-Y. <em>%% has to be 1.0</em></pre><p>Somehow we’ve got 16.0 instead of anticipated 1.0. What can we do to improve it?</p><pre>reduction_eapa(_)-&gt;</pre><pre>  X = eapa_int:with_val(1, &lt;&lt;&quot;87654321098765432&quot;&gt;&gt;),</pre><pre>  Y = eapa_int:with_val(1, &lt;&lt;&quot;87654321098765431&quot;&gt;&gt;),</pre><pre>  &lt;&lt;&quot;1.0&quot;&gt;&gt; = eapa_int:to_float(eapa_int:sub(X, Y)).</pre><h3>Some more unexpected features of floating-point arithmetic in Erlang/Elixir</h3><p>Let’s start with ignoring the signed zero.</p><pre>eq(_)-&gt;</pre><pre>  true = list_to_float(&quot;0.0&quot;) =:= list_to_float(&quot;-0.0&quot;).</pre><p>It should be mentioned that EAPA sticks to such behaviour:</p><pre>eq_eapa(_)-&gt;</pre><pre>  X = eapa_int:with_val(1, &lt;&lt;&quot;0.0&quot;&gt;&gt;),</pre><pre>  Y = eapa_int:with_val(1, &lt;&lt;&quot;-0.0&quot;&gt;&gt;),</pre><pre>  true = eapa_int:eq(X, Y).</pre><p>as it is absolutely acceptable. As Erlang does not possess any clear syntax or handling NaN and infinities, it leads to a number of features like the following:</p><pre>1&gt; math:sqrt(list_to_float(&quot;-0.0&quot;)).<br>0.0</pre><p>Next thing is particular processing of big and small numbers. Let’s repeat it for small numbers:</p><pre>2&gt; list_to_float(&quot;0.&quot;++lists:duplicate(322, $0)++&quot;1&quot;).<br>1.0e-323<br>3&gt; list_to_float(&quot;0.&quot;++lists:duplicate(323, $0)++&quot;1&quot;).<br>0.0</pre><p>and for big ones:</p><pre>4&gt; list_to_float(&quot;1&quot;++lists:duplicate(308, $0)++&quot;.0&quot;).<br>1.0e308<br>5&gt; list_to_float(&quot;1&quot;++lists:duplicate(309, $0)++&quot;.0&quot;).<br>** exception error: bad argument</pre><p>Some more examples for small numbers:</p><pre>6&gt; list_to_float(&quot;0.&quot;++lists:duplicate(322, $0)++&quot;123456789&quot;).<br>1.0e-323<br>7&gt; list_to_float(&quot;0.&quot;++lists:duplicate(300, $0)++&quot;123456789&quot;).<br>1.23456789e-301</pre><p>and last one:</p><pre>8&gt; 0.123456789e-100 * 0.123456789e-100.<br>1.524157875019052e-202<br>9&gt; 0.123456789e-200 * 0.123456789e-200.<br>0.0</pre><p>All the above-mentioned examples just confirm the truth for Erlang projects: money mustn’t be calculated in IEEE754.</p><h3>EAPA</h3><p>EAPA is a NIF extension written on Rust. So far, in EAPA repository there is an <em>eapa_int</em>interface. It is as simple as possible, as well as the most convenient. This interface is used for working with fixed-point numbers. Among its main features are:</p><ol><li>No effects of IEEE754 encoding</li><li>Big numbers support</li><li>Customized precision up to 126 decimal places (current realization)</li><li>Autoscaling</li><li>Support of all main numerical operations</li><li>More or less complete testing, including property based one</li></ol><p><em>eapa_int</em> interface:</p><ul><li><em>with_val/2</em> — conversion from a float into a fixed-point representation which can be safely used with json and xml.</li><li><em>to_float/2</em> — conversion from a fixed-point number into a float with precision required.</li><li><em>to_float/1</em> — conversion from a fixed-point number into a float.</li><li><em>add/2</em> — sum of two numbers</li><li><em>sub/2</em> — difference</li><li><em>mul/2</em> — multiplication</li><li><em>divp/2</em> — division</li><li><em>min/2</em> — min number</li><li><em>max/2</em> — max number</li><li><em>eq/2</em> — equality</li><li><em>lt/2</em> — less than</li><li><em>lte/2</em> — less than or equals to</li><li><em>gt/2</em> — greater than</li><li><em>gte/2</em> — greater than or equals to</li></ul><p>You might find EAPA code in the repository<a href="https://github.com/Vonmo/eapa"> https://github.com/Vonmo/eapa</a></p><p>When is using eapa_int a good idea? For instance, if your app deals with money, or if you have to compute numbers like 92233720368547758079223372036854775807.92233720368547758079223372036854775807 precisely and with no trouble.</p><p>As almost every solution, EAPA is a bit of a compromise. We get the precision required at the expense of memory and speed. Performance tests and real systems statistics show that most of the operations are performed within 3–30 microseconds range. It should also be taken into account while choosing EAPA interface with a fixed point.</p><h3>Conclusion</h3><p>Obviously, we don’t always deal with this kind of problems in Erlang or Elixir. However, when one arises, but there isn’t a proper tool, you can do nothing but invent a solution. This article is just an attempt to share such a tool and a bit of personal experience with the community. I hope that this library might be of use for some of you and will help save your time.</p><p>Well…how do you count money in Erlang?</p><p>P.S. The following articles will be devoted to working with rational and complex numbers. They will also cover the topic of native access to Integer, Float, Complex, and Rational types of arbitrary precision. Stay tuned!</p><p>See also:</p><ul><li><a href="https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a></li><li><a href="http://steve.hollasch.net/cgindex/coding/ieeefloat.html">IEEE Standard 754 Floating Point Numbers</a></li><li><a href="http://0.30000000000000004.com/">0.30000000000000004</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3e7e95febb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>