<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://waytoounoriginal.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://waytoounoriginal.github.io/" rel="alternate" type="text/html" /><updated>2026-09-27T17:39:40+00:00</updated><id>https://waytoounoriginal.github.io/feed.xml</id><title type="html">Yet-another-personal-blog</title><subtitle>Yet another &quot;another personal blog&quot;. Nothing special, I just hope to provide some stories about my engineering career, in a post-LLM era.</subtitle><entry><title type="html">On programming, statistics, and Java</title><link href="https://waytoounoriginal.github.io/programming/stats/optimizations/2026/09/26/on-programming-stats-and-java.html" rel="alternate" type="text/html" title="On programming, statistics, and Java" /><published>2026-09-26T00:00:00+00:00</published><updated>2026-09-26T00:00:00+00:00</updated><id>https://waytoounoriginal.github.io/programming/stats/optimizations/2026/09/26/on-programming-stats-and-java</id><content type="html" xml:base="https://waytoounoriginal.github.io/programming/stats/optimizations/2026/09/26/on-programming-stats-and-java.html"><![CDATA[<p><em>With love, to my dear girlfriend who loves my nerdiness</em></p>

<hr />

<p><small> <em>poof</em> </small></p>

<p>That’s the sound of this blog being born into existence, as this is the first post on it. It is also about the problem that gave me the idea to have a blog in the first place.</p>

<p>As the people coming from my LinkedIn might know, I am currently wrapping up my internship. It wasn’t the usual internship experience, though, in the sense that I did not have my own self-contained project, but rather I was part of <em>some “stabilisation initiative”</em> for an existing project.</p>

<p><small> <em>As a side note, I believe that me having to work on production systems has allowed me to truly enjoy this internship, and I hope more internships would take this approach. It also allowed me to see how fun it is to benchmark and see colorful lines go up and down!</em> </small></p>

<p>Coming back, I was part of a fairly small team, around 4.5 people (.5 because one person was active in two projects), so, honestly, work has felt more like a startup than a FAANG (or MAANG, MANGOS, GAYMAN, or whatever it will be next week). I basically had my cake and ate it too, since I had a rather large amount of ownership and freedom in my tasks.</p>

<p>Today I won’t focus on the boring parts (integration tests), but rather I want to tell you, my dear reader, about <strong>how my stats course finally mattered at the job, and about how much I hate Java</strong>.</p>

<hr />

<h1 id="context">Context</h1>
<p>The service I spent most of my time working on was a DataStore service. As the name says, it is about… <em>storing data</em>.</p>

<p>The initiative’s <em>(I will use this term for lack of a better one; I promise to not use corpo-speak too much 🤙)</em> goal for this service was <strong>scalability</strong>. How much scalability? How about <strong>being able to take on 1TB ingestions?</strong></p>

<p><em>I am trying to provide as little context as possible so that I don’t somehow violate my NDA, but the overarching project was working with regulatory data, and we had to ingest and store this data on our end</em></p>

<p>For context, from my measurements (<em>and previous <strong>refactoring and optimisation</strong> of the service</em>) we were able to ingest <strong>hundreds of GB*</strong>.</p>

<p>Now, let’s start with the interesting stuff!</p>

<p><small> * - This is extrapolated. The measurements were taken in the beta stage, where we had a container one-fourth the size of the production container. </small></p>

<hr />

<h1 id="the-problem">The problem</h1>
<p>Now, the main problem was that we were holding a <code class="language-plaintext highlighter-rouge">HashSet&lt;String&gt;</code> in memory for a later pass after the ingestions. We basically had something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>processed = Set()
for ingestion in input_data:

    // do stuff

    processed.add(ingestion.str_that_is_not_PK) // please pay attention to this str_that_is_not_PK!

    // do more stuff, also db.insert(ingestion)

for streamed_row in db.get_rows():

    if streamed_row.str_that_is_not_PK in processed:
        continue

    // do stuff
</code></pre></div></div>

<p><small> <em>There might have been a better arch, but I wasn’t going to overhaul already existent data, so I did what I could</em> </small></p>

<p>As you can probably see, the memory will grow in a <em>more or less</em> linear fashion. Saying more or less because there is also GC involved and whatnot.</p>

<hr />

