<?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 Petr Janda on Medium]]></title>
        <description><![CDATA[Stories by Petr Janda on Medium]]></description>
        <link>https://medium.com/@petrjanda?source=rss-93fb977b82bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fAHIINu8eIOpamsq.jpeg</url>
            <title>Stories by Petr Janda on Medium</title>
            <link>https://medium.com/@petrjanda?source=rss-93fb977b82bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:12:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petrjanda/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[Going fast, by investing deep]]></title>
            <link>https://petrjanda.medium.com/going-fast-by-investing-deep-4f7b13491847?source=rss-93fb977b82bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f7b13491847</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Petr Janda]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 11:03:03 GMT</pubDate>
            <atom:updated>2022-04-04T12:09:38.124Z</atom:updated>
            <content:encoded><![CDATA[<p>Early-stage software startups have a hard job to do. With much less capital than their well-established competitors, they are running against time. Either iterate their way to product-market(<a href="https://brianbalfour.com/essays/product-channel-fit-for-growth">-channel-model</a>) fit or die.</p><p>From the very first day, the sense of urgency is real, and the team has to start shipping fast. Speed of delivery is everything. New features have to reach users as fast as possible, setting other concerns aside. There is no time to set a solid technology foundation in place. What’s the point of losing time with that, right? We don’t know what users want yet, it’s more important to ship features.</p><p>This approach is certainly one way to do it. I am just not sure if it’s the most efficient one. It feels like this to me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*Sf6mGYfcMnPq4t_L.jpeg" /></figure><p>With little to no foundation in place, the team risks taking incohesive directions, losing time reinventing the basics, or generating unnecessary amounts of technical debt. It feels like a missed opportunity to sit down and think twice about what would make the team the most productive in the first place.</p><h3>Lessons from the later stage</h3><p>I’ve interviewed dozens of technology leaders who run teams with hundreds of engineers, noticing an interesting pattern. When the team reaches between 80 and 100 engineers, they create a so-called Platform organization — a group of teams tasked to drive the technology ecosystem for other engineering teams. Over time these teams grow and could be around 20% of the technology organization.</p><p>The typical trigger for such investment is diminishing productivity. Adding new engineers doesn’t have the same impact as it used to anymore. Teams often reinvent the wheel, lacking a common foundation to build on. Platform teams are formulated to address that, and it usually takes months of hard work to implement meaningful organization-wide changes — they have to drive technology changes across dozens of teams.</p><p>But besides the technology itself, they have another challenge at hand: Culture has to shift too. Investments in technology platforms are new. They take time and budgets away from building the end-user product. The ROI is long-term and harder to measure. Platform teams and their leadership have to shift the status quo of what is valued and rewarded across the organization.</p><p>Not an easy job indeed.</p><p>And it makes me think: Do we have to wait till we have 80 engineers? Wouldn’t it be better to seed a different culture from the get-go?</p><h3>Layers of a technology system</h3><p>When I think about a healthy technology system that enables fast development of new functionality, I conceptually separate three essential layers:</p><ul><li>The underlying <em>Technology Platform</em> — infrastructure, build systems, deployment automation, system architecture, API management, and other standard libraries that solve everyday problems that nearly any engineering team has.</li><li><em>Core System Domain</em> — the heart of the software, that defines key system entities and how they tie together, modeling the real world into the software.</li><li><em>User Experiences</em> — the end-user-facing products that deliver value to end-users.</li></ul><p>These layers are fundamentally different. The amount of unknowns differs vastly too.</p><p>In the early days, startups don’t know what experience works the best to solve users’ needs. They will need to experiment with and iterate user experiences a lot. And fast.</p><p>In comparison, teams can make very opinionated choices very early regarding the Technology Platform that fits the type of the market and product they intend to build.</p><p>Lastly, the core system domain is a vital part of the system, where some experimentation will be needed. The quality of the model will often dictate how easy or hard it is for the team to build the features that users demand. It could be a real uphill battle if the features don’t “fit” the chosen model.</p><p>With the above in mind, we can formulate the following approach:</p><blockquote><strong><em>Start investing in the Technology Platform (very) early.<br>Invest time to find a solid core domain model.<br>Iterate fast on the user experience.</em></strong></blockquote><p>Regardless of if it’s 5, 50, or 500 people, investment in the Technology Platform has several positive effects.</p><p>It prevents teams from losing time by reinventing the same concepts twice.<br><em>Do you want to deploy code to the Kubernetes cluster?</em> <strong>✔️</strong> there is a standard way for that. <em>Do you want to set up new log monitoring?</em> <strong>✔️</strong> there is a standard way for that.<br><em>Do you want to define and release a new API?</em> <strong>✔️</strong> there is a standard way for that.<br><em>Do you want to send an event across systems?</em> <strong>✔️</strong> there is a standard way for that.</p><p>Nearly any team will have all these problems. Over and over again.</p><blockquote><strong><em>Solving known problems that we know we will keep having over and over just once is a no-brainer. Solving them in an opinionated way is a massive productivity gain and investment well-worth the time.</em></strong></blockquote><p>It has a positive effect on engineers’ well-being too. Doing repetitive work and fighting your core systems is not fun. The concept of <a href="https://sre.google/sre-book/eliminating-toil/">toil from the SRE book</a> is real. Coding in a growing system without a strong structure is not fun either. Getting ahead of this early means we can get a lot done with a smaller, happier, and more productive team.</p><blockquote><strong><em>The team, supported by a sound technology platform and solid core system domain model, can spend more time shipping features for end-users. Their investments in the platform and domain make them fast iterating on user experience.</em></strong></blockquote><h3>Early-stage technology platform in practice</h3><p>Let’s dive deeper into a more specific example. It’s important to stress that the below choices are <em>our</em> choices; there are many alternatives you can use. The important part is choosing what system we want to build and defining what technology platform we will need from the get-go.</p><blockquote><strong><em>The Technology Platform defines what system you can build. It makes some things easy and some things hard. The right technology platform that fits your product will get you closer to the technology system you want to have.</em></strong></blockquote><p>In our case, we have chosen to build a system with the following properties:</p><ul><li><strong>It’s automated.</strong> Let’s face it; no one wants to do the boring stuff. Yes, you can leave a few manual actions here and there. But you can also choose not to tolerate any. We opt-in for the latter and pay the price.</li><li><strong>It’s composed of small parts.</strong> We first build simple systems and then compose them into complex ones. We prefer a few smaller systems over one big one. Some people call this a micro-services approach.</li><li><strong>It’s loosely coupled.</strong> With a few notable exceptions, we like to think about system design as if everything around us is on fire. We prefer asynchronous communication between systems, ensuring that <em>the other system</em> can do its job when ready, maybe a little later.</li><li><strong>It’s opinionated.</strong> Suppose there are two good ways to do something. We pick one and stick with it. It helps us focus on other complex problems.</li><li><strong>It’s optimized for productivity.</strong> Repetitive work is systematically phased out.</li></ul><p>This dictates several choices we have made to make the above reality.</p><h3>Heavy investments in infrastructure automation</h3><p>We’ve heavily invested in infrastructure as code, which means everything from inviting colleagues to Github, complete deployment of Auth0, GCP networking, clusters, Kubernetes, Kafka, and storage is entirely automated. Anyone on the team can execute it from start to finish.</p><h3>Opinionated micro-service architecture</h3><p>Micro-services became a fashion in the tech industry, but we wanted to go an extra mile and create an ecosystem in which building micro-services is natural.</p><p>We define every interaction across systems in Protobuf and gRPC — we start from the protocol and generate client/server code. There is no other way to call across micro-services. We use grpc-web to bridge types from the deepest parts of the systems to the UI component.</p><p>All micro-services have a built-in async messaging. We believe being primarily asynchronous is an integral part of building micro-services — do your stuff and tell the world about it. Synchronous calls across services are infrequent; in lower single digit % of our service communication is sync.</p><p>To build a solid asynchronous backbone, we use Kafka with an opinionated configuration for low-volume high-risk scenarios where we block message publishing and wait for ACK, to high-volume, low-risk scenarios where we pump data to Kafka as fast as Kafka can take it. Publishing and consuming messages (typed by protobuf ofc) is easy.</p><p>Authentication and authorization are by the book. It just doesn’t make sense to innovate when it comes to security. All systems use JWT tokens with self-descriptive scopes and metadata to authorize requests without calling other systems.</p><p>There certainly is a lot more to building micro-services. The intention is not to solve all the potential problems up front. Instead, we focus on problems we know we have. We will expand our approach as we mature our product and overall technology system. The key is that we make explicit opinionated choices and codify them into core libraries and dev tools.</p><h3>Early investment in tools and core libraries</h3><p>We want to be equipped with the right developer tools to go fast. We buy many tools, but we have rolled up our sleeves and built our own tools to glue them all together into a cohesive experience.</p><blockquote><strong><em>If humans are good at something, </em></strong><a href="https://www.youtube.com/watch?v=KmuP8gsgWb8"><strong><em>it’s tool building</em></strong></a><strong><em>. We build tools to make previously hard things easy.</em></strong></blockquote><p>This is no different in software.</p><p>Our tooling revolves around automating everyday tasks and the life-cycle of a micro-service. We bundle all the good stuff together to facilitate the development of a cohesive technology platform.</p><p>A new micro-service can be created very fast. This is what it takes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AEcv1aQvcW_6vQzL.gif" /></figure><p>This action generated a basic micro-service. It has default libraries for access to the database, management of migrations, authentication, authorization, Kafka management, API handlers management for both gRPC and HTTP, an internal job scheduler with a backoff retry with workers that can distribute to many pods, logging, and environment variables management. The generated codebase can be further committed to our mono-repo, and CICD will parse the configuration to find what exact steps to run and how to deploy to our Kubernetes cluster.</p><blockquote><strong><em>Our internal dev tools give us easy-to-use tooling with opinions and built-in best practices. Their codebase is lean and straightforward, yet they already do </em>a lot<em> of heavy lifting.</em></strong></blockquote><p>And so, in a couple of minutes, we have a running micro-service. This approach lives up to all fundamental system properties we wanted — it is an automated, opinionated, and productivity-optimized way to work towards a composable, loosely coupled system.</p><h3>Path forward</h3><p>Our current technology platform addresses some of our already repetitive problems. The cost was about 10 days of work so far and we are getting great value for this relatively small investment — we can spend more time building user experiences.</p><p>Even better, we are seeding a culture of productivity from the beginning. Throughout our journey, we want to think critically about where does our delivery speed come from. Sometimes it makes sense to ship more features, sometimes to take a step back and expand our technology platform first.</p><p>— —</p><p><em>Get in touch, if you like to geek out about engineering productivity and technology platforms. I am at petr@synq.to.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f7b13491847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large scala analytics aggregations with Monoids in Scala]]></title>
            <link>https://petrjanda.medium.com/large-scala-analytics-aggregations-with-monoids-in-scala-fbdc779ccd28?source=rss-93fb977b82bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbdc779ccd28</guid>
            <category><![CDATA[adtech]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Petr Janda]]></dc:creator>
            <pubDate>Fri, 30 Oct 2015 16:25:44 GMT</pubDate>
            <atom:updated>2015-11-01T17:23:17.626Z</atom:updated>
            <content:encoded><![CDATA[<p>At GlobalWebIndex we work on several challenging problems, one of which is large scale analytics system behind our new product. From the data processing point of view its very similar to other ad-tech systems. We have an impression log, which gets a new line each time our javascript tag is trigger on any of the campaigns / websites we are tracking. Each line contains <em>cookie id</em> with handful of other attributes.</p><p>Aside of more complex analytics requirements, we want to be able to calculate several aggregations — total number of impressions, total unique cookies or average number of impressions per cookie. Even though these are very basic, they are quite expensive to calculate on the scale of hundreds of millions or billions.</p><p>—</p><p><em>For the further elaboration I will use dataset of 39M impressions in the log with about 10M unique UUIDs which in total is about 1.4GB dataset.</em></p><h4>Building the aggregations</h4><p>Lets start with a simple aggregation — number of total impressions — which will help us understand few common aggregation attributes we are looking for . As my target is to build a general solution which can scale to billions I have to make sure my calculations can be made incremental. This means that I should be able to calculate total impressions by day, or by campaign or by any other reasonable partitioning.</p><p>It turns out that we can find inspiration in abstract algebra. Its again a mythical Monoid. In order to make my aggregation a Monoid I have to satisfy both axioms: Presence of <em>identity element</em> and <em>Associativity</em>. As it turns out it will work out nicely:</p><ol><li>I am able to initialise empty aggregation — total number of elements of empty impression log is <em>0</em></li><li>I am able to calculate 2 subtotals and then combine them to calculate the final value — this is associative, so the order doesn’t matter</li></ol><p>This actually gets even more interesting because the very same Monoid abstraction is valid for whole range of other useful aggregations as we will show later.</p><p>—</p><p>Ok lets start some code. I will define a trait <em>Aggregateable:</em></p><pre>trait Aggregateable[I, O, S] {<br>  def init: S</pre><pre>  def lift(in: I): S</pre><pre>  def combine(left: S, right: S): S</pre><pre>  def unwrap(result: S): O<br>}</pre><p>It has <em>I, O, S</em> types, which represent our aggregation Input, Output and Storage. New Storage can be created with <em>init</em>, Input can be lifted to Storage with <em>lift(in: I): S</em>, two Storages can be combined with <em>combine(left: S, right: S): S</em> and finally we can get the Output value from Storage by calling <em>unwrap(result: S): O</em>.</p><p>This trait defines an interface, which can be implemented by various aggregations which can be later use by the common processing built around them.</p><p>Back to our total impressions we can define a <em>Counter</em>:</p><pre>object Counter extends Aggregateable[Seq[String], Long, Long] {<br>  def init = 0L</pre><pre>  def lift(in: Seq[String]): Long = in.size.toLong</pre><pre>  def combine(left: Long, right: Long): Long = left + right</pre><pre>  def unwrap(result: Long): Long = result<br>}</pre><p>which is quite straightforward.</p><p>I will also create a class <em>Aggregator</em> which will take <em>Agregateable</em> and provide several convenient methods on top of it:</p><pre>class Aggregator[I, O, S]<br>  (agg: Aggregateable[I, O, S], in: Option[S] = None) {<br>  private val underlying: S = in.getOrElse(agg.init)</pre><pre>  def add(in: I): Aggregator[I, O, S] = <br>    combine(underlying, agg.lift(in))</pre><pre>  def merge(other: this.type) = <br>    combine(underlying, other.underlying)</pre><pre>  def result: O = <br>    agg.unwrap(underlying)</pre><pre>  private def combine(left: S, right: S): Aggregator[I, O, S] =<br>    new Aggregator(agg, Some(agg.combine(left, right)))<br>}</pre><p>and use it as part of my Akka Stream application (but you can use it pretty much everywhere where you can fold over the sequence) to calculate total of UUIDs I will be loading from a file:</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(Counter)) { _ add _ }</pre><p>Here I am iterating over lines of a file, grouping them by 10k and running them through our Aggregator which now works as a <em>Counter</em>. The result is <em>39191737</em>, which is exact count of lines in the file. No surprise.</p><p>Lets try to calculate number of unique elements in the list. Here is our Aggregation:</p><pre><strong>object </strong>Unique <strong>extends </strong>Aggregateable[Seq[String], Long, Set[String]] {<br>  <strong>def </strong>init = <em>Set</em>.empty[String]<br><br>  <strong>def </strong>lift(in: Seq[String]): Set[String] = in.toSet<br><br>  <strong>def </strong>combine(left: Set[String], right: Set[String]): Set[String] =<br>    left ++ right<br><br>  <strong>def </strong>unwrap(result: Set[String]): Long = result.size<br>}</pre><p>using it as follows:</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(Unique)) { _ add _ }</pre><p>I can calculate unique count of cookies in my dataset — <em>9801125</em> in about 79.8s. Of course the above is rather naive way to go about it as the resource consumption is enormous (we will tackle this problem in the next post).</p><h4>Powerful combinations</h4><p>Lets go further, I might want to know what is an average of number of appearances per UUID in our set? We can calculate the average = total /distinct thus I can implement average on top of Counter and Unique:</p><pre><strong>case class </strong>Avg(unique: Set[String], total:Long)</pre><pre><strong>object </strong>Average <strong>extends </strong>Aggregateable[Seq[String], Double, Avg] {<br>  <strong>def </strong>init: Avg = <em>Avg</em>(Unique.<em>init</em>, Counter.<em>init</em>)<br><br>  <strong>def </strong>combine(left: Avg, right: Avg): Avg =<br>    <em>Avg</em>(Unique.<em>combine</em>(left.unique, right.unique), Counter.<em>combine</em>(left.total, right.total))<br><br>  <strong>def </strong>lift(in: Seq[String]): Avg =<br>    <em>Avg</em>(Unique.<em>lift</em>(in), Counter.<em>lift</em>(in))<br><br>  <strong>def </strong>unwrap(result: Avg): Double =<br>    result.unique.size.toDouble / result.total.toDouble<br>}</pre><p>Here I’ve created yet another Aggregateable which we can again use very easily in our Akka Stream:</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(Average)) { _ add _ }</pre><p>Nice! Soon you will find out how rich Aggregateable abstraction really is. I can for instance go ahead and implement its version reporting on pair of aggregations. Lets have a look at it:</p><pre>class Pair[I, O, O2, S, S2]<br>  (first: Aggregateable[I, O, S], second: Aggregateable[I, O2, S2]) <br>  extends Aggregateable[I, (O, O2), (S, S2)] {</pre><pre>  override def init: (S, S2) = <br>    (first.init, second.init)</pre><pre>  override def lift(in: I): (S, S2) = <br>    (first.lift(in), second.lift(in))</pre><pre>  override def combine(left: (S, S2), right: (S, S2)): (S, S2) = <br>    (first.combine(left._1, right._1), second.combine(left._2, right._2))</pre><pre>  override def unwrap(result: (S, S2)): (O, O2) = <br>    (first.unwrap(result._1), second.unwrap(result._2))<br>}</pre><p>Voila, now instead of Average I can get both Total and Distinct values from the stream with very little code changes.</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(new Pair(Counter, HLL)) { _ add _ }</pre><p>will yield a pair of 2 Longs — (39191737,9810035) which is the total and distinct count. Now, given I can do a pair, there is nothing preventing me to do pair of pairs or countess other aggregations which can be designed around the same abstraction. Handy, isn’t it?</p><h4>Conclusions</h4><p>I hope this was a nice exercise demonstrating real world application of power of Monoids. It is a very powerful abstraction which will allow me to calculate lots of other interesting aggregations — min value, max value, top N most occurring elements, etc. There is also nothing dictating I have to work with sequences of Strings, I am able to define various combinations of input / output / storage and all the surrounding code will hold which makes system very flexible for future requirements.</p><p>In the next post I will show another version of cardinality aggregation — this time using HyperLogLog approximations and will demonstrate how we can calculate number of unique elements in the set in much more efficient way, which can easily scale to 2⁶⁴ values with KBs of memory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbdc779ccd28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large scale cardinality calculations with probabilistic data structures in Scala]]></title>
            <link>https://petrjanda.medium.com/large-scale-cardinality-calculations-with-probabilistic-data-structures-in-scala-e7daef2fdc71?source=rss-93fb977b82bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7daef2fdc71</guid>
            <category><![CDATA[hyperloglog]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Petr Janda]]></dc:creator>
            <pubDate>Fri, 30 Oct 2015 16:16:56 GMT</pubDate>
            <atom:updated>2015-10-31T10:56:08.853Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of the article about aggregations on large scale datasets in Scala. If you didn’t read the <a href="https://medium.com/@petrjanda/large-scala-analytics-aggregations-with-monoids-in-scala-fbdc779ccd28">first part</a> I strongly encourage you to do so as I will continue on several thoughts and code examples from there.</p><h4>Cardinality aggregation</h4><p>One of the aggregations I’ve built last time is the number of unique elements in the impression log. The naive version from the last article:</p><pre><strong>object </strong>Unique <strong>extends </strong>Aggregateable[Seq[String], Long, Set[String]] {<br>  <strong>def </strong>init = <em>Set</em>.empty[String]<br><br>  <strong>def </strong>lift(in: Seq[String]): Set[String] = in.toSet<br><br>  <strong>def </strong>combine(left: Set[String], right: Set[String]): Set[String] =<br>    left ++ right<br><br>  <strong>def </strong>unwrap(result: Set[String]): Long = result.size<br>}</pre><p>and used as</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(Unique)) { _ add _ }</pre><p>calculated cardinality of <em>9801125</em> from 39.1M dataset in about 79.8s.</p><p>—</p><p>Now lets have a look at the memory. Just to clarify, our cookie id is 128-bit UUID value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*qmR--TCRzmxkAOo-2q7rkg.png" /><figcaption>Memory consumed by Unique aggregation to calculate number of distinct values</figcaption></figure><p>Ouch.</p><p>As you can see on the chart our algorithm is quite memory hungry. At the peak we got to ~2.8GB of used heap memory and we calculated “only” ~39.1M impressions. Now, imagine we have 1B. I think its fair assumption to expect that memory needed for the calculation is linear to the number of true unique values in the dataset — 2x increase of unique values will need about 2x more memory because the values need to be all present in the Storage set at the point before we fetch the result cardinality value.</p><h4>Approximations, is that ok?</h4><p>There are certainly markets, where you need exact numbers, but fortunately, in advertising we are able to get away with small amount of error (in the end cookies are far from 100% accurate anyway). It turns out there is convenient algorithm exactly for this purpose called HyperLogLog.</p><p>HyperLogLog is an algorithm for the count-distinct problem, approximating the number of distinct elements in a set. I wouldn’t spend too much effort explaining it in the detail — see <a href="https://highlyscalable.wordpress.com/2012/05/01/probabilistic-structures-web-analytics-data-mining/">this post</a> if you’re interested — , but let me elaborate on few particularly interesting attributes of HLL.</p><ul><li>You can construct empty HyperLogLog, which contains zero unique values</li><li>You can combine 2 HyperLogLogs and get the combined cardinality approximation (order of combinations doesn’t matter)</li></ul><p>Given these 2 attributes the HyperLogLog is a Monoid and will fit our <em>Aggregateable</em> interface nicely. Lets have a look.</p><pre><strong>object </strong>HLL <strong>extends </strong>Aggregateable[Seq[String], Long, HLLCounter] {<br>  <strong>def </strong>init = <strong>new </strong>HLLCounter(<strong>true</strong>)<br><br>  <strong>def </strong>lift(in: Seq[String]): HLLCounter = {<br>    <strong>val </strong>hll = init<br>    hll.put(in: _*)<br><br>    hll<br>  }<br><br>  <strong>def </strong>combine(left: HLLCounter, right: HLLCounter): HLLCounter = {<br>    <strong>val </strong>hll = init<br>    hll.combine(left)<br>    hll.combine(right)<br><br>    hll<br>  }<br><br>  <strong>def </strong>unwrap(result: HLLCounter): Long = result.size<br>}</pre><p>Again, I am accepting <em>Seq[String]</em> as input and producing <em>Long</em> — number of unique values as an output. I am using <em>com.adroll.cantor.HLLCounter</em> — Java implementation of <em>HyperLogLog</em> — as a Storage. <em>Note that I was able to use lift and combine methods to make our final aggregator immutable.</em></p><p>Using it is very simple. I just change one line in my current code:</p><pre>val res = Source(() =&gt; file.getLines)<br>  .grouped(10000)<br>  .runFold(new Aggregator(HLL)) { _ add _ }</pre><p>Boom! I am calculating number of unique values in a set of 39.1M lines very efficiently. I got <em>9810035</em> uniques at <em>55.4s</em>, which is about ~30% faster. Lets calculate an error: <em>9801125 / 9810035 = </em>0.9990917464. So we are 99.9% accurate. Quite good, isn’t it? And that’s not the main thing. Look at the memory consumption now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*WHJ0NsReRqe0t44oNbvEzA.png" /><figcaption>Memory consumed by Unique aggregation using HyperLogLog to calculate number of distinct values</figcaption></figure><p>We got away with ~180MB of memory! Its because everything is streamed, (beyond 10k UUIDs grouping, which is in my control) there is no buffering and no need to load everything into the memory. HyperLogLog itself consumes about 1.5kb which is negligible. I bet we can get even further, but the above is already just fine as if I scale the dataset to 1B with this solution not much, if anything, will change.</p><h4>Conclusions</h4><p>As you could see we were able to gain significant speedup and massive improvement in the resource consumption on our distinct count problem with the sacrifice of as little as 0.1% of accuracy. Now, that might not be ok for some use cases, but think about it next time, when you’re tasked to do a distinct count of anything. You know the cost of 100% accuracy. Is it really what you need?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7daef2fdc71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>