<?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 Konstantin Ilchenko on Medium]]></title>
        <description><![CDATA[Stories by Konstantin Ilchenko on Medium]]></description>
        <link>https://medium.com/@simpl1g?source=rss-20d71d514bd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K6OVDoQ-C7NeQlUbdDunUw.jpeg</url>
            <title>Stories by Konstantin Ilchenko on Medium</title>
            <link>https://medium.com/@simpl1g?source=rss-20d71d514bd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:42:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simpl1g/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[Using your API as source for ClickHouse dictionary]]></title>
            <link>https://simpl1g.medium.com/using-your-api-as-source-for-clickhouse-dictionary-5f9e738507f1?source=rss-20d71d514bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9e738507f1</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Konstantin Ilchenko]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 15:32:40 GMT</pubDate>
            <atom:updated>2023-04-25T15:32:40.653Z</atom:updated>
            <content:encoded><![CDATA[<p>ClickHouse is an open-source column-oriented database management system that is optimised for OLAP (Online Analytical Processing) workloads. It is designed to handle large volumes of data with high performance and scalability. One of the key features of ClickHouse is its ability to use dictionaries, which can be used to read data from various sources. Most often used are jdbc/odbc, which allow to connect to most of the databases. However sometimes we need something different than DBs. In this cases we can use HTTP source Dictionary.</p><p>This is a special type of dictionary that is used to extract data from HTTP endpoints. This can be particularly useful if you have some complex business logic available in your BackEnd application. You can easily extract this information and store it in a way that is optimised for analysis by using this engine.</p><p>To use the URL engine with ClickHouse, you need to first create a dictionary that defines the structure of the URL. This dictionary should specify the different components of the URL, such as the protocol, domain, path, query string parameters, and so on. Once you have defined the dictionary, you can use it to parse URLs and extract the relevant data.</p><pre>CREATE OR REPLACE DICTIONARY default.http_test<br>(<br>    `app_id`  UInt64,<br>    `user_id` UInt64,<br>    `result`  UInt64<br>)<br>PRIMARY KEY app_id, user_id<br>SOURCE(<br> HTTP(<br>  NAME testdict<br> )<br>)<br>LAYOUT(COMPLEX_KEY_DIRECT)</pre><p>Pro tip: We use named collection here to hide sensitive information from DDL. `API_KEY` is fetched from ENV variable:</p><pre>&lt;clickhouse&gt;<br>    &lt;named_collections&gt;<br>        &lt;testdict&gt;<br>            &lt;url&gt;http://api:9292&lt;/url&gt;<br>            &lt;format&gt;CSVWithNames&lt;/format&gt;<br>            &lt;headers&gt;<br>                &lt;header&gt;<br>                    &lt;name&gt;Content-Type&lt;/name&gt;<br>                    &lt;value&gt;application/csv&lt;/value&gt;<br>                &lt;/header&gt;<br>                &lt;header&gt;<br>                    &lt;name&gt;API_KEY&lt;/name&gt;<br>                    &lt;value from_env=&quot;API_KEY&quot; /&gt;<br>                &lt;/header&gt;<br>            &lt;/headers&gt;<br>        &lt;/testdict&gt;<br>    &lt;/named_collections&gt;<br>&lt;/clickhouse&gt;</pre><p>Now we need to create API that can handle this Dictionary. Main requirements for this is:</p><ul><li>It should respond to POST request</li><li>It should also return input columns</li></ul><p>For example in our case we send app_id and user_id from ClickHouse. HTTP server should return app_id, user_id and result columns back.</p><p>Let’s build super simple API using Ruby and Rack:</p><pre>require &#39;rack&#39;<br>require &#39;polars&#39;<br><br>ACCESS_DENIED_RESPONSE = [403, {&#39;Content-Type&#39; =&gt; &#39;text/plain&#39;}, [&#39;Access Denied&#39;]]<br><br>class RackApp<br>  def call(env)<br>    return ACCESS_DENIED_RESPONSE if env[&#39;HTTP_API_KEY&#39;] != ENV[&#39;API_KEY&#39;]<br><br>    table = Polars.read_csv(env[&#39;rack.input&#39;], has_header: true)<br>    table = table.with_column((table[&#39;user_id&#39;] * table[&#39;app_id&#39;]).alias(&#39;result&#39;))<br><br>    [200, {&#39;Content-Type&#39; =&gt; &#39;application/csv&#39;}, [table.to_csv]]<br>  end<br>end<br><br>run RackApp.new</pre><p>Here we use Polars to parse CSV to DataFrame and add new column, in this example it super simple, it just multiplies app_id and user_id. In reality for example we use this API to fetch distributed IDs that we store in KV database and fill missing data in ClickHouse.</p><p>You can find full example with docker-compose in this repo <a href="https://github.com/simpl1g/clickhouse_url_dict">https://github.com/simpl1g/clickhouse_url_dict</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9e738507f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ClickHouse internal_replication setting]]></title>
            <link>https://simpl1g.medium.com/clickhouse-internal-replication-setting-b6d8c7c2a9f2?source=rss-20d71d514bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d8c7c2a9f2</guid>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[replication]]></category>
            <dc:creator><![CDATA[Konstantin Ilchenko]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 18:45:29 GMT</pubDate>
            <atom:updated>2022-11-28T18:45:29.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*ekEfMbeeP4T9s1WWuMFJag.jpeg" /></figure><p>One of the most frequently asked questions in ClickHouse community is why do I need the internal_replication configuration parameter when describing a shard section?</p><p><strong>internal_replication = false</strong> (Default)</p><p>Writes down data to all underlying replicas if we do insert in a Distributed table. In most cases <strong>you’d better not use this mode.</strong></p><p>And here is why:</p><ul><li>Replicas can diverge with time, no consistency guaranties.</li><li>If you insert in underlying table, e.g. MergeTree, data will not be replicated.</li><li>If you need to add a new replica, you will need to think how to load data into a new replica.</li></ul><p>The only case when it makes sense is if you have instances in different DC’s with high latency (like &gt; 200ms). In this case it can be problematic to maintain a replication using ZooKeeper.</p><p><strong>internal_replication = true </strong>(Use with ZooKeeper and Replicated*MergeTree)</p><p>The Distributed table inserts data only into<strong> </strong>one of underlying table replicas, after that the Replicated table replicates data into other replicas.</p><p>Only Replicated tables can be used if you need proper / good consistency.</p><p>If you have <strong>internal_replication = false</strong> and the Replicated table you will get duplicates, because the Distributed table inserts data into all replicas while underlying Replicated tables also replicate data.</p><h3>Now let’s try to replicate data using <strong>internal_replication = false</strong></h3><p>We have a cluster named shards which includes 2 shards and 2 replicas:</p><pre>&lt;remote_servers&gt;<br>  &lt;shards&gt;<br>    &lt;shard&gt;<br>      &lt;internal_replication&gt;false&lt;/internal_replication&gt;<br>      &lt;replica&gt;<br>        &lt;host&gt;clickhouse-1-1&lt;/host&gt;<br>        &lt;port&gt;9000&lt;/port&gt;<br>      &lt;/replica&gt;<br>      &lt;replica&gt;<br>        &lt;host&gt;clickhouse-1-2&lt;/host&gt;<br>        &lt;port&gt;9000&lt;/port&gt;<br>      &lt;/replica&gt;<br>    &lt;/shard&gt;<br>    &lt;shard&gt;<br>      &lt;!-- If we don&#39;t have this flag in config - it will be eq to false --&gt;  <br>      &lt;!-- &lt;internal_replication&gt;false&lt;/internal_replication&gt; --&gt;<br>      &lt;replica&gt;<br>        &lt;host&gt;clickhouse-2-1&lt;/host&gt;<br>        &lt;port&gt;9000&lt;/port&gt;<br>      &lt;/replica&gt;<br>      &lt;replica&gt;<br>        &lt;host&gt;clickhouse-2-2&lt;/host&gt;<br>        &lt;port&gt;9000&lt;/port&gt;<br>      &lt;/replica&gt;<br>    &lt;/shard&gt;<br>  &lt;/shards&gt;<br>&lt;/remote_servers&gt;</pre><p>Now let’s create simple MergeTree table for tests</p><pre>CREATE TABLE local ON CLUSTER shards<br>(<br>    `a` Int32<br>)<br>ENGINE = MergeTree<br>ORDER BY a;<br><br>CREATE TABLE distr ON CLUSTER shards AS local<br>ENGINE = Distributed(ch_shards, default, local, rand());<br><br>INSERT INTO distr VALUES (1)(2);<br><br>SELECT count() FROM distr;<br>┌─count()─┐<br>│       2 │ -- No duplicates<br>└─────────┘<br><br>SELECT count() FROM local;<br>┌─count()─┐<br>│       1 │ -- We have 1 record on clickhouse-1-1 server<br>└─────────┘<br>-- We can have same result if query via remote function<br>SELECT count() FROM remote(&#39;clickhouse-1-1&#39;, &#39;default.local&#39;);<br><br>SELECT count() FROM remote(&#39;clickhouse-1-2&#39;, &#39;default.local&#39;);<br>┌─count()─┐<br>│       1 │ -- Query returns same result for second replica of this shard<br>└─────────┘ -- Data is replicated using internal_replication = false<br><br>INSERT INTO local VALUES (3)(4);<br>SELECT count() FROM remote(&#39;clickhouse-1-1&#39;, &#39;default.local&#39;);<br>┌─count()─┐<br>│       3 │<br>└─────────┘<br>SELECT count() FROM remote(&#39;clickhouse-1-2&#39;, &#39;default.local&#39;);<br>┌─count()─┐<br>│       1 │ -- Data was not replicated, because we inserted directly to local<br>└─────────┘</pre><p>Everything works as expected, though in a real life I would not recommend such setup in production. Now try the same with ReplicatedMergeTree.</p><pre>CREATE TABLE local_replicated ON CLUSTER shards<br>(<br>    `a` Int32<br>)<br>ENGINE = ReplicatedMergeTree(&#39;/clickhouse/tables/{shard}/local_replicated&#39;, &#39;{replica}&#39;)<br>ORDER BY a;<br><br>CREATE TABLE distr_replicated ON CLUSTER cshards AS local<br>ENGINE = Distributed(ch_shards, default, local_replicated, rand());<br><br>INSERT INTO distr_replicated VALUES (1)(2);<br><br>SELECT count() FROM distr_replicated;<br>┌─count()─┐<br>│       2 │<br>└─────────┘</pre><p>Looks like we have correct numbers. And some users might think that now everything is working correctly and they have managed to setup a working cluster. The trick here is that by default CH does a deduplication of inserts. So in reality we had inserts on the each replica. But CH stores hashes of last inserted blocks in ZK and if our block has the same hash — data will not be inserted. We can check this behaviour disabling deduplication:</p><pre>SET insert_deduplicate = 0;<br>TRUNCATE TABLE local_replicated ON CLUSTER shards<br>INSERT INTO distr_replicated VALUES (&#39;a&#39;, 1)(&#39;b&#39;, 2);<br>SELECT count() FROM distr_replicated;<br>┌─count()─┐<br>│       4 │ -- This time instead of 2 records we have 4<br>└─────────┘ -- because insert has been made on each replica and then replicated</pre><h3>Conclusion</h3><p>I highly recommend setting internal_replication = true when you setup replication in CH. It will make your life easier in future and can save you hours of debugging problems :)</p><p>The situation when a worse option is default is a bit strange but this is because it had been introduced before Replicated tables even existed. Now it is impossible to change it for backward compatibility. Maybe one day an auto option will be implemented. See <a href="https://github.com/ClickHouse/ClickHouse/issues/14178">https://github.com/ClickHouse/ClickHouse/issues/14178</a> for details.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d8c7c2a9f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Big Data in Ruby]]></title>
            <link>https://simpl1g.medium.com/handling-big-data-in-ruby-405111397d28?source=rss-20d71d514bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/405111397d28</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[apache-arrow]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Konstantin Ilchenko]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 09:07:04 GMT</pubDate>
            <atom:updated>2021-12-27T09:07:04.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHjZF_6W5D9QEryCwNHcfQ.jpeg" /></figure><p>Have you ever wondered how to efficiently parse big files in Ruby, like 500Mb — 1Gb CSV?</p><p>Let’s suppose we have a 10_000_000-row file (~ 540Mb) with the following structure:</p><pre>&quot;user&quot;,&quot;revenue&quot;<br>&quot;f86fe409-42e0-469d-87e6-52b84c7f72dc&quot;,0.000492905577346</pre><p>Our task is to get total revenue from it. It is a fairly simple operation, so we just need to iterate line by line and accumulate total revenue.</p><h4>Solution 0</h4><p>I will skip solutions that try to load the whole file and then iterate through it to reduce our time :)</p><h4>Solution 1</h4><p>The first thing that comes to mind is good old <em>CSV</em>, a pretty simple solution</p><pre>sum = 0<br>CSV.foreach(filename) { |row| sum += row.last.to_f }</pre><pre>sum</pre><p>It took over 1 minute(62 seconds)!!! to iterate through the file, this is too much, let’s try to improve.</p><h4>Solution 2</h4><p>Let’s remove overhead that comes from <em>CSV</em> and try to use the plain <em>File</em> class and manual parsing</p><pre>sum = 0<br>File.foreach(filename) { |row| sum += row.split(&#39;,&#39;).last.to_f }</pre><pre>sum<br># File.open(filename).each gives similar performance</pre><p>Now it is much faster, 14 seconds on my laptop, almost 5 times quicker with small changes in code. Ok, we can end our post here. Or not?</p><h4>Solution 3</h4><p>Meet the ‘<em>red-arrow</em>’ gem and his big brother behind — <a href="https://arrow.apache.org/">Apache Arrow</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FdpdsV8K121h4ffV.png" /></figure><p>It is not only a columnar format for storing data, but also the entire ecosystem for computation written in C++, which allows you to parse not only the Arrow format, but also Parquet, CSV and ORC. It has bindings in many programming languages, including Ruby. And I would like to say thank you to <a href="https://github.com/kou">Sutou Kouhei</a>, who supports the Ruby version.</p><p>Lets’s try to build solution with Arrow.</p><pre>table = Arrow::Table.load(filename)<br>sum_function = Arrow::Function.find(&#39;sum&#39;)<br>sum_function.execute([table[&#39;revenue&#39;].data]).value.value</pre><p>Boom!💣 less than 1 second!</p><p>So what just has happened:</p><ul><li>Arrow::Table.load — reads the whole file in memory! in columnar format.</li><li>Arrow::Function#execute applies Arrow Compute function to a data frame. This is faster than applying plain Ruby sum.</li></ul><p>Of course, speed is not for free. Here are some thoughts about this gem:</p><h4>Pros:</h4><ul><li>Loads the whole file in memory, so that you can do any transformations, grouping/filtering.</li><li>It automatically does typecasting to the best possible data type. You don’t need to call ‘to_f’.</li><li>Blazing fast 🚀 It outperforms Ruby more than 10 times, especially on big datasets.</li></ul><h4>Cons:</h4><ul><li>Loads the whole file in memory. If you have 10Gb file — you need 10Gb RAM.</li><li>It is not a full data frame solution, you have to do many coding manually, like applying of compute functions.</li><li>Some of the C++ functionality is not available in the gem.</li><li>Not a lot of projects use this library, so you can find bugs, but I hope it will be adopted in the Ruby community.</li></ul><p>In the next post, I will try to cover some examples of how to use Arrow with Ruby.</p><p>Below you can find the full script that compares the performance of the three solutions above for 10_000 lines(data10k.csv) and 10_000_000 lines(data10M.csv) files.</p><p>If you know how to improve the performance — leave your ideas in the comments!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2431a57b053e5440de28f0daf40b99/href">https://medium.com/media/8e2431a57b053e5440de28f0daf40b99/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405111397d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>