<h1 id="1st-shot-at-optimizing">1st shot at optimizing</h1>
<p><em>At first (slight spoilers)</em> I believed that we were inserting the PK into the sets, which happened to be a SHA-256 <strong>string</strong>, meaning it had <strong>64 bytes instead of 32</strong>. I think you can also see where I attacked first!</p>

<p>In my naivety, retrospectively, I created a new class <code class="language-plaintext highlighter-rouge">HashedSHAKey</code>, which stored just 4 <code class="language-plaintext highlighter-rouge">long</code> variables. A <code class="language-plaintext highlighter-rouge">long</code> in Java is 8 bytes, so <code class="language-plaintext highlighter-rouge">8 x 4 = 32</code>, 50% of 64.</p>

<p><strong>Nice! We probably saved ~50% of the memory! We can pat ourselves on the back and call it a day!</strong> We could now scale to ~800GB, probably way above this project’s needs in this lifetime. Let’s just see what the tests say…</p>

<blockquote>
  <p><em>-18% in memory utilization…</em></p>
</blockquote>

<p><strong>What the f*#k??</strong> This does not make any sense. Let me prompt Claude to see what it can <em>hallucinate</em> <small> (and verify the claims myself, of course) </small>.</p>

<p><em>It seems that for every object in Java, an additional 12-16 bytes is allocated as the header of the object</em>. So for every <code class="language-plaintext highlighter-rouge">HashedSHAKey</code>, instead of 32 bytes, I had like 48. <em>That meant that I was using 50% more memory than I anticipated, meaning my upper bound was a 25% overall improvement</em>. With whatever shenanigans Java does under the hood for HashSet (<em>which, btw, IS significant for the memory overhead</em>), the math started mathing.</p>

<hr />

<h1 id="libraries--probabilities">Libraries &amp; probabilities</h1>
<p>I moved on to a different approach, and eyed this one library <em>with close to 0 overhead</em>, <strong>fastutil</strong>. There was one problem, though: <strong>there aren’t any 32-byte HashSet implementations, only 8-byte</strong>.</p>

<p>Now, narrowing <em>what I thought to be</em> full SHA-256 strings to 8 bytes seemed <strong>risky, to say the least</strong>. Thankfully, my mentor, who had a master’s in statistics, thought the same thing and prompted me to compute the <em>probabilities of false-positives in the narrowing case</em>.</p>

<p><em>This started a series of 3 days of a vicious cycle</em></p>
<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>               ┌────────────────────┐
               │                    │
               ▼                    │
┌─────────────────────────────┐     │
│  1. Computed something      │     │
└──────────────┬──────────────┘     │
               ▼                    │
┌─────────────────────────────┐     │
│  2. Got happy — result      │     │
│     seemed good             │     │
└──────────────┬──────────────┘     │
               ▼                    │
┌─────────────────────────────┐     │
│  3. Girlfriend doubted my   │     │
│     statistical competence  │     │
└──────────────┬──────────────┘     │
               ▼                    │
┌─────────────────────────────┐     │
│  4. Started double-guessing │     │
│     myself                  │     │
└──────────────┬──────────────┘     │
               ▼                    │
┌─────────────────────────────┐     │
│  5. Debated with the        │     │
│     hallucination machines  │     │
└──────────────┬──────────────┘     │
               │                    │
               └────────────────────┘
                    (loop forever)
</code></pre></div></div>
<p><br /></p>

<p>Ultimately I got sick of wondering whether to use the birthday formula <em>(my mentor put that thought in my head; didn’t even know what it was used for before)</em> or not, so I took my own approach.</p>

<p><strong>You can skip the math here if you’d like, but it is interesting!</strong></p>

<p>We are also taking the worst case scenario, in which we constantly add rows to our database.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Goal = 1TB
Avg. row size = 2KB

N = 500M
Precision = 64 (so 2^64 total possibilities)

M = # of iterations (the # will grow each run by N) = 0, 500M, 1B, 1.5B, ... = i * N

P(false-positive in 1 iteration) = 500M / 2^64 = q
P(no false-positive in 1 iteration) = 1 - q
P(no false-positive in 1 run of M_i iterations) = (1 - q) ^ M_i

P(no false-positives in all R runs) 
    = (1 - q)^0 * (1 - q)^500M * ... 
    = Product_i=0^R [ (1 - q)^i * N ]
    = (1 - q)^(N * (0 + 2 + ... + R - 1))
    = (1 - q)^(N * R * (R - 1) / 2)

</code></pre></div></div>

<p>Let’s say that an acceptable p of encountering at least 1 false positive in all R runs is 0.5:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0.5 = (1 - q)^(N * R * (R - 1) / 2)

&lt;=&gt;

ln(0.5) = N * R * (R - 1) / 2 * ln(1 - q)

&lt;=&gt;

2 * ln(0.5) / (N * ln(1 - q)) = R * (R - 1)
</code></pre></div></div>

<p>Since q is really small, we can approximate <code class="language-plaintext highlighter-rouge">ln(1 - q) = -q</code></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2 * ln(0.5) / (N * -q) = R^2 - R
</code></pre></div></div>

<p>Now we can replace N and q, solve for R and get…</p>

<blockquote>
  <p>R = 10 (approx)</p>
</blockquote>

<p>Wow, all this math only to find that, with the naive approach of having 1 set storing the first 8 bytes of the SHA256, we’d toss a coin on the 10th run already. <strong>This is bad</strong>.</p>

<p>Hmm, what if <em>instead of 1 set, we have <strong>2</strong>?</em> One for the first 8 bytes, another for the next 8 bytes. We’d need a false positive in both sets this way.</p>

<p>Doing the math again… <em>(truth be told I used a matlab script for this):</em></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>P(no false-positives in both sets) = P(no false-positives in the first set) * P(no false-positives in the second set)
</code></pre></div></div>
<p><sub>We will suppose we have independent probabilities for simplicity (and I hope it is the case as well in the real world…) </sub></p>

<figure class="highlight"><pre><code class="language-matlab" data-lang="matlab"><span class="n">N</span> <span class="o">=</span> <span class="mi">500000000</span><span class="p">;</span>
<span class="n">q</span> <span class="o">=</span> <span class="p">(</span><span class="n">N</span> <span class="p">/</span> <span class="mi">2</span><span class="o">^</span><span class="mi">64</span><span class="p">)</span><span class="o">^</span><span class="mi">2</span><span class="p">;</span>

<span class="n">x</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">*</span> <span class="nb">log</span><span class="p">(</span><span class="mf">0.5</span><span class="p">)</span> <span class="p">/</span> <span class="p">(</span><span class="n">N</span> <span class="o">*</span> <span class="nb">log1p</span><span class="p">(</span><span class="o">-</span><span class="n">q</span><span class="p">));</span>

<span class="n">R</span> <span class="o">=</span> <span class="nb">ceil</span><span class="p">((</span><span class="mi">1</span> <span class="o">+</span> <span class="nb">sqrt</span><span class="p">(</span><span class="mi">1</span> <span class="o">+</span> <span class="mi">4</span><span class="o">*</span><span class="n">x</span><span class="p">))</span> <span class="p">/</span> <span class="mi">2</span><span class="p">);</span>

<span class="nb">fprintf</span><span class="p">(</span><span class="s1">'Smallest run = %d\n'</span><span class="p">,</span> <span class="n">R</span><span class="p">);</span></code></pre></figure>

<p>Plugging this in gives us:</p>

<blockquote>
  <p>Smallest run = 1942642</p>
</blockquote>

<p>Honestly, if the math is right, and by absurd a 1TB ingestion would run each day, <strong>it vastly outlives this project</strong>.</p>

<p>Great! Time to run the test again aaand… Eureka! <strong>We got the expected 75% reduction in memory usage <small> <em>(excluding the first 2.3GB the container allocated)</em> </small></strong>!</p>

<p>The truth is, though, that when running a 400GB test on a single container (remember, production has four times as many containers as beta), I somehow got <strong>a ~10x reduction in memory</strong>, and I have absolutely no idea why. Claude hallucinated that it could be because of some GC shenanigans, but I have no idea. But nor do I care, since the result is better than what I hoped for.</p>

<p><img src="/res/math_paper.jpeg" alt="the 'napkin' math" width="50%" />
<small>Ugh, got the wrong approximation formula for ln(1-q) on the pic. Bummer…</small></p>

<hr />

<h1 id="final-sanity-check">Final sanity check</h1>
<p>Before checking everything off and putting the PR up for review, I decided to trust my gut and look again inside the code. <em>And yeah, remember when I said str_that_is_not_PK was a 64-character SHA-256 string?</em> <strong>It wasn’t.</strong> It could really be anything; I was confusing it with the PK for the past 3 days.</p>

<p>Now, were my efforts in vain? <strong>Not at all; with the set approach I was hashing the string to sha256 either way, so I was still working on the same probability space</strong>.</p>

<p>Phew, that scared me for a bit. Time to do this PR!</p>

<hr />

<h1 id="conclusions">Conclusions</h1>
<p>I believe that, by now, you can see why one might come to hate Java when it comes to certain things. There is no denying it is a good language for <em>some</em> things, but it is <strong>certainly not a good language if you have lots of small objects</strong>.</p>

<p>But aside from this, there is a really positive message behind all of this: <strong>math <em>can</em> matter</strong>. Yeah, sure, on a daily basis there are very few developers who are going to really need maths beyond simple computations. Now even less with the advent of LLMs, probably.</p>

<p>But man, oh man! How good it feels to solve problems again! I can say that for the past few days I’ve had the same feeling I had while programming in the pre-LLM era. <em>It felt GREAT</em>. I truly hope to have more such opportunities from now on!</p>

<p>But I believe that’s all for this post. Hopefully I did not bore you too much, dear reader.</p>

<p>‘Til we see again!</p>

<hr />

<h1 id="update-27092026">Update (27.09.2026)</h1>
<p>Since writing this article I’ve been reminded of this teeny tiny probabilistic data structure: <strong>Bloom Filters</strong>.</p>

<p>Honestly, I am not well-versed enough in using Bloom Filters, or computing the probabilities for them, but looking at the <a href="https://en.wikipedia.org/wiki/Bloom_filter">Wikipedia article for them</a>, we can see the following section:</p>

<h2 id="optimal-number-of-hash-functions">Optimal number of hash functions</h2>
<blockquote>
  <p>The number of hash functions, k, must be a positive integer. Putting this constraint aside, for a given m and n, the value of k that minimizes the false positive probability is
<code class="language-plaintext highlighter-rouge">k = m/n * ln(2)</code></p>
</blockquote>

<p>Where <code class="language-plaintext highlighter-rouge">m = the required number of bits</code>, <code class="language-plaintext highlighter-rouge">n = the number of inserted elements</code>. We are going to use <code class="language-plaintext highlighter-rouge">p = the FP (false-positive) probability desired</code>.</p>

<p>The same section does the math for us and gives us the formula for <code class="language-plaintext highlighter-rouge">m</code>:</p>
<blockquote>
  <p><code class="language-plaintext highlighter-rouge">m = -n * ln(p) / ln(2)^2</code></p>
</blockquote>

<p>Honestly, there has been enough math in this post, so we are just going to use <a href="https://hur.st/bloomfilter">this Bloom Filter calculator, made by Thomas Hurst</a>. Plugging in the same <code class="language-plaintext highlighter-rouge">(500M / 2^64)^2</code> probability we got for the 2-set approach:</p>

<blockquote>
  <p>k = 70
m = 5.9GB</p>
</blockquote>

<p>Technically, a Bloom Filter would take less space (not by a large margin), but instead of <strong>1</strong> hash, we would have <strong>70</strong> hashes.</p>

<p><em>Truth be told, these are the computations for the <strong>whole 128-bit space</strong> (or 2-choice 64-bit space) probabilities, <strong>not chosen for the project’s true needs</strong>. It’s very possible the project won’t ever need that level of precision, meaning the p chosen could be <strong>several orders of magnitude smaller</strong> (e.g. 1e-8, as an example).</em></p>

<p>Taking this into account, I believe the approach we settled on using might be the better one, but I’ll admit that I was wrong for not testing it beforehand. I promise to <em>try</em> to test it before the internship ends though!</p>]]></content><author><name></name></author><category term="programming" /><category term="stats" /><category term="optimizations" /><summary type="html"><![CDATA[With love, to my dear girlfriend who loves my nerdiness]]></summary></entry></feed